<template>
  <el-dialog
    :title="modelTitle ? modelTitle : '自定义模型'"
    :visible.sync="outerDialogVisible"
    width="750px"
    center
  >
    <el-dialog
      title="请输入模型名称"
      width="20%"
      :visible="innerDialogVisible"
      append-to-body
      center
      ><div class="model-name">
        <div class="model-name-title">名称 :</div>
        <el-input v-model="inputName" placeholder="请输入模型名称"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm()">确认</el-button>
      </span>
    </el-dialog>
    <div class="transfer-container">
      <div class="transfer-container-left">
        <div class="search">
          <el-input
            v-model="filterText"
            placeholder="请输入搜索内容"
          ></el-input>
        </div>
        <div class="tree">
          <el-tree
            :default-expanded-keys="checkedList"
            :data="transferData"
            :props="defaultProps"
            @check-change="transferCheckChange"
            ref="transferTree"
            node-key="id"
            :filter-node-method="filterNode"
          >
            <span class="custom-tree-node" slot-scope="{ node }">
              <template
                v-if="
                  node.data.mainType === '所有图层' ||
                  node.data.mainType === '预设模型'
                "
              >
                <el-checkbox v-model="node.checked" style="position: relative"
                  >{{ node.label }}
                </el-checkbox>
              </template>
              <template v-else>
                <div
                  :class="{
                    'tree-arrow': !node.expanded,
                    'tree-arrow-expanded': node.expanded,
                  }"
                ></div>
                <span>{{ node.label }}</span>
              </template>
            </span>
          </el-tree>
        </div>
      </div>
      <div class="transfer-container-center">
        <div class="inner">
          <el-tooltip
            effect="light"
            :content="
              isLeftTransferBtn ? '移除不需要的图层' : '不可进行移除操作'
            "
            placement="top-end"
          >
            <el-button
              size="normal"
              type="primary"
              icon="el-icon-arrow-left"
              @click="deleteCheckList"
              id="leftArrowBtn"
              class="inner-left"
              :class="{ 'allow-cursor': isLeftTransferBtn }"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            effect="light"
            :content="isRightTransferBtn ? '添加选中图层' : '不可进行添加操作'"
            placement="top-end"
          >
            <el-button
              size="normal"
              type="primary"
              icon="el-icon-arrow-right"
              @click="addCheckList"
              class="inner-right"
              :class="{ 'allow-cursor': isRightTransferBtn }"
            ></el-button>
          </el-tooltip>
        </div>
      </div>
      <div class="transfer-container-right">
        <el-checkbox-group v-model="checkedList">
          <div class="inner-group" v-for="item in checkArr" :key="item">
            <el-checkbox :key="item" :label="item"></el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>
    <div
      v-if="overlayBtnShow"
      class="overlay-container"
      :class="{ forbidden: forbidOverlayBtn }"
      @click="executeOverlay"
    >
      <div
        class="overlay-container-icon"
        :class="{ checked: overlayBtnChecked }"
      ></div>
      <div
        class="overlay-container-btn"
        :class="{ checked: overlayBtnChecked }"
      >
        叠置分析
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="clearDialogVisible()">取 消</el-button>
      <el-button type="primary" @click="saveModel()">保存模型</el-button>
    </span>
  </el-dialog>
</template>
<script>
import publicFun from "@/utils/publicFunction.js";
/**
 * 底部菜单（自定义模型）组件
 * @author: Gao Lu
 * @Date: 2022.11.22
 */
export default {
  name: "CustomModelDialog",
  components: {},
  data() {
    return {
      uploadBaseUrl: "/dms",
      classTextToIndex: {},
      overlayBtnChecked: false,
      outerDialogVisible: false,
      innerDialogVisible: false,
      overlayBtnShow: false,
      modelTitle: null,
      inputName: "自定义模型1",
      checkArr: [],
      checkedList: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      transferData: [],
      filterText: "",
      createModelParams: {
        title: "",
        content: "",
        // 叠置分析geojson附件
        // c_dzfx_file: "",
        // 类型 -- 公开：1; 私人: 0
        c_level: "1",
        // 是否叠置分析
        c_isOverlay: false,
        // 绑定图层（json图层数组）
        c_bind_layer: "",
        // 用户id
        c_user_id: "",
      },
      checkedKeysArr: [],
      isLeftTransferBtn: false,
      isRightTransferBtn: false,
      allowStyle: {
        cursor: "not-allowed",
      },
      notAllowedStyle: {
        cursor: "pointer",
      },
      currentModifiedModelId: "",
      currentOverlayFile: "",
      forbidOverlayBtn: "",
    };
  },
  watch: {
    checkedKeysArr: {
      handler(val) {
        if (val.length === 0) {
          this.isRightTransferBtn = false;
        }
        if (val.length > 0) {
          this.isRightTransferBtn = true;
        }
      },
      immediate: true,
    },
    checkedList(val) {
      let btn = document.getElementById("leftArrowBtn");
      if (btn) {
        if (val.length === this.checkArr.length) {
          this.isLeftTransferBtn = false;
        }
        if (val.length < this.checkArr.length) {
          this.isLeftTransferBtn = true;
        }
      }

      // console.log(val, "checkedList");
    },
  },
  created() {
    this.checkedKeysArr = [];
    this.getColumnList();
    // DMS - 任务类型
    // 水资源审计 - 2；林地资源审计 - 3；生态资源审计 - 4； 土地资源审计 - 1
    this.classDictQuery("0", "c_task_type", "任务类型");
    // DMS - 浦东行政区划
    this.classDictQuery("0", "浦东新区行政区划", "浦东新区行政区划");
  },
  mounted() {
    // 监听自定义模型
    this.$bus.$off("customModelEvent");
    this.$bus.$on("customModelEvent", () => {
      this.customModelEvent();
    });

    // 监听模型修改事件
    this.$bus.$off("updateModel");
    this.$bus.$on("updateModel", (node) => {
      // console.log("监听模型中");
      this.overlayBtnChecked = false;
      // console.log(node, "节点数据");
      if (node.data.c_dzfx_file) {
        // console.log("已有叠置分析结果");
        this.forbidOverlayBtn = true;
      }

      if (!node.data.c_dzfx_file) {
        // console.log("未进行叠置分析");
        this.forbidOverlayBtn = false;
      }
      this.currentModifiedModelId = node.data.id;
      this.currentOverlayFile = node.data.c_dzfx_file;
      // console.log(this.currentModifiedModelId, "currentModifiedModelId");
      // console.log(this.currentOverlayFile, "currentOverlayFile");

      this.$nextTick(() => {
        if (this.$refs.transferTree) {
          this.$refs.transferTree.setCheckedKeys([]);
        }
      });
      this.checkedKeysArr = [];
      this.checkArr = [];
      this.checkedList = [];
      this.outerDialogVisible = true;
      if (node.data.c_bind_layer) {
        let bindLayerArr = JSON.parse(node.data.c_bind_layer);
        // console.log(bindLayerArr, "c_bind_layer");
        if (bindLayerArr.length > 0) {
          this.checkArr = bindLayerArr;
          this.checkedList = bindLayerArr;
          this.checkedKeysArr = bindLayerArr;
          this.$nextTick(() => {
            if (this.$refs.transferTree) {
              this.$refs.transferTree.setCheckedKeys(this.checkedList);
            }
          });
        }
      }
      // this.checkedList = node.data.data;
      this.inputName = node.data.label;
      this.overlayBtnShow = true;
      this.modelTitle = node.data.label;
      this.$store.state.modelStatus = "modify";
    });
  },
  beforeDestroyed() {
    // 当容器销毁时，需要停止监听该事件
    this.$bus.$off("customModelEvent");
    this.$bus.$off("updateModel");
    this.overlayBtnShow = false;
  },
  methods: {
    classDictQuery(type, cName, keyName) {
      let params = new FormData();
      params = {
        type: type,
        cName: cName,
      };
      this.$Post(this.urlsCollection.selectByCNameAType, params).then((res) => {
        if (res.code === 200 && res.content.length > 0) {
          this.classTextToIndex[keyName] = new Map();
          res.content.forEach((v) => {
            this.classTextToIndex[keyName].set(v.name, v.index + "");
          });
          // console.log(this.classTextToIndex[keyName], keyName);
        }
      });
    },
    getColumnList() {
      this.transferData = [];
      this.$Post(this.urlsCollection.getColumnList).then((res) => {
        if (res.code === 200 && res.content.length > 0) {
          let data = res.content.map((item1) => {
            if (item1.title === "所有图层" && item1.columnList.length > 0) {
              return {
                id: `${item1.title}_${item1.id}`,
                label: item1.title,
                // 镇
                children:
                  item1.columnList.length === 0
                    ? []
                    : item1.columnList.map((item2) => {
                        return {
                          id: `${item2.title}_${item2.id}`,
                          label: item2.title,
                          // 水资源，土地资源，林地资源
                          children:
                            item2.columnList.length === 0
                              ? []
                              : item2.columnList.map((item3) => {
                                  return {
                                    id: `${item3.title}_${item3.id}`,
                                    label: item3.title,
                                    tag: item3.tag,
                                    children:
                                      item3.columnList.length === 0
                                        ? []
                                        : item3.columnList.map((item4) => {
                                            return {
                                              id: `${item4.title}_${item4.id}`,
                                              label: item4.title,
                                              children: [],
                                              columnId: item4.id,
                                              modelName: item4.modelName,
                                              modelId: item4.modelId,
                                              tag: item4.tag,
                                              type: item3.title,
                                              town: item2.title,
                                              mainType: item1.title,
                                            };
                                          }),
                                  };
                                }),
                        };
                      }),
              };
            }
            if (item1.title === "预设模型" && item1.columnList.length > 0) {
              return {
                id: `${item1.title}_${item1.id}`,
                label: item1.title,
                children:
                  item1.columnList.length === 0
                    ? []
                    : item1.columnList.map((item2) => {
                        return {
                          id: `${item2.title}_${item2.id}`,
                          label: item2.title,
                          children:
                            item2.columnList.length === 0
                              ? []
                              : item2.columnList.map((item3) => {
                                  return {
                                    id: `${item3.title}_${item3.id}`,
                                    label: item3.title,
                                    children: [],
                                    mainType: item1.title,
                                    columnId: item3.id,
                                  };
                                }),
                        };
                      }),
              };
            }
          });

          data.forEach((c) => {
            if (c) {
              this.transferData.unshift(c);
            }
          });
        }
      });
    },
    transferCheckChange(data, checked) {
      if (data.mainType === "预设模型" || data.mainType === "所有图层") {
        if (checked) {
          if (!this.checkedKeysArr.includes(data.id)) {
            this.checkedKeysArr.push(data.id);
          }

          // 判断图层是否有权限
          if (data.mainType === "所有图层") {
            let searchParam = [];
            let targetTown = this.classTextToIndex["浦东新区行政区划"].get(
              data.town
            );
            let targetType = this.classTextToIndex["任务类型"].get(
              data.type + "审计"
            );
            let paramUser = {
              field: "c_user_id",
              searchType: "2",
              content: {
                value: localStorage.getItem("USER_ID"),
              },
            };
            searchParam.push(paramUser);
            let paramTown = {
              field: "c_area_code",
              searchType: "1",
              content: {
                value: targetTown,
              },
            };
            searchParam.push(paramTown);
            let paramType = {
              field: "c_task_type",
              searchType: "1",
              content: {
                value: targetType,
              },
            };
            searchParam.push(paramType);
            let params = new FormData();
            // dms - 我的任务
            params = {
              columnId: 48,
              states: "2,3",
              pageSize: 10,
              page: 0,
              search: JSON.stringify(searchParam),
            };
            this.$Post(this.urlsCollection.selectContentList, params)
              .then((res) => {
                if (res.code === 202 && res.content === "数据不存在") {
                  this.$message.info("当前图层无权限!");
                  layerAuthorityMap.set(data.id, "无权限");
                }
                if (res.code === 200 && res.content.data.length > 0) {
                  layerAuthorityMap.set(data.id, "有权限");
                  // console.log("有权限");
                }
              })
              .catch((err) => {
                console.log(err, "接口请求失败，我的任务 - selectContentList");
              });
          }

          if (data.mainType === "预设模型") {
            layerAuthorityMap.set(data.id, "有权限");
          }
        } else {
          if (this.checkedKeysArr.includes(data.id)) {
            this.checkedKeysArr = this.checkedKeysArr.filter((v) => {
              return v !== data.id;
            });
          }
        }
      }
    },
    // 添加模型
    addModel() {
      // 设置需要添加的参数
      this.createModelParams.title = this.inputName;
      this.createModelParams.content = this.inputName;
      this.createModelParams.c_user_id = localStorage.getItem("USER_ID") || 4;

      let newData = this.checkedList.filter((v) => {
        if (layerAuthorityMap.has(v) && layerAuthorityMap.get(v) === "有权限") {
          return v;
        }
      });
      // console.log(newData, "可以进行叠置分析的图层");

      this.createModelParams.c_bind_layer = JSON.stringify(newData);
      let params = new FormData();
      params = {
        columnId: 49,
        modelId: 53,
        content: JSON.stringify(this.createModelParams),
      };
      this.$Post(this.urlsCollection.addContent, params)
        .then((res) => {
          // console.log(res, "保存自定义模型的res");
          if (res.code === 200) {
            this.$message.success("模型已保存");
            this.$store.state.customModelsArr.push({
              name: this.inputName,
              data: this.checkedList,
            });
            this.clearDialogVisible();
          }
        })
        .catch(() => {
          this.$message.info("模型保存失败");
        });
    },
    // 修改模型 -- 直接调用修改模型接口
    modifyModel(type, bindData) {
      // console.log("这一步是修改模型");

      // console.log(this.currentModifiedModelId, "model id");
      let obj = {
        id: this.currentModifiedModelId,
        title: this.inputName,
        content: this.inputName,
        c_level: "1",
        c_bind_layer: JSON.stringify(bindData),
        c_user_id: localStorage.getItem("USER_ID"),
      };
      let modifyParams = new FormData();
      modifyParams = {
        columnId: 49,
        modelId: 53,
        content: JSON.stringify(obj),
      };
      this.$Post(this.urlsCollection.updateContent, modifyParams).then(
        (res) => {
          if (res.code === 200) {
            this.$store.state.customModelsArr.filter((v) => {
              return v.name !== this.inputName;
            });
            this.$store.state.customModelsArr.push({
              name: this.inputName,
              data: bindData,
            });
            this.clearDialogVisible();
            if (type === "alreadyOverlay") {
              this.$message.success("系统已完成叠置分析,数据已保存!");
            }

            if (type === "notOverlay") {
              this.$message.success("模型修改成功");
            }
          }
        }
      );
    },
    deleteCheckList() {
      if (
        this.checkedList.length < this.checkArr.length &&
        this.isLeftTransferBtn
      ) {
        this.checkArr = this.checkedList;
        this.isLeftTransferBtn = false;
      }
    },
    addCheckList() {
      this.$nextTick(() => {
        if (this.$refs.transferTree) {
          this.checkArr = [];
          this.checkedList = [];
          this.checkArr = this.checkedKeysArr;
          this.checkedList = this.checkedKeysArr;
        }
      });
    },
    // 节点过滤事件
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 弹窗关闭时询问
    handleClose() {
      // if (this.outerDialogVisible) {
      //   this.$confirm("").then(() => {
      //     this.clearDialogVisible();
      //   });
      // }
    },
    clearDialogVisible() {
      this.outerDialogVisible = false;
      this.innerDialogVisible = false;
    },
    // 底部按钮自定义模型事件
    customModelEvent() {
      this.$nextTick((e) => {
        if (this.$refs.transferTree) {
          this.$refs.transferTree.setCheckedKeys([]);
        }
      });
      this.modelTitle = null;
      this.overlayBtnShow = false;
      this.$store.state.modelStatus = "create";
      this.outerDialogVisible = true;
      // console.log(this.$store.state.treeDataCollection, "treeDataCollection");
      this.checkedList = [];
      this.checkArr = [];
      // this.transferCheckedKeys = [];
      if (this.$store.state.treeDataCollection.size > 0) {
        this.$store.state.treeDataCollection.forEach((v, i) => {
          this.checkArr.push(i);
          this.checkedList.push(i);
        });
        this.$nextTick((e) => {
          // console.log(this.$refs.transferTree, "this.$refs.transferTre");
          this.$refs.transferTree.setCheckedKeys(this.checkedList);
        });
      }

      this.inputName = "自定义模型1";
    },
    saveModel() {
      if (this.checkedList.length < 2) {
        this.$message.info("请至少选择两个类型!");
      } else {
        if (this.$store.state.modelStatus === "create") {
          this.innerDialogVisible = true;
        } else {
          this.confirm();
        }
      }
    },
    confirm() {
      this.$confirm("确认保存吗?").then(() => {
        // modify -- 改变数组类型
        if (this.$store.state.modelStatus === "modify") {
          let newData = this.checkedList.filter((v) => {
            if (
              layerAuthorityMap.has(v) &&
              layerAuthorityMap.get(v) === "有权限"
            ) {
              return v;
            }
          });
          this.modifyModel("notOverlay", newData);
        }

        // console.log(this.$store.state.customModelsArr, "先获取的模型数据");
        // create -- 创建新的数组
        if (this.$store.state.modelStatus === "create") {
          this.addModel();
        }
      });
    },
    // 呈现叠置分析的数据
    displayOverlayGeometry(url) {
      // console.log(url);
      this.$Get(url).then((res) => {
        // console.log(res, "叠置分析的结果数据");
      });
    },
    // 执行叠置分析
    executeOverlay() {
      this.overlayBtnChecked = !this.overlayBtnChecked;
      if (this.overlayBtnChecked && !this.forbidOverlayBtn) {
        // 进行叠置分析后，叠置分析结果会自动保存
        // 当前勾选的图层并未自动保存，需要重新调用一次保存接口
        let newData = this.checkedList.filter((v) => {
          if (
            layerAuthorityMap.has(v) &&
            layerAuthorityMap.get(v) === "有权限"
          ) {
            return v;
          }
        });
        let bindLayer = newData.join(",");
        let tagretUrl = `${this.urlsCollection.overlayAnalysis}?modelId=${this.currentModifiedModelId}&bindLayer=${bindLayer}`;
        this.$Get(tagretUrl).then((res) => {
          if (res.code === 200) {
            let address = this.uploadBaseUrl + res.content;
            this.displayOverlayGeometry(address);
            this.modifyModel("alreadyOverlay", newData);
          }
        });
      }
    },
  },
};
</script>
<style lang="less" scoped>
@commonBorderColor: rgb(0, 170, 255);
.model-name {
  // pointer-events: auto;
  width: 100%;
  height: 100%;
  display: flex;
  &-title {
    width: 30%;
    height: 100%;
    color: #fff;
    font-size: 18px;
    line-height: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .el-input {
    width: 70%;
  }
}
.transfer-container {
  width: 700px;
  height: 330px;
  position: relative;
  margin: 0 auto;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  &-left {
    width: 270px;
    height: 320px;
    border: 1px solid @commonBorderColor;
    border-radius: 5px;
    .search {
      width: 240px;
      height: 40px;
      position: absolute;
      left: 17px;
      top: 10px;
    }
    .tree {
      width: 240px;
      height: calc(90% - 40px);
      position: absolute;
      top: 60px;
      left: 10px;
      // border: 1px solid peachpuff;
      overflow: auto;
      .tree-arrow {
        position: relative;
        top: 0;
        left: 0;
        display: inline-block;
        width: 0px;
        height: 0px;
        border: 7px solid transparent;
        border-left-color: #fff;
      }
      .tree-arrow-expanded {
        position: relative;
        top: 4px;
        left: -3px;
        display: inline-block;
        width: 0px;
        height: 0px;
        border: 7px solid transparent;
        border-top-color: #fff;
      }
      .custom-tree-node {
        position: relative;
        width: 250px;
        // .el-checkbox {
        //   width: 50%;
        // }
        .el-checkbox {
          width: 50%;
          color: #fff;
          /deep/.el-checkbox__input.is-checked + .el-checkbox__label {
            color: rgba(116, 255, 255, 1);
          }

          /deep/.el-checkbox__input.is-checked .el-checkbox__inner::after {
            width: 70%;
            height: 70%;
            background: #74ffff;
            border-radius: 0;
            transform: rotate(0deg) scaleY(1);
            position: static;
          }

          /deep/.el-checkbox__inner {
            border: 1px solid #dcdfe6;
            background: rgba(0, 170, 255, 0);
            display: flex;
            align-items: center;
            justify-content: center;
            position: static;
            &::after {
              transition: 0ms;
            }
          }

          /deep/.el-checkbox__label {
            padding-left: 0;
            font-size: 15px;
            position: absolute;
            top: 1px;
            left: 25px;
          }
        }
      }
    }
  }
  &-center {
    width: 150px;
    height: 320px;
    // border: 1px solid yellow;
    display: flex;
    align-items: center;
    justify-content: center;
    .inner {
      // border: 1px solid black;
      width: 150px;
      height: 30%;
      display: flex;
      align-items: center;
      justify-content: space-around;
      .inner-left {
        cursor: not-allowed;
        &.allow-cursor {
          cursor: pointer;
        }
      }
      .inner-right {
        cursor: not-allowed;
        &.allow-cursor {
          cursor: pointer;
        }
      }
    }
  }
  &-right {
    width: 270px;
    height: 320px;
    border: 1px solid @commonBorderColor;
    border-radius: 5px;
    overflow: auto;
  }
}

.el-checkbox-group {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  overflow: auto;
  height: 310px;
  .inner-group {
    width: 210px;
    height: 30px;
    position: relative;
    /deep/.el-checkbox {
      font-weight: 500;
      font-size: 15px;
      cursor: pointer;
      // width: 10px;
      height: 30px;
      line-height: 30px;
      color: #e6e6e6;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      left: 0;
      .el-checkbox__input.is-checked + .el-checkbox__label {
        color: #fff;
      }
      .el-checkbox__input.is-checked .el-checkbox__inner::after {
        width: 70%;
        height: 70%;
        background: #74ffff;
        border-radius: 0;
        transform: rotate(0deg) scaleY(1);
        position: static;
      }
      .el-checkbox__inner {
        border: 1px solid #dcdfe6;
        background: rgba(0, 170, 255, 0);
        display: flex;
        align-items: center;
        justify-content: center;
        position: static;
        &::after {
          transition: 0ms;
        }
      }
    }
    /deep/.el-checkbox_label {
      width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

// /deep/.el-checkbox_label{
//   width: 200px !important;
// }
.overlay-container {
  width: 100%;
  height: 35px;
  border-radius: 4px;
  cursor: pointer;
  color: #e6e6e6;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  top: 14px;
  &.forbidden {
    cursor: not-allowed;
  }
  &-icon {
    width: 25px;
    height: 25px;
    background: url("../../../assets/image/overlay_white.png") no-repeat center;
    &.checked {
      background: url("../../../assets/image/overlay.png") no-repeat center;
    }
  }
  &-btn {
    width: 80px;
    height: 25px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    &.checked {
      color: rgb(0, 170, 255);
    }
  }
}
</style>
