<template>
  <el-dialog    :close-on-click-modal="false"
    title="模板绑定"
    :before-close="handleClose"
    :visible.sync="dialogVisible"
    width="30%"
    class="mbbdtck"
    style="padding: 10px;"
  >
    <div class="tranferbox">
      <div class="conbox">
        <div class="titbox">
          <el-input
            size="mini"
            placeholder="搜索"
            suffix-icon="el-icon-search"
            v-model="filterText"
          ></el-input>
        </div>
        <div class="wordbox">
          <el-tree 
            default-expand-all
            @check.stop="getData"
            show-checkbox
            class="filter-tree"
            node-key="id"
            :data="data"
            :props="defaultProps"
            :filter-node-method="filterNode"
            ref="tree"
            style="height: 440px; overflow-y: auto"
          >
          <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label}}</span>
        
        <span style="position:absolute;right:10px" >
          <div  @click.stop>
          <el-switch
            @change='swicthchange($event,data,node)'
            style="display: block;z-index: 9999999;"
            v-model="node.data.activation"
            :active-color=settings.themeColor
            :active-value="true"
            :inactive-value="false"
            inactive-color="#ccc"
            :active-text="node.data.activation?'激活':'未激活'"
            >
          </el-switch>
        </div>
        </span>
      </span>
        </el-tree>
        </div>
      </div>

      <!-- <div class="conbox" style="margin-left: 20px">
        <div class="wordbox">
          <el-input
          v-model="search"
          size="mini"
          placeholder="输入关键字搜索"/>
          <el-table
            stripe
            border
            header-cell-class-name="table_header"
            height="465px"
            :data="keyarr.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
            style="width: 100%"
          >
            <el-table-column
              prop="name"
              show-overflow-tooltip
              label="部门"
              width="200px"
            >
            </el-table-column>
            <el-table-column prop="activation" width="160px" label="是否激活">
              <template slot-scope="scope">
            
                <el-switch
                  @change="tagClick(scope.$index, scope.row, $event)"
                  :active-value="1"
                  :inactive-value="0"
                  class="tablescope"
                  v-model="scope.row.activation"
                >
                </el-switch>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="address" label="删除" width="100px">
              <template slot-scope="scope">
                <el-button
                  @click="removeData(scope.row)"
                  size="mini"
                  type="danger"
                  >删除</el-button
                >
              </template>
            </el-table-column> -->
          <!-- </el-table> -->
        
        <!-- </div>
      </div> -->
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="binding">绑 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { pvTree } from "@/api/AccountOperation";
import {
  updateBindTemplate,
  getDataByTempId,
} from "@/api/templateConfiguration";
import { mapGetters } from "vuex";
import defaultSettings from "@/settings"
export default {
  props: {
    dialogVisible: {
      required: true,
      type: Boolean,
    },
    valList: {
      required: true,
      type: [Object, Array],
    },
  },
  computed: {
    settings() {
      return this.$store.state.settings;
    },
    ...mapGetters(["settings"]),
  },
  data() {
    return {
      hhdl:true,
      value2:[],
      input3: "",
      search:'',
      checkList: [],
      keyarr: [],
      filterText: "",
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      id: [],
      list: {},
      idlist:[],
      ydata:[],
      listids:[]
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.list = JSON.parse(JSON.stringify(this.valList)); 

    this.getIndexs();
    
   

  },
  methods: {
    setSwitchStatus(id, data, status) {
      let that = this;
      data.forEach((x) => {
        if (x.id == id) {
          x.activation = status;
          if (x.children) {
            x.children.forEach((o) => {
              that.setSwitchStatus(o.id, x.children, status);
            });
          }
        } else {
          if (x.children) {
            that.setSwitchStatus(id, x.children, status);
          }
        }
      });
     // this.setParentSwitcStatus(this.treeData[0]);
    },
    setParentSwitcStatus(data) {
      let that = this;
      let activation = true;
      if (data.children) {
        data.children.forEach((x) => {
          if (!x.activation) {
            activation = false;
          }
          if (x.children) {
            that.setParentSwitcStatus(x);
          }
        });
      }
      data.activation = activation;
    },
  


    swicthchange(event,data,node){
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        this.$set(data, 'activation'+new Date().getTime(), !event);
        // let obj = children.splice(index, 1);
        // console.log(obj);
        //children.splice(index,0,obj[0]);
       // this.data =  [...this.data]

      this.$forceUpdate()
      if(event){
      var p={
          deptId: data.id,
          tempId: this.valList.id,
          activation:1,
      } 
      // data.activation =true
      this.listids.push(p)  
      }else{
        var p={
          deptId: data.id,
          tempId: this.valList.id,
          activation:0 ,
      } 
      // data.activation =true
       this.listids.push(p)  
       $set(data, 'activation'+new Date().getTime(), false); 
      }

    //  console.log("+++++=",event,node)
    //  console.log("+++++====",data)
    //  console.log("+++++===333=",this.data)
    },
    getIndexs() {
        pvTree().then((res) => {
        // console.log(res);
        if (res.code == "A0000") {
          // res.data.forEach((item) => {
          //   if (item.children.length > 0) {
          //     item.children.forEach((e) => {
          //       if (e.children.length > 0) {
          //         e.children.forEach((v) => {
          //           if (v.children.length > 0) {
          //             v.children.forEach((s) => {
          //               if (s.children.length > 0) {
          //               } else {
          //                 s.children = null;
          //               }
          //             });
          //           } else {
          //             v.children = null;
          //           }
          //         });
          //       } else {
          //         e.children = null;
          //       }
          //     });
          //   } else {
          //     item.children = null;
          //   }
          // });

          // item.children.length > 0 ? item.children : null;
          //             item.children.forEach((e) => {
          //               e.children.length > 0 ? e.children : null;
          //               e.children.forEach((v) => {
          //                 e.children.children.length > 0 ? v.children : null;
          //               });
          //             });

          this.ydata = res.data;
          this.getgbdata(this.ydata)
         // console.log('++++++=',this.ydata)
          this.getDataByTempIds();
        }
      });
    },
    getgbdata(data){
     data.forEach((m)=>{
       m.activation = false
       if(m.children.length>0){
      this.getgbdata(m.children)
     }
     })
    
    },
    // 根据模板ID查询数据
    getDataByTempIds() {
      getDataByTempId({ id: this.valList.id }).then((res) => {
        this.keyarr = [];
        this.idarr =[]
        res.data.forEach((item) => {
          this.keyarr.push({
            name: item.deptName,
            id: item.deptId,
            activation: item.activation,
          });
          this.idarr.push({id:item.deptId})
        });
        this.gettreeData(this.ydata,this.keyarr)
        this.data  = this.ydata
        this.setCheckedNodes(this.idarr);
        setTimeout(() => {
          this.removeData();
        }, 0);
      });
    },
    settreeData(data,id){
      data.forEach((m)=>{
        if(m.id == id){
          m.activation= false
       }
      })
      if(m.children.length>0){
        this.settreeData(m.children,id) 
      }
    },
    gettreeData(mdata,ids){
      mdata.forEach((m)=>{
        ids.forEach((n)=>{
          if(m.id == n.id && n.activation==1){
            m.activation = true
           }
          })
       if(m.children.length>0){
        this.gettreeData(m.children,ids) 
       }else{
        m.children =null
       }
      // m.activation= false
      })
      
    },
    //关键词搜索
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    getData() {
      this.id = [];
      this.keyarr.forEach((item) => {
        if (item.activation == true) {
          this.id.push(item.id);
        }
      });

      this.keyarr = [];

      this.checkList = this.$refs.tree.getCheckedNodes();
      //   console.log(this.checkList);
      if (this.checkList.length != 0) {
        for (var i = 0; i < this.checkList.length; i++) {
          if (!this.checkList[i].children) {
            this.checkList[i].activation = false;
            // if( this.checkList[i].id==this.id){
            //    this.checkList[i].activation = 1;
            // }
            for (var k = 0; k < this.id.length; k++) {
              if (this.id[k] == this.checkList[i].id) {
                this.checkList[i].activation = true;
                break;
              } else {
                this.checkList[i].activation = true;
              }
            }
            this.keyarr.push(this.checkList[i]);
            // this.keyarr.push(this.checkList[i]);

            // console.log(this.checkList[i]);
          }
        }
        //  this.keyarr = Array.from( new Set([... this.keyarr,...list]));
      } else {
        this.keyarr = [];
      }
    },
    setCheckedNodes(arr) {
      setTimeout(()=>{
        this.$refs.tree.setCheckedNodes(arr);
      },500)
     
    },
    removeData(data) {
      let checklist = this.keyarr;
      //   console.log(this.keyarr);
      if (data != undefined) {
        for (var i = 0; i < checklist.length; i++) {
          if (checklist[i].id === data.id) {
            checklist.splice(i, 1);
          }
        }
      }
      //   console.log(this.keyarr);
      this.id = [];
      this.keyarr.forEach((item) => {
        if (item.activation == true) {
          this.id.push(item.id);
        }
      });
      this.keyarr = checklist;
      this.setCheckedNodes(this.keyarr);
    },
    //去重
   quchong(arr) {
        let list = [];
        return arr.filter((item) => !list.includes(item.deptId) && list.push(item.deptId))
    },
    // 绑定模板
   async binding() {
      // listid = [];
      console.log("++++++++++++",this.keyarr)

      this.keyarr.forEach((item) => {
        if(item.activation){
          this.listids.push({
          deptId: item.id,
          tempId: this.valList.id,
          activation: 1,
        });
        } else{
          this.listids.push({
          deptId: item.id,
          tempId: this.valList.id,
          activation: 0,
        });
        }
        
      });
      this.listids  =   this.quchong(this.listids)
      //console.log("===========",this.listids)
    await  updateBindTemplate(this.listids).then((res) => {
        this.$message({
          type: "success",
          message: res.message,
        });
        this.$emit("binding");
      });
    },
    tagClick(index, row, val) {
      let list = null;

      this.keyarr[index].activation = val;
      this.id = [];
      this.keyarr.forEach((item) => {
        if (item.activation == true) {
          this.id.push(item.id);
        }
      });
      list = JSON.parse(JSON.stringify(this.keyarr));
      //this.keyarr = [];
      setTimeout(() => {
        this.keyarr = list;
      }, 0);

      //  row.editable = true;
      // this.$set(this.keyarr,index,row);
    },

    // 关闭弹框
    handleClose() {
      this.$emit("handleClose");
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../styles/comStyle.less");
</style>
<style lang="scss" scoped>
.tranferbox {
  display: flex;
  .conbox {
    flex: 1;
  }
}
::v-deep.mbbdtck.el-dialog .el-dialog__body {
     max-height: 70vh;
     padding: 20px 10px 10px 10px !important;
    //overflow-y: auto;
}

::-webkit-scrollbar {
    width: 8px !important;
    height: 14px;
    
}
</style>
