<template>
  <div class="dialog">
    <el-dialog
      title="自定义模型"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="close"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <div class="modelTitle">
        <div class="siteCon">
          <span>分析模型名称:</span>
        </div>
        <el-input
          v-model="fxmxmc"
          size="mini"
          placeholder="请输入项目名称"
        ></el-input>
      </div>
      <el-row>
        <el-col :span="11">
          <div class="yztitle">请选择分析数据</div>
          <el-scrollbar class="left-tree">
            <el-input placeholder="输入查询内容" v-model="filterText" clearable>
            </el-input>
            <el-tree
              :data="options"
              :props="defaultProps"
              highlight-current
              show-checkbox
              node-key="id"
              ref="tree"
              :default-checked-keys="defaultArr"
              :filter-node-method="filterNode"
            ></el-tree>
          </el-scrollbar>
        </el-col>
        <el-col :span="2">
          <div class="grid-content bg_purple">
            <el-button
              icon="el-icon-d-arrow-right"
              @click="turnLeftToRight"
            ></el-button>
            <el-button
              icon="el-icon-d-arrow-left"
              @click="turnRightToLeft"
            ></el-button>
          </div>
        </el-col>
        <el-col :span="11">
          <div class="yztitle">已选数据</div>
          <el-table
            ref="multipleTable"
            :data="dialogData"
            border
            class="right-table scroll-style"
            size="small"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column prop="name" label="数据名称"> </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { GetFactorList } from "../../../api/ghss/gdbh.js";
export default {
  components: {},
  props: {
    tableData: {
      type: Array,
    },
    editData: {
      //editData用来存储编辑的数据,用bsm判断是否为编辑,全部存储是为了防止以后新增需求
      type: Object,
    },
  },

  data() {
    return {
      fxmxmc: "", //分析模型名称
      filterText: "", //树结构搜索关键字
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogVisible: false,
      options: [],
      kxyzList: [],
      tempList: [],
      optionsTemp: [],
      selectdialogData: [],
      dialogData: [],
      defaultArr: [], //用地类型选中后可选因子默认勾选的值
      yzTableData: [], //用地类型选中后影响因子对应的值
    };
  },
  computed: {},
  mounted() {
    this.GetFactorList();
  },
  methods: {
    //树结构过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    reset() {
      console.log(898888);
      this.$parent.templateYZ = [];
      this.filterText = ""; //还原分析数据搜索框
      this.fxmxmc = ""; //清空分析模型名称输入框
      this.yzTableData = [];
      this.GetFactorList(); //重新获取分析数据
      this.dialogData = []; //清空已选数据表单
      console.log(this.dialogData, "到货时间肯定会撒");
    },
    testInput(val) {
      val = Number(val);
    },
    close() {
      this.dialogVisible = false;
      this.reset();
    },
    GetFactorList() {
      GetFactorList().then((res) => {
        this.kxyzList = res.data;
        this.tempList = JSON.parse(JSON.stringify(res.data));
        this.getTreeList();
      });
    },

    getTreeList() {
      function arrayToTreeLoop(nodes) {
        const map = {};
        const tree = [];
        for (const node of nodes) {
          map[node.id] = { ...node, children: [] };
        }
        for (const node of Object.values(map)) {
          if (node.parentId == "") {
            tree.push(node);
          } else {
            map[node.parentId].children.push(node);
            map[node.parentId].parentNode = true;
          }
        }
        return tree;
      }
      this.options = arrayToTreeLoop(this.kxyzList);
      this.optionsTemp = JSON.parse(JSON.stringify(this.options));
    },

    setTable(selectdata) {
      let tableList = [];
      selectdata.forEach((item) => {
        tableList.push({
          id: item.id,
          name: item.name,
          bsm: item.bsm,
          // conditionInfo: JSONItem,
        });
      });
      tableList.forEach((item) => {
        this.resetTree(this.options, item);
      });
      this.removeChildrenZero(this.options);
      return tableList;
    },
    resetTree(data, item1) {
      data.forEach((item, index) => {
        if (item.id == item1.id) {
          data.splice(index, 1);
        }
        if (item.children != undefined && item.children.length != 0) {
          this.resetTree(item.children, item1);
        }
      });
    },

    removeChildrenZero(data) {
      data.forEach((item, index) => {
        if (item.children != undefined && item.children.length == 0) {
          if (item.parentNode) {
            item.disabled = true;
            if (this.$refs.tree) {
              //用地类型绑定后易出现找不到tree的情况
              this.$refs.tree.setCheckedKeys([]);
            }
          }
        }
        if (item.children != undefined && item.children.length > 0) {
          this.removeChildrenZero(item.children);
        }
      });
    },

    turnLeftToRight() {
      if (this.$refs.tree.getCheckedNodes().length == 0) {
        this.$message.warning("请勾选可选因子");
        return false;
      }
      let list = this.$refs.tree.getCheckedNodes().filter((item) => {
        return item.children == undefined || item.children.length == 0;
      });
      list = this.setTable(list);
      this.dialogData = [...this.dialogData, ...list];
    },
    turnRightToLeft() {
      if (this.selectdialogData.length == 0) {
        this.$message.warning("请勾选已选因子");
        return false;
      }
      let list = this.dialogData;
      this.selectdialogData.forEach((item) => {
        list = list.filter((item1) => {
          return item.id != item1.id;
        });
      });
      this.dialogData = list; //去掉勾选元素

      this.options = JSON.parse(JSON.stringify(this.optionsTemp));
      list.forEach((item) => {
        this.resetTree(this.options, item);
      });
      if (this.$refs.tree) this.$refs.tree.setCheckedKeys([]);
    },
    handleSelectionChange(val) {
      this.selectdialogData = val;
    },
    submit() {
      let saveData = {
        bsm: new Date().getTime(),
        bsmmc: this.fxmxmc,
        gdbhMxYzRet: this.dialogData,
      };
      if (this.editData.bsm) {
        //判断是否为编辑状态
        this.$parent.anaModels.forEach((item) => {
          if (item.bsm == this.editData.bsm) {
            this.$parent.anaModels[item] = saveData; //替换数据
          }
        });
        this.dialogVisible = false;
      } else {
        this.$parent.anaModels.push(saveData);
        this.dialogVisible = false;
      }
      this.$refs.multipleTable.clearSelection();//清空勾选
    },
    setData(data) {
      data.filter((item) => {
        this.clearitem(item);
      });
    },
    clearitem(item) {
      this.options[0].children = this.options[0].children.filter((item1) => {
        return item.id != "";
      });
      this.options[1].children = this.options[1].children.filter((item1) => {
        return item.id != ""; //item1.defaultValue
      });
      this.options[0].children.length == 0
        ? (this.options[0].disabled = true)
        : (this.options[0].disabled = false);
      this.options[1].children.length == 0
        ? (this.options[1].disabled = true)
        : (this.options[1].disabled = false);
    },
    resetDialogData() {
      if (!this.tableData.length) {
        // 重置时，树的数据恢复
        this.dialogData = [];
        this.options = JSON.parse(JSON.stringify(this.optionsTemp));
        this.selectdialogData = [];
      } else {
        // 选择模板时，生成新的树
        this.dialogData = JSON.parse(JSON.stringify(this.tableData));
        this.options = JSON.parse(JSON.stringify(this.optionsTemp));
      }
      this.dialogData.forEach((item) => {
        this.resetTree(this.options, item);
      });
      this.removeChildrenZero(this.options);
      return this.dialogData;
    },
  },
  watch: {
    //监听树结构过滤的关键字
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    // dialogVisible(oldVal, newVal) {
    //   if (newVal) this.resetDialogData();
    // },
    yzTableData(oldVal, newVal) {
      let idArr = [];
      this.yzTableData.forEach((item) => {
        idArr.push(item.id);
      });
      this.defaultArr = idArr;
      this.resetDialogData();
    },
  },
};
</script>

<style lang="scss" scoped>
.hgxsc {
  height: 100%;
}

.yztitle {
  color: #fff !important;
}

.dialog {
  /deep/.el-dialog__body {
    color: #fff !important;
  }

  .left-tree {
    height: 400px;
    overflow-y: auto;
    margin-top: 10px;
    border: 1px solid #ddd;

    .el-tree {
      margin-top: 10px;

      .el-tree-node__content {
        height: 35px;
        line-height: 35px;
      }
    }
  }

  /deep/.el-dialog__body {
    padding: 10px 30px;
  }

  .bg_purple {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400px;

    .el-button + .el-button {
      margin-left: 0;
      margin-top: 20px;
    }
  }

  .right-table {
    margin-top: 10px;
    height: 400px;
    overflow: hidden;
    overflow-y: auto;

    /deep/ .el-table__inner-wrapper {
      height: 100%;
    }

    /deep/.el-table__header-wrapper,
    .el-table__header {
      height: 40px;
    }

    /deep/.el-table__body-wrapper {
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
}

/deep/.el-dialog__body {
  color: #fff !important;
}

/* 去除Element UI中el-input数字类型的样式 */
/deep/ .el-input__inner[type="number"] {
  -webkit-appearance: none;
  /* 移除系统默认的外观样式 */
}

/* 去除增加/减少数字按钮的样式 */
/deep/ .el-input__inner[type="number"]::-webkit-inner-spin-button,
.el-input__inner[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  /* 移除输入框两侧的上下箭头 */
  margin: 0;
  /* 移除上下箭头与文本之间的间隔 */
}

/* 去除Firefox浏览器中的一些特定样式 */
/deep/ .el-input__inner[type="number"]::-moz-inner-spin-button {
  -moz-appearance: none;
  /* 移除Firefox中的上下箭头 */
}

.clearBtn {
  padding: 12px 20px;
  border-radius: 4px;
  cursor: pointer;
  width: 30%;
  background-color: #3f94f53f;
  border: 1px solid #3f93f5;
  color: #b6e0ff;

  &:hover {
    font-weight: bold;
  }
}

.modelTitle {
  color: #fff;

  /deep/ .el-input__inner {
    max-width: 100%;
    color: #fff;
    background: #041c3273 !important;
    border: 1px dashed #0f7ac8 !important;
  }

  width: 100%;
  height: 40px;
  color: #fff;
  font-weight: 400;
  font-size: 16px;
  display: flex;
  justify-content: space-between;

  .siteCon {
    width: 140px;
    display: flex;
    justify-content: flex-start;

    span {
      display: inline-block;
    }
  }
}
</style>