<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"
    >
      <el-row>
        <el-col :span="6">
          <div class="yztitle">可选因子</div>
          <el-scrollbar class="left-tree">
            <el-tree
              :data="options"
              :props="defaultProps"
              highlight-current
              show-checkbox
              node-key="id"
              ref="tree"
              :default-checked-keys="defaultArr"
            ></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="16">
          <div class="yztitle">已选因子</div>
          <el-table
            :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-column prop="conditionInfo" label="条件" width="150">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.conditionInfo.default"
                  placeholder="请选择"
                  class="input-style"
                >
                  <el-option
                    v-for="item in scope.row.conditionInfo.items"
                    :key="item.key"
                    :label="item.name"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="defaultValue"
              label="约束值(m/°)"
              width="120"
            >
              <template slot-scope="scope">
                <el-input
                  Onkeyup="this.value=this.value.replace(/[^\d^\.]+/g,'').replace(/^0+(\d)/,'$1').replace(/^\./,'0.').match(/\d+.?\d{0,2}/);this.dispatchEvent(new Event('input'))"
                  v-model.number="scope.row.conditionInfo.defaultValue"
                  placeholder="距离"
                  class="input-style font-14"
                  :disabled="!scope.row.conditionInfo.hasValue"
                  type="number"
                  @input="testInput(scope.row.conditionInfo.defaultValue)"
                ></el-input>
                <!-- :disabled="scope.row.condition == 'F'" -->
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <span class="clearBtn" @click="submit(true)">保存至模板</span>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="submit(false)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  GetFactorList,
  AddTemplate,
  DelTemplate,
} from "../../../api/ghss/ghxz.js";
export default {
  components: {},
  props: {
    tableData: {
      type: Array,
    },
  },

  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogVisible: false,
      options: [],
      kxyzList: [],
      tempList: [],
      optionsTemp: [],
      selectdialogData: [],
      dialogData: [],
      defaultArr: [], //用地类型选中后可选因子默认勾选的值
      yzTableData: [], //用地类型选中后影响因子对应的值
    };
  },
  computed: {},
  mounted() {
    this.GetFactorList();
  },
  methods: {
    save(factors) {
      AddTemplate({ landTypeCode: this.$parent.ydlxBSM, factors }).then(
        (res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$parent.GetTemplateFactorList(this.$parent.ydlxBSM);
          }
        }
      );
    },
    reset() {
      DelTemplate({ landTypeCode: this.$parent.ydlxBSM }).then((res) => {
        if (res.success) {
          this.$parent.GetTemplateFactorList(this.$parent.ydlxBSM);
        }
      });
    },
    testInput(val) {
      val = Number(val);
    },
    close() {
      this.dialogVisible = false;
    },
    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.parent_id == "") {
            tree.push(node);
          } else {
            map[node.parent_id].children.push(node);
            map[node.parent_id].parentNode = true;
          }
        }
        return tree;
      }
      this.options = arrayToTreeLoop(this.kxyzList);
      this.optionsTemp = JSON.parse(JSON.stringify(this.options));
    },

    getList() {
      // yzlist().then((res) => {
      //   if (res.success) {
      this.tempList.forEach((item) => {
        var num = item.lx == "FZXZ01" ? 0 : item.lx == "FZXZ02" ? 1 : 2;
        this.options[num].children.push({
          type: num,
          value: item.bsm,
          label: item.yxyzmc,
          sjlx: item.sjlx,
          yztj: item.yztj,
          sjy: item.sjy,
        });
      });
      this.optionsTemp = JSON.parse(JSON.stringify(this.options));
      // }
      // });
    },

    setTable(selectdata) {
      let tableList = [];
      selectdata.forEach((item) => {
        let JSONItem = JSON.parse(item.conditionInfo);
        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;
      }
      // this.dialogData = [];
      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);
      });
    },
    handleSelectionChange(val) {
      this.selectdialogData = val;
      console.log(val, "这是什么");
    },
    submit(issave) {
      var sign = true;
      let saveData = [];
      this.dialogData.forEach((item) => {
        item.type && item.value == "" && (sign = false);
        issave &&
          saveData.push({
            ...item,
            conditionInfo: JSON.stringify(item.conditionInfo),
          });
      });
      if (sign) {
        if (issave) {
          this.save(saveData);
        } else {
          this.$parent.tableData = this.dialogData;
          this.dialogVisible = false;
        }
      } else {
        this.$message.warning("请将信息补充完整！");
      }
    },
    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.setData(this.dialogData);
      }
      if (this.defaultArr.length) {
        this.dialogData.forEach((item) => {
          this.resetTree(this.options, item);
        });
        this.removeChildrenZero(this.options);
        return this.dialogData;
      }
    },
  },
  watch: {
    dialogVisible(oldVal, 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;
  }
}
</style>