<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入部门名称"
          clearable
          size="small"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button plain size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <br>
      <el-form-item>
        <el-button plain size="mini" @click="synchrodeptJob">部门信息同步</el-button>
        <el-button plain size="mini" @click="batchChange(1)">部门充值比例绑定</el-button>
        <el-button plain size="mini" @click="batchChange(0)">部门充值比例解除</el-button>
      </el-form-item>
    </el-form>
    <el-table  :data="adminList"  ref="tableRef" :header-cell-class-name="cellClass"
    @select="handletableSelect"

          @selection-change="handletableSelectionChange" height="calc(100vh - 12vh - 120px)" row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="id" align="center" prop="id" show-overflow-tooltip />
      <el-table-column label="部门名称" align="center" prop="name"  show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy"  show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog   :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false"  >
      <el-form ref="queryParams" :model="queryParams"  :rules="rules" label-width="120px" >
        <el-form-item label="到账比例：" prop="id">
          <el-select v-model="queryParams.id" style="width: 240px" placeholder="请选择到账比例" clearable size="small" >
            <el-option :label="`${item.identity}:${item.proportion}`"  :value="item.id" v-for="(item, index) in radioList" :key="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!loading">确 定</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm" v-else>提交中...</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listChannel, deptJob, updataByDept, deptList } from "@/api/recharge/department";
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import { allRadio } from "@/api/recharge/radio";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import qs from 'qs'
export default {
  name: "admin",
   components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      dialogFormVisible:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        id: undefined,
      },
      //批量到账比例处理
      staffList:{},
      // 到账比例
      radioList:[],
      // 表单参数
      form: {
        name:'',
      },
      // 表单校验
      rules: {
        id:[
           { required: true, message: "充值比例不能为空", trigger: "change"},
        ],
      },
      tableRadio: {},
      deptIds:[],//部门绑定集合,
      deptIdsb:[],//部门绑定集合,
      tableSelect:[],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //去除全选
    cellClass(row) {
        if (row.columnIndex === 0) {
            return 'disabledCheck';
        }
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    handletableSelect(selection, row) {
      if (row.children) { //只对有子节点的行响应
        // if (row.isChecked === undefined) row.isChecked = true
        if (!row.isChecked) {   //由行数据中的元素isChecked判断当前是否被选中
          this.traverseChildNodes(row.children, this.$refs.tableRef, true)
          row.isChecked = true; //当前行isChecked标志元素切换为false
        } else {
          this.traverseChildNodes(row.children, this.$refs.tableRef, false)
          row.isChecked = false;
        }
      }
      // 处理父级选择逻辑
      // tableSelect 字段是 handletableSelectionChange 回调回来的
      // 如果不用 this.$nextTick 无法获取到正确数据
      this.$nextTick(() => {
        // 递归寻找当前子节点的父级节点
        let getParentNode = function (data, id) {
          for (let i in data) {
            if (data.hasOwnProperty(i)) {
              if (data[i].id === id) {
                return [data[i]]
              }
              if (data[i].children) {
                let node = getParentNode(data[i].children, id);
                if (node !== undefined) {
                  return node.concat(data[i])
                }
              }
            }
          }
        }
        // 设置checkbox半选择状态
        // 此处的传入的id就是匹配表格id字段的
        let updateCheckboxIndeterminate = function (id, isIndeterminate) {
          setTimeout(() => {
            // el-table不支持checkbox半选 目前方案是遍历dom获取行节点设置样式
            let elementsRow = document.getElementsByClassName("el-table__row");
            for (let i = 0; i < elementsRow.length; i++) {
              let element = elementsRow.item(i);
              // tips: 通过其他手段设置行内row-id的 以下代码需要修改
              let childNode = element.childNodes.item(1); // row-key 字段在dom中的索引   第二列=1
              if (childNode.innerText === `${id}`) {
                let td = element.childNodes.item(0) // 获取要设置半选中状态的checkbox
                let div = td.firstChild; // <div class="cell">
                let label = div.firstChild; // <label class="el-checkbox">
                let span = label.firstChild; // <span class="el-checkbox__input">
                if (isIndeterminate)
                  span.classList.add("is-indeterminate")  // 设置半选中状态
                else
                  span.classList.remove("is-indeterminate")  // 取消半选中状态
              }
            }
          }, 1)

        }
        let parentNode = getParentNode(this.$refs.tableRef.data, row.id)
        // > 1 说明节点有子节点
        if (parentNode.length > 1) {
          // 提取兄弟节点ids
          let siblingNodeIds = parentNode[1].children.map(item => item.id)
          // 提取全选所选择项的ids
          let checkedIds = this.tableSelect.map(item => item.id)
          // 获取兄弟行选择数
          let siblingNodeCheckedIds = siblingNodeIds.filter(id => checkedIds.indexOf(id) !== -1)
          if (siblingNodeCheckedIds.length === siblingNodeIds.length) {
            // 兄弟节点选择数===兄弟节点数   全选
            updateCheckboxIndeterminate(parentNode[1].id, false)
            parentNode[1].isChecked = true
            this.$refs.tableRef.toggleRowSelection(parentNode[1], true)
          } else if (siblingNodeCheckedIds.length === 0) {
            // 兄弟节点选择数===0   全不选
            parentNode[1].isChecked = false
            this.$refs.tableRef.toggleRowSelection(parentNode[1], false)
            updateCheckboxIndeterminate(parentNode[1].id, false)
          } else if (siblingNodeCheckedIds.length < siblingNodeIds.length) {
            parentNode[1].isChecked = true
            this.$refs.tableRef.toggleRowSelection(parentNode[1], true)
            for (let i = 0; i < parentNode.length; i++) {
              if (i > 0) updateCheckboxIndeterminate(parentNode[i].id, true)
            }
          }
        }
      })
    },
    // 当用户手动勾选全选 Checkbox 时触发的事件
    handletableSelectAll(selection) {
      this.$refs.tableRef.data.map(items => {
        if (items.children && items.children.length > 0) {
          if (!items.isChecked) {
            this.$refs.tableRef.toggleRowSelection(items, true);
            items.isChecked = true
            this.traverseChildNodes(items.children, this.$refs.tableRef, true)
            this.deptIds.push(items.did)
          } else {
            this.$refs.tableRef.toggleRowSelection(items, false);
            items.isChecked = false;
            this.traverseChildNodes(items.children, this.$refs.tableRef, false)
            this.deptIds=[]
          }
        } else {

        }
      })
      console.log(this.deptIds)
    },
    // 当选择项发生变化时会触发该事件
    handletableSelectionChange(selection) {
      // let that = this
      // selection.forEach(item => {
      //   that.deptIdsb.push(item.did);
      // });
      // setTimeout(()=>{
      //   var newArr = that.deptIdsb.filter(function(item,index){
      //     return that.deptIdsb.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
      //   });
      //   console.log(newArr)
      // },1)

      // let arr = []
      // for(let i =0;i<selection.length;i++){
      //   arr.push(selection[i].did)

      // }
      //  console.log(arr)
      // if(this.deptIds.length>0){

      // }else{
      //   this.deptIds.push(selection[0].did)
      // }

      // console.log(selection)
      // console.log(this.deptIds)
      // let that = this
      // setTimeout(()=>{
      //   that.tableSelect = selection
      //   console.log(that.tableSelect,Date.parse(new Date()))
      // })

      // this.deptIds = []
      // this.deptIds.push(selection)
      // setTimeout(()=>{
      //   console.log(this.deptIds)
      // },1)

      // this.tableSelect = selection
    },
    // 递归设置子节点
    traverseChildNodes(children, ref, selected) {
      children.map(item => {
        ref.toggleRowSelection(item, selected);
        item.isChecked = selected;
        if (item.children) {
          this.traverseChildNodes(item.children, ref, selected)
        }
      })
    },

    /** 查询参数列表 */
    getList() {
      this.loading = true;
      deptList(this.addDateRange(this.queryParams)).then(response => {
        this.adminList = this.handleTree2(response.data, "id");
        this.loading = false;
        }
      );
    },
    // 同步部门信息
    synchrodeptJob(){
      if(this.queryParams.name){
        deptJob({"name":this.queryParams.name}).then(response =>{
          this.getList();
        })
        localStorage.setItem("timeout","大于10s")
        this.msgSuccess('请在定时任务中部门信息中，选择点击更多--调度日志查询同步进度 ', 5000)
        this.$router.push({path:'/system/job/jobTaskIndex'})
        localStorage.setItem('department', 1)
      }else{
        this.$message.error('同步部门信息不能为空')
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 单选框选中数据
    selectBrand(row) {
      this.tableRadio = row
    },
    /** 获取充值管理的数据用于修改赋值 */
    getListczgl() {
      allRadio().then(response => {
        this.radioList = response.data.map(item=>{
          return {
            identity:item.identity,
            proportion:item.proportion,
            id:item.id
          }
        })
      });
    },
    //批量处理
    batchChange(change){
      this.staffList.deptIds = []
      if(this.$refs.tableRef.selection.length>0){

      }else{
        this.msgError("请选择部门")
      }
      if(this.tableRadio){
        if(change == "1"){
          this.getListczgl()
          this.open = true;
          this.title = "修改参数";
        }else{
          this.loading = true;
          let formData = new FormData();
          let arr = []
          for(let i = 0;i<this.$refs.tableRef.selection.length;i++){
            arr.push(this.$refs.tableRef.selection[i].did)
          }
          formData.append('deptIds[]',arr);
          formData.append('radioId',1);
          formData.append('isBinding',0);
          updataByDept(formData).then(response =>{
            this.loading = false;
            this.msgSuccess(`解绑完成`)
            this.getList();
          }).catch(err=>{
            this.loading = false;
          })
        }
      }else{
        this.$message.error('请勾选需要处理充值到账比例部门信息')
      }
    },
    /** 提交按钮 */
    submitForm() {
      let formData = new FormData();
      let arr = []
      for(let i = 0;i<this.$refs.tableRef.selection.length;i++){
        arr.push(this.$refs.tableRef.selection[i].did)
      }
      formData.append('deptIds[]',arr);
      this.$refs["queryParams"].validate(valid => {
        if (valid) {
          if(this.queryParams.id){
            this.loading = true;
            formData.append('radioId',this.queryParams.id);
            formData.append('isBinding',1);
            updataByDept(formData).then(response =>{
              this.loading = false;
              this.open = false;
              this.msgSuccess(`绑定完成`)
              this.getList();
              this.reset()
            }).catch(err=>{
              this.loading = false;
            })
          }
        }
      })
    },
  }
};
</script>
<style lang="scss" scoped>
 // 深度选择器 去掉全选按钮
            ::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
                display: none;
            }
</style>
