<template>
  <!-- 关联公共WBS模板 -->
  <el-dialog
    title="关联公共WBS模板"
    class="excelBox"
    :visible.sync="AssociatedPublicTap"
    modal-append-to-body
    append-to-body
    :close-on-click-modal="false"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <el-select
          style="width: 100%"
          v-model="GLExcelFrom.name"
          placeholder="请选择"
          @change="changetherr()"
        >
          <el-option
            v-for="(item, key) in GLExcelData"
            :key="key"
            :label="item.wbsName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-scrollbar style="height: 50vh">
          <div class="flex" style="margin-top: 10px" v-if="isShowInput">
            <el-input
              size="small"
              placeholder="输入关键字搜索"
              clearable
              @clear="clearInput"
              v-model="filterText1"
            >
            </el-input>
            <el-button size="small" class="mg-l-10" @click="treeFilter1"
              >搜索</el-button
            >
          </div>
          <el-tree
            v-if="GLExcelFromtag"
            @node-click="handleNodeClickExcel"
            ref="tree"
            class="filter-tree"
            style="margin-top: 10px"
            :props="GLExcelProps"
            :data="exceldata"
            :load="loadNodeTan"
            lazy
            node-key="id"
            accordion
            :show-checkbox="activeName == 'add'"
            :check-strictly="true"
            :default--checked-keys="selectNodeIds"
          >
          </el-tree>

          <el-tree
            style="width: 100%"
            ref="treeall1"
            v-loading="treeloading1"
            :data="allTreeData1"
            :props="treeProps1"
            @node-click="handleNodeClickExcel"
            node-key="id"
            :expand-on-click-node="false"
            :filter-node-method="filterNode1"
            v-show="GLExcelFromtag1"
            :show-checkbox="activeName == 'add'"
            :default--checked-keys="selectNodeIds"
            :check-strictly="true"
          >
          </el-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="12" v-if="addElementForm.wbsId">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="关联元素表" name="link">
            <el-table
              :data="addTableData"
              border
              style="width: 100%"
              class="martop20"
            >
              <el-table-column
                prop="tableName"
                label="已有元素表名称"
                align="center"
              >
              </el-table-column>
              <el-table-column prop="name" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    style="margin: 0px"
                    @click="relationMD(scope.row, '关联')"
                    v-show="!scope.row.checknd"
                    :loading="scope.row.loading"
                    >选择关联</el-button
                  >
                  <el-button
                    type="danger"
                    size="mini"
                    style="margin: 0px"
                    @click="relationMD(scope.row, '取消关联')"
                    v-show="scope.row.checknd"
                    :loading="scope.row.loading"
                    >取消关联</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="新增元素表" name="add">
            <div>
              <div class="flexBetween martop20">
                <el-input
                  v-model="addElementForm.nodeName"
                  placeholder="请输入表名"
                ></el-input>
                <el-select
                  class="marleft10"
                  v-model="addElementForm.tableType"
                  placeholder="请选择表类型"
                >
                  <el-option
                    v-for="(item, index) in exceltypeData"
                    :key="index"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  ></el-option>
                </el-select>
              </div>
              <el-select
                style="width: 100%"
                class="martop20"
                v-model="addElementForm.tableOwner"
                placeholder="请选择所属方"
              >
                <el-option
                  v-for="(item, index) in ownerTypeList"
                  :key="index"
                  :label="item.dictValue"
                  :value="item.dictKey"
                ></el-option>
              </el-select>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <span
      slot="footer"
      class="dialog-footer"
      style="display: flex; justify-content: center; align-items: center"
    >
      <el-button @click="AssociatedPublicClose()">取 消</el-button>
      <el-button
        style="margin-left: 30px"
        type="primary"
        @click="saveElementMD()"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { getAlltree } from "@/api/manager/wbstree";
import { getDictionary } from "@/api/system/dict";
import { dictionarydataType } from "@/api/exctab/editelement";
import {
  excelType,
  excelType1,
  submitExcelRelationWbsTreeAndElement,
  getWbsTypeList,
  getLazytree,
  cancelRelation,
  saveRelation,
  searchNodeTables,
  savelinktableInfo,
} from "@/api/exctab/excelmodel";
import { getColByTabId } from "@/api/manager/AdjustForm";

export default {
  props: {
    from: Object,
  },
  data() {
    return {
      AssociatedPublicTap: false,
      //#region 弹框属性
      GLExcelFrom: {
        id: "",
        name: "",
        search: "", //搜素框舒服的值
      },
      GLExcelData: [], //
      isShowInput: false,
      filterText1: "",
      GLExcelFromtag1: false,
      GLExcelFromtag: false,
      GLExcelProps: {
        label: "title",
        children: "children",
        isLeaf: function (data) {
          if (data.hasChildren && data.isExistForm != 1) {
            return false;
          } else if (data.hasChildren && data.isExistForm == 1) {
            return true;
          } else {
            return true;
          }
        },
        disabled: function (data) {
          if (data.hasChildren && data.isExistForm != 1) {
            return true;
          } else if (data.hasChildren && data.isExistForm == 1) {
            return false;
          } else {
            return false;
          }
        },
      },
      exceldata: [],
      selectNodeIds: [],

      treeloading1: false,
      allTreeData1: [],
      treeProps1: {
        label: "title",
        children: "children",
        isLeaf: "hasChildren",
        disabled: function (data) {
          if (data.hasChildren && data.isExistForm != 1) {
            return true;
          } else if (data.hasChildren && data.isExistForm == 1) {
            return false;
          } else {
            return false;
          }
        },
      },

      addElementForm: {
        id: "",
        initTableName: "",
        nodeName: "",
        tableType: "",
        tableOwner: "",
        wbsId: "",
        parentId: "",
      },
      nodeTypelist: [],
      ownerTypeList: [],

      addTableData: [], //新增元素信息表
      activeName: "link",
      dataType: [],
      addElement: false,
      exceltypeData: [],
    };
  },
  methods: {
    show() {
      console.log(this.from, "from");
      this.AssociatedPublicTap = true;
      this.addElementForm.nodeName = this.from.title;
      this.addElementForm.tableType = this.from.tableType + "";
      this.addElementForm.tableOwner = this.from.tableOwner;
      //清除数据
      this.filterText1 = "";
      this.exceldata = [];
      this.allTreeData1 = [];
      this.selectedId = "";
      this.GLExcelFrom.name = "";
      this.isShowInput = false;

      //清理之前填写的数据
      this.addElementForm.wbsId = "";
      // this.addElementForm.tableOwner = "";
      this.getWbsTypeList();

      this.getOwnerTypelist();
      this.getColByTabId();
    },
    addElementMD() {
      //新增元素信息表按钮
      this.excelType();
      this.addElement = true;
    },
    async excelType(type) {
      //清表类型
      // const { data: res } = await excelType({ code: "sys_excltab_type" });
      const { data: res } = await excelType1({ code: type });
      console.log(res);
      if (res.code === 200) {
        this.exceltypeData = res.data;
      }
    },
    async getWbsTypeList() {
      //获取清表模板信息
      const { data: res } = await getWbsTypeList({ wbstype: 1 });

      if (res.code === 200 && res.msg === "操作成功") {
        this.GLExcelData = res.data;
      }
    },
    changetherr(item) {
      console.log(item, "关联item");
      console.log(this.GLExcelFrom.name, "name");
      //下拉框change事件
      this.GLExcelFromtag = false;
      this.GLExcelFromtag1 = false;
      this.filterText1 = "";
      if (this.GLExcelFrom.name != "") {
        this.GLExcelFrom.search = "";
        this.exceldata = [];
        this.addTableData = [];
        this.isShowInput = false;
        this.addElementForm.wbsId = "";
        this.$nextTick(() => {
          this.GLExcelFromtag = true;
        });
      }
    },
    clearInput() {
      (this.selectedId = ""),
        (this.GLExcelFromtag1 = false),
        (this.GLExcelFromtag = true);
      if (this.$refs.tree) {
        this.nodeIds = this.$refs.tree.getCheckedKeys();
      }
      if (this.$refs.treeall1) {
        this.nodeIds1 = this.$refs.treeall1.getCheckedKeys();
      }
      this.selectNodeIds = this.uniqueArr(this.nodeIds, this.nodeIds1);
      console.log(this.selectNodeIds, "this.selectNodeIds111111");
      // this.$refs.tree.setCheckedKeys(this.selectNodeIds)

      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.selectNodeIds);
      });
    },
    treeFilter1() {
      if (this.filterText1) {
        if (this.$refs.tree) {
          this.nodeIds = this.$refs.tree.getCheckedKeys();
        }
        if (this.$refs.treeall1) {
          this.nodeIds1 = this.$refs.treeall1.getCheckedKeys();
        }

        this.selectNodeIds = this.uniqueArr(this.nodeIds, this.nodeIds1);
        this.$refs.treeall1.setCheckedKeys(this.selectNodeIds);
        console.log(this.selectNodeIds, "this.selectNodeIds");
        this.GLExcelFromtag1 = true;
        this.GLExcelFromtag = false;
        this.treeloading1 = true;
        console.log(this.selectedId, "selectedId");
        console.log(this.GLExcelFrom.name, "this.GLExcelFrom.name");
        // tabLazytreeAll({
        //   modeId: this.GLExcelFrom.name,
        //   name: "",
        // })
        getAlltree("000000", 1, this.GLExcelFrom.name).then((res) => {
          this.treeloading1 = false;
          this.allTreeData1 = res.data.data;
          console.log(this.exceldata, "this.exceldata");
          console.log(this.GLExcelFromtag, "this.GLExcelFromtag");

          this.$nextTick(() => {
            console.log("过滤2", this.filterText1);
            this.$refs.treeall1.filter(this.filterText1);
          });
        });
      }
    },

    handleNodeClickExcel(data) {
      this.excelType("table_type");
      // if(data.wbsType===2){
      //   this.excelType('trial_table_type');
      // }else{
      //    this.excelType('table_type');
      // }

      //点击节点事件
      this.addElementForm.wbsId = this.GLExcelFrom.name;
      this.addElementForm.parentId = data.id;
      //this.selectByNodeTable(data.id)
      this.searchNodeTables(data.id);
    },
    //#region

    async loadNodeTan(node, resolve) {
      //懒加载
      console.log(node);
      this.selectedId = node.data.id;
      if (node.level === 0) {
        return resolve(await this.getLazytree(0));
      } else {
        return resolve(await this.getLazytree(node.data.id));
      }
    },
    // filterNode1(value, data) {
    //     if (!value) return true;
    //     return data.title.indexOf(value) !== -1;
    // },

    getReturnNode(node, _array, value) {
      let isPass =
        node.data && node.data.title && node.data.title.indexOf(value) !== -1;
      isPass ? _array.push(isPass) : "";
      if (!isPass && node.level != 1 && node.parent) {
        this.getReturnNode(node.parent, _array, value);
      }
    },

    filterNode1(value, data, node) {
      if (!value) {
        return true;
      }
      let level = node.level;
      let _array = []; //这里使用数组存储 只是为了存储值。
      this.getReturnNode(node, _array, value);
      let result = false;
      _array.forEach((item) => {
        result = result || item;
      });
      return result;
    },

    getOwnerTypelist() {
      if (this.ownerTypeList.length > 1) {
        return;
      }
      getDictionary({
        code: "owner_type",
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.ownerTypeList = res.data.data;
      });
    },
    relationMD(row, type) {
      console.log("关联元素表", row);
      //关联取消关联
      row.loading = true;
      if (type == "关联") {
        // saveRelation(row.id, this.from.id, this.tableData)
        this.savelinktableInfo1({
          linkids: row.id,
          tabId: this.from.id,
          type: 1,
          wbsId: this.GLExcelFrom.name,
        })
          .then(() => {
            row.checknd = true;
            row.isLinkTable = 2;
          })
          .finally(() => {
            row.loading = false;
          });
      } else {
        this.savelinktableInfo1({
          linkids: row.id,
          tabId: this.from.id,
          type: 4,
          wbsId: this.GLExcelFrom.name,
        })
          .then(() => {
            row.checknd = false;
            row.isLinkTable = 1;
          })
          .finally(() => {
            row.loading = false;
          });
      }
    },
    AssociatedPublicClose() {
      console.log("AssociatedPublicClose");
      //关联公共WBS模板关闭事件
      this.addElementForm = {
        id: "",
        initTableName: "",
        nodeName: "",
        tableType: "",
        tableOwner: "",
        wbsId: "",
        parentId: "",
      };
      this.GLExcelFrom = {
        name: "",
        search: "",
      };
      this.exceldata = [];
      this.addElement = false;

      //清理之前填写的数据
      this.addElementForm.wbsId = "";
      // this.addElementForm.tableType = '';
      this.addElementForm.tableOwner = "";

      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.tree.setCurrentKey(null);
      }

      this.addTableData = [];
      this.AssociatedPublicTap = false;
    },
    saveElementMD() {
      //保存按钮
      if (this.addElementForm.wbsId) {
        console.log(this.tableData, "this.tableData");
        if (this.activeName == "link") {
          this.AssociatedPublicTap = false;
          this.AssociatedPublicClose();
        } else {
          if (
            this.addElementForm.nodeName &&
            this.addElementForm.tableType &&
            this.addElementForm.tableOwner
          ) {
            if (this.$refs.tree) {
              this.nodeIds = this.$refs.tree.getCheckedKeys();
            }
            if (this.$refs.treeall1) {
              this.nodeIds1 = this.$refs.treeall1.getCheckedKeys();
            }

            this.selectNodeIds = this.uniqueArr(this.nodeIds, this.nodeIds1);
            console.log(this.selectNodeIds, "去重的数组");

            if (this.selectNodeIds.length < 1) {
              this.$message({
                type: "warning",
                message: "至少勾选一个节点",
              });
              return;
            }
            this.selectNodeIds = this.selectNodeIds.join(",");
            this.savelinktableInfo({
              linkids: this.selectNodeIds,
              tabId: this.from.id,
              type: 2,
              wbsId: this.GLExcelFrom.name,
            });

            // this.submitExcelRelationWbsTreeAndElement({
            // nodeName: this.addElementForm.nodeName,
            // tableType: this.addElementForm.tableType,
            // tableOwner: this.addElementForm.tableOwner,
            // wbsId: this.addElementForm.wbsId,
            // elementList: this.tableData,
            // nodeIds: this.selectNodeIds,
            // excelTabId: this.from.id,
            // submitStatus: 2,
            // });
          } else {
            this.$message({
              type: "warning",
              message: "请填写和选择新增的表名，表类型，表所属方",
            });
          }
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先选择WBS树节点表单",
        });
      }
      this.activeName = "link";
    },
    async getLazytree(parentId) {
      //清表树信息
      const { data: res } = await getLazytree({
        parentId: parentId,
        wbsId: this.GLExcelFrom.name,
        wbsType: "1",
      });
      console.log(res);
      if (res.code === 200 && res.msg === "操作成功") {
        this.isShowInput = true;
        console.log(this.isShowInput, " this.isShowInput");
        res.data.forEach((val) => {
          val.isExistForm = !!val.isExistForm;
        });
        return res.data;
      } else {
        return [];
      }
    },
    //查看节点下已关联的元素表信息
    searchNodeTables(id) {
      searchNodeTables(id, this.from.id).then((res) => {
        if (res.data.data&&res.data.data.length > 0) {
          res.data.data.forEach((val) => {
            if (val.isLinkTable == 2) {
              val.checknd = true;
            } else {
              val.checknd = false;
            }
            val.loading = false;
          });
          this.addTableData = res.data.data;
        } else {
          this.addTableData = [];
        }
      });
    },
    //数组去重
    uniqueArr(arr1, arr2) {
      //合并两个数组
      arr1.push(...arr2); //或者arr1 = [...arr1,...arr2]
      //去重
      let arr3 = Array.from(new Set(arr1)); //let arr3 = [...new Set(arr1)]
      return arr3;
    },
    async dictionarydataType() {
      //数据类型字典
      const { data: res } = await dictionarydataType();
      console.log(res);
      if (res.code == 200) {
        res.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.dataType = res.data;
      }
    },
    //  async submitExcelRelationWbsTreeAndElement(da) {
    //      console.log(da,'新增元素信息表');
    //     //保存接口
    //     da.elementList.forEach((ele) => {
    //         ele.eName = ele.textInfo;
    //         ele.eType = ele.textElementType;
    //         ele.eAllowDeviation = ele.textDeviation;
    //     });
    //     const { data: res } = await submitExcelRelationWbsTreeAndElement(da);
    //     if (res.code == 200) {
    //         this.$message({
    //         type: "success",
    //         message: "设置成功",
    //         });
    //         this.AssociatedPublicTap = false;
    //         this.AssociatedPublicClose();
    //     }
    // },
    async savelinktableInfo(da) {
      console.log("新增元素表", da);
      const { data: res } = await savelinktableInfo(da);
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "设置成功",
        });
        this.AssociatedPublicTap = false;
        this.AssociatedPublicClose();
      }
    },
    //选择关联取消关联修改
    async savelinktableInfo1(da) {
      console.log("选择关联", da);
      const { data: res } = await savelinktableInfo(da);
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "设置成功",
        });
        // this.AssociatedPublicTap = false;
        // this.AssociatedPublicClose();
      }
    },

    async getColByTabId() {
      //获取字段信息
      const { data: res } = await getColByTabId({ tabId: this.from.id });

      // const { data: res } = await getColByTabId({tabId: '1537614072773054466' });

      if (res.code === 200) {
        res.data.forEach((element) => {
          //element.eName = element.textInfo;
          if (element.textElementType < 1) {
            element.textElementType = 1;
          }
        });
        this.tableData = res.data;
        console.log(this.tableData, "获取字段信息");
      }
    },
  },
};
</script>

<style></style>
