<template>
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot-scope="{type,size,row}" slot="menu">
          <el-button icon="el-icon-setting" :size="size" :type="type" @click="configurationClick(row)">配置划分</el-button>
          <el-button icon="el-icon-setting" :size="size" :type="type" @click="Associationlist(row)">关联清表</el-button>
          <el-button icon="el-icon-setting" :size="size" :type="type" @click="associatedClick(row)">数据映射配置</el-button>
        </template>
      </avue-crud>

         <!-- 关联清表 -->
    <el-dialog
      title="关联下载模板表"
      class="excelBox"
      :visible.sync="GLExcel"
      width="500px"
      modal-append-to-body
      append-to-body
      @close="GLExcelMD"
    >
   <div class="mg-b-10">
    <el-alert
        :closable="false"
        title="选择需要关联的清表 注意:每次只能单选操作"
        type="warning">
      </el-alert>
   </div>
      <div>
        <el-select
          style="width: 100%"
          v-model="GLExcelFrom.name"
          placeholder="请选择"
          @change="changetherr"
        >
          <el-option
            v-for="(item, key) in GLExcelData"
            :key="key"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-scrollbar style="margin-top: 20px; height: 50vh">
          <el-input
          style="width: 100%"
            v-model.trim="searchVal"
            placeholder="请输入需要选择的内容"
          ></el-input>
          <el-tree
          v-if="checkId"
            :key="treeKey"
            lazy
            :filter-node-method="filterNode222"
            ref="tree"
            class="filter-tree"
            style="margin-top: 10px"
            :props="GLExcelProps"
            :load="loadNode"
            node-key="id"
            accordion
            show-checkbox
            @check="checkchange"
            v-loading="GLExcelLoading"
            :default-checked-keys="linkexcelId"

          >
          </el-tree>
        </el-scrollbar>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: center; align-items: center"
      >
        <el-button @click="GLExcelMD()">取 消</el-button>
        <el-button
          style="margin-left: 30px"
          type="primary"
          v-throttle="2000"
          @click="saveLink()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 配置划分数据 -->
    <configDivision :testGLExcel="testGLExcel" :setId="setId" @changemodal="changemodal" :trialTreeIds="trialTreeIds"></configDivision>
    </basic-container>
  </template>
  
  <script>
  import {getList, getDetail, add, update, remove} from "@/api/tentative/testcollect";
  import {mapGetters} from "vuex";
  import {
  getList as getListQing,


} from "@/api/exctab/excelmodel";
import {relevancy,tablazy} from "@/api/tentative/testcollect";
import configDivision from "./components/configDivision.vue";

  
  export default {
    components:{
      configDivision
    },
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        search:{},
        selectionList: [],
        option: {
          menuWidth:440, 
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          searchMenuSpan: 0,
          border: true,
          index: true,
          viewBtn: true,
          selection: false,
          dialogClickModal: false,
          labelWidth:150,
          column: [
            {
              label: "分类名称",
              prop: "className",
              rules: [{
                required: true,
                message: "请输入分类名称",
                trigger: "blur"
              }]
            }
          ]
        },
        data: [],
        GLExcel:false,
        GLExcelFrom:{
          id: "",
          name: "",
          search: "", //搜素框舒服的值
          ids: "",
          excelId: "",
          initTableName: "",
          initTableId:""
        },
        searchVal:'',
        GLExcelData:[],
        exceldata:[],
        GLExcelProps: {
        label: "name",
        children: "children",
        disabled: "hasChildren",
        isLeaf: function (data) {
          let tag = false;
          if (!data.hasChildren) {
            tag = true;
          }
          if (data.isExistForm == 1) {
            tag = true;
          }
          return tag;
        },
      },
      testGLExcel:false,
      checkId:'',
      treeKey:Math.random,
      setId:'',
      trialTreeIds:'',//已关联的配置划分数据
      linkexcelId:[]//已关联的清表数据
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          viewBtn: false,
          //addBtn: this.vaildData(this.permission.imageclassificationconfig_add, false),
          //viewBtn: this.vaildData(this.permission.imageclassificationconfig_view, false),
          //delBtn: this.vaildData(this.permission.imageclassificationconfig_delete, false),
         // editBtn: this.vaildData(this.permission.imageclassificationconfig_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    watch: {
      searchVal(val) {
        if (this.exceldata) {
          this.$refs.tree.filter(val);
        }
      },
     
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },

   
        //关联清表
    Associationlist(row) {
      //关联清表点击事件
      if(row.excelId){
        this.linkexcelId=row.excelId.split(',')
      }
     
      this.GLExcelFrom.id = row.id;
      this.GLExcelFrom=row
      this.searchVal=''
      this.GLExcel =true ;
      this.treeKey=Math.random()
      this.getList({
        current: 1,
        size: 100000,
        parentId: 0,
      });
     
    },
    GLExcelMD() {
      //弹框关闭事件
      this.GLExcelFrom.name = "";
      this.GLExcelFrom.search = "";
      this.GLExcelFrom.id = "";
      this.exceldata = [];
      this.checkId=''
      this.GLExcel = false;
    },
    changetherr(val) {
      console.log(val,'val');
      //清表类型选择框change事件
      if (this.GLExcelFrom.name != "") {
        this.GLExcelFrom.search = "";
        this.checkId=val
        this.treeKey=Math.random()
        
    
      }
    },

    loadNode(node, resolve) {
      let pid = 0;
      let modeId=this.checkId;
      if (node.level != 0) {
        pid = node.data.id;
        modeId=node.data.parentId
      }
      tablazy({
        modeId: modeId,
        parentId: pid,
        classId:this.GLExcelFrom.id
      }).then((res) => {
        let arr = [];
        if (Array.isArray(res.data.data)) {
          arr = res.data.data;
        }
        return resolve(arr);
      });
    },
    filterNode222(value,data,node) {
      if(!value){
          return true;
        }
        let level = node.level;
        let _array = [];//这里使用数组存储 只是为了存储值。
        this.getReturnNode2(node,_array,value);
        let result = false;
        _array.forEach((item)=>{
          result = result || item;
        });
        return result;
      },
    getReturnNode2(node,_array,value){
          let isPass = node.data &&  node.data.name && node.data.name.indexOf(value) !== -1;
          isPass?_array.push(isPass):'';
          if(!isPass && node.level!=1 && node.parent){
            this.getReturnNode2(node.parent,_array,value);
          }
      },
    async getList(da) {
      //获取清表模板信息
        const { data: res } = await getListQing(da);
        console.log(res);
        if (res.code === 200 && res.msg === "操作成功") {
          this.GLExcelData = res.data.records;
        }
    },
    checkchange(data) {
        //节点选中回调
        if (this.$refs.tree.getCheckedNodes().length === 0) {
          this.$refs.tree.setCheckedKeys([]);
        } else if (this.$refs.tree.getCheckedNodes().length >= 1) {
          this.$refs.tree.setCheckedKeys([data.id]);
        }
    },
    async saveLink() {
        //保存按钮
        let checkIds=this.$refs.tree.getCheckedKeys();
        if (checkIds.length > 0) {
          
          const { data: res } = await relevancy({
                classId:this.GLExcelFrom.id,
                excelId:checkIds.join(',')
          });
          console.log(res);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "关联清表成功",
            });
            this.GLExcel =false ;
            this.refreshChange()
          }
        } else {
          this.$message({
            type: "warning",
            message: "请先选择清表",
          });
        }
    },
    //配置划分
    configurationClick(row){
      this.testGLExcel=true
      this.setId=row.id
      this.trialTreeIds=row.trialTreeIds
    },
    changemodal(){
      this.testGLExcel=false
      this.refreshChange()
    },
    //数据映射配置
    associatedClick(row) {
      this.$router.push({
        path: '/tentative/dataMap',
        query: { classId: row.id }


      });
     },
    },
  
  };
  </script>
  
  <style>
  </style>
  