<template>
  <div class="ContainerBox tableAlign">
    <!-- 备注区域 -->
    <section class="remarkBox">
      <div class="remarkInfo">
        <i class="el-icon-warning-outline el-icon-flag"></i>
        <span>
          1. 若您为{{ $SuperviseStr.depart }}管理员，则只能操作可管理的{{
            $SuperviseStr.depart
          }}，可点击排序列的数值进行{{
            $SuperviseStr.depart
          }}显示排序设置（影响通讯录显示排序）。<br />
          2. 可点击{{ $SuperviseStr.depart }}成员数的数值查看具体的{{
            $SuperviseStr.depart
          }}成员进行管理。<br />
          <!-- <span v-if="homeTemplateBoradType!='rtpayTemplate'">3. 可点击关联的驻勤点名称查看详细的驻勤点信息。</span> -->
        </span>
      </div>
    </section>

    <!-- 按钮区域 -->
    <section class="buttonBox">
      <el-row>
        <el-col :span='20'>
        <el-button type="primary" @click="addDept"
          >添加{{ $SuperviseStr.depart }}</el-button
        >
        <el-button @click="importDept"
          >导入{{ $SuperviseStr.depart }}</el-button
        >
        <el-button :disabled="disabled" @click="moveDept"
          >批量转移{{ $SuperviseStr.depart }}成员</el-button
        >
        <el-button :disabled="disabled" @click="ImDept"
          >批量设置通讯录权限</el-button
        >
        <el-button @click="exportExcel">导出</el-button>
        <el-button type="danger" :disabled="disabled" @click="patchDel"
          >批量删除</el-button
        >
        </el-col>
        <el-col :span='4'>
          <el-input v-model="search" placeholder="请输入部门名称" clearable/>
        </el-col>
      </el-row>
    </section>

    <!-- 选中表格内容展示区域 -->
    <section class="TableSelectBox" v-if="multipleSelection.length">
      <span
        ><i class="el-icon-warning-outline el-icon-flag"></i>已选中：<span
          v-for="(item, index) in multipleSelection"
          :key="index"
          >{{ item.name
          }}<b v-if="index != multipleSelection.length - 1">,</b></span
        ></span
      >
    </section>

    <!-- 内容区域 -->
    <section class="contentBox">
      <el-table
        :data="treeTable"
        ref="districtTable"
        max-height="500"
        default-expand-all="true"
        row-key="id"
        :lazy="true"
        :expand-row-keys="expandRow"
        @selection-change="handleSelectionChange"
        @select-all="handleSelectionAllChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- <el-table-column  prop="name"  label="部门名称"  width="180">
            </el-table-column> 
            <el-table-column  prop="displayOrder"  label="排序"  width="150">
                <template slot-scope="scope">
                    <span>
                     <em class="bluelink" title="点击编辑排序" @click.stop="displayOrderClick(scope.row,scope.$index)" v-if="!scope.row.displayOrderCheck">{{scope.row.displayOrder}}</em>
                      <strong v-if="scope.row.displayOrderCheck" class="displayOrderInput"><el-input v-model="scope.row.displayOrder"/><i><img src="~@/assets/staffImgs/save.png"/></i><i><img src="~@/assets/staffImgs/close.png"/></i></strong>
                     </span>
                </template>
            </el-table-column> 
            <el-table-column  prop="totalMember"  label="部门成员数"  width="180">
                <template slot-scope="scope">
                    <span class="bluelink" @click="totalMemberClick(scope.row)">
                        {{scope.row.totalMember}}
                    </span>
                </template>
            </el-table-column> 
            <el-table-column  prop="permissionType"  label="部门成员通讯录权限"  width="180">
            </el-table-column>  -->
        <el-table-column
          v-for="(item, index) in tableColumn"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :align="item.align"
          v-if="item.show"
        >
          <template slot-scope="scope">
            <span v-if="item.prop == 'permissionType'">
              {{
                scope.row[item.prop] == "JustOnDepart"
                  ? `可见所在${$SuperviseStr.depart}成员`
                  : ""
              }}
              {{ scope.row[item.prop] == "JustSelf" ? "可见自己" : "" }}
              {{
                scope.row[item.prop] == "OnDepartAndSub"
                  ? `可见所在${$SuperviseStr.depart}及下级${$SuperviseStr.depart}成员`
                  : ""
              }}
              {{
                scope.row[item.prop] == "Special"
                  ? `可见指定${$SuperviseStr.depart}` +
                    "(" +
                    scope.row.allowedDepartsStr +
                    ")"
                  : ""
              }}
              {{ scope.row[item.prop] == "Whole" ? "可见全部成员" : "" }}
            </span>
            <span v-else-if="item.prop == 'displayOrder'">
              <em class="bluelink">
                <el-popover
                  :ref="`popover-${scope.$index}`"
                  placement="right"
                  width="100"
                  trigger="click"
                >
                  <strong class="displayOrderInput">
                    <el-input
                      type="number"
                      v-model.number="scope.row[item.prop]"
                      clearable
                    />
                    <i @click.stop="saveok(scope.row, scope)"
                      ><img src="~@/assets/staffImgs/save.png" /></i
                    ><i @click="close(scope.row, scope)"
                      ><img src="~@/assets/staffImgs/close.png"
                    /></i>
                  </strong>
                  <span slot="reference">{{
                    scope.row.displayOrderNumber
                  }}</span>
                </el-popover>
              </em>
            </span>
            <span v-else-if="item.prop == 'totalMember'">
              <span class="bluelink" @click="totalMemberClick(scope.row)">
                查看成员
              </span>
            </span>

            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              @click="editDept(scope.row)"
              type="text"
              size="small"
              class="primaryColor"
              >编辑</el-button
            >
            <el-button
              @click="delDept(scope.row)"
              type="text"
              size="small"
              class="dangerColor"
              v-if="scope.row.parentId"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </section>

    <!-- 添加编辑部门弹窗 -->
    <DeptDialog
      :showdialog.sync="showdialog"
      :getTreeDepartlist="tableData"
      @refurlist="refurlist"
      ref="popChildren"
    ></DeptDialog>

    <!-- 导入部门弹窗 -->
    <ImportDeptDialog
      :showdialogImport.sync="showdialogImport"
      :getTreeDepartlist="tableData"
      @refurlist="refurlist"
      ref="ImportpopChildren"
    ></ImportDeptDialog>

    <!-- 批量转移部门成员弹窗 -->
    <MoveDeptDialog
      :showdialogMove.sync="showdialogMove"
      :getTreeDepartlist="tableData"
      @refurlist="refurlist"
      ref="MovepopChildren"
    ></MoveDeptDialog>

    <!-- 批量设置通讯录权限弹窗 -->
    <ImDeptDialog
      :showdialogIm.sync="showdialogIm"
      :getTreeDepartlist="tableData"
      @refurlist="refurlist"
      ref="ImpopChildren"
    ></ImDeptDialog>

    <!-- 部门成员数弹窗 -->
    <UserDeptDialog
      :showdialogUser.sync="showdialogUser"
      :getTreeDepartlist="tableData"
      @refurlist="refurlist"
      ref="UserpopChildren"
    ></UserDeptDialog>
  </div>
</template>
<script>
import {
  StaffDepartmentListApi,
  delDepartmentsApi,
  displayOrderApi,
  exportDepartListExcelApi
} from "@/api/staffApi.js";
import DeptDialog from "./components/DeptDialog.vue";
import ImportDeptDialog from "./components/ImportDeptDialog.vue";
import MoveDeptDialog from "./components/MoveDeptDialog.vue";
import ImDeptDialog from "./components/ImDeptDialog.vue";
import UserDeptDialog from "./components/UserDeptDialog.vue";
export default {
  data() {
    return {
      search:"",
      expandRow: [],
      tableData: [],
      multipleSelection: [], //全选列表
      tableColumn: [
        {
          prop: "name",
          label: `${$SuperviseStr.depart}名称`,
          width: "400",
          align: "left",
          show: true,
        },
        {
          prop: "displayOrder",
          label: "排序",
          width: "80",
          align: "center",
          show: true,
        },
        {
          prop: "totalMember",
          label: `${$SuperviseStr.depart}成员数`,
          width: "180",
          align: "center",
          show: true,
        },
        {
          prop: "permissionType",
          label: `${$SuperviseStr.depart}成员通讯录权限`,
          width: "",
          align: "center",
          show: true,
        },
      ],
      showdialog: false,
      showdialogImport: false,
      showdialogMove: false,
      showdialogIm: false,
      showdialogUser: false,
      disabled: true, //默认禁用
      isAllSelect: false, //是否全选
      displayOrderShow: false,
      homeTemplateBoradType:localStorage.getItem("homeTemplateBoradType") || "",
    };
  },
  components: {
    DeptDialog,
    ImportDeptDialog,
    MoveDeptDialog,
    ImDeptDialog,
    UserDeptDialog,
  },
  created() {
    this.tableDatalist(); //表格列表
  },
  computed:{
     treeTable(){
       let searchValue=this.search
       if(searchValue){
        //  return this.tableData.filter(item=>{
        //    return Object.keys(item).some(its=>{
        //      return String(item[its]).toLowerCase().indexOf(searchValue)>-1
        //    })
        //  })
        let treeData=this.tableData
        let handleTreeData=this.handleTreeData(treeData,searchValue)
        console.log(handleTreeData)
        this.setExpandRow(handleTreeData)
        console.log(this.expandRow)
        this.expandRow=this.expandRow.join(",").split(",")//返回数组id ['id1','id2']
        return handleTreeData  //匹配返回过滤查询到的父子树数据
       }
       console.log(this.tableData)
       return this.tableData //没匹配返回全部
     }
  },
  watch: {
    multipleSelection() {
      //复选框选中启用按钮
      if (this.multipleSelection.length) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
    },
  },
  methods: {
    //树形表格过滤
    handleTreeData(treeData, searchValue){
      // debugger
      if(!treeData||treeData.length==0) return [];
      const array=[];
      for(let i=0;i<treeData.length;i++){
              let match=false;
              for(let pro in treeData[i]){
                if(typeof(treeData[i][pro])=='string'){
                  match |=treeData[i][pro].includes(searchValue);
                  if(match) break;
                }
              }
              if(this.handleTreeData(treeData[i].children,searchValue).length>0||match){
                array.push({...treeData[i],children:this.handleTreeData(treeData[i].children,searchValue)})                
              }              
      } 
      console.log(array)
      return array;
    },
     //将过滤好的树形数据展开
    setExpandRow(handleTreeData){
       if(handleTreeData.length){
          for(let i of handleTreeData){
             this.expandRow.push(i.id)
             if(i.children.length){
               this.setExpandRow(i.children)
             }
          }
       }
    }, 
    exportExcel() {
      //导出
      let obj2 = { domainId: this.$route.query.domainId };
      exportDepartListExcelApi(this.params, obj2).then((response) => {
        console.log(response);
        const content = response;
        const blob = new Blob([content]);
        const fileName = `导出.xls`;
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      });
    },
    tableDatalist() {
      //表格列表
      let obj = { domainId: this.$route.query.domainId }; //获取url域domainId
      StaffDepartmentListApi(obj).then((response) => {
        if (response.data) {
          this.tableData = response.data;
          this.sortTableData(this.tableData);
        }
      });
    },
    sortTableData(arr) {
      //递归排序
      if (arr.length) {
        arr.forEach((item) => {
          item.displayOrderNumber = item.displayOrder;
          let allowedDepartsStr = [];
          if (item.allowedDeparts && item.allowedDeparts.length) {
            item.allowedDeparts.forEach((its) => {
              allowedDepartsStr.push(its.name);
            });
            item.allowedDepartsStr = allowedDepartsStr.join(",");
          }
          if (item.children.length) {
            this.sortTableData(item.children);
          }
        });
      }
    },
    handleSelectionChange(val) {
      //选中全选
      console.log(val);
      this.multipleSelection = val;
    },
    handleSelectionAllChange(selection, first) {
      //全选
      if (!first) {
        this.isAllSelect = !this.isAllSelect;
      }
      selection.map((el) => {
        if (el.children) {
          el.children.map((j) => {
            this.toggleSelection(j, this.isAllSelect);
          });
          if (el.children.length > 0) {
            this.handleSelectionAllChange(el.children, true);
          }
        }
      });
    },
    toggleSelection(row, select) {
      //全选选中与取消选中
      if (select) {
        this.$refs.districtTable.toggleRowSelection(row, select); //全选选中
      } else {
        this.$refs.districtTable.clearSelection(); //取消选中
      }
    },
    addDept() {
      //新增
      this.showdialog = true;
      this.$refs.popChildren.getTableRow({}, 0, this.tableData);
    },
    editDept(row) {
      console.log(row)
      //编辑
      this.showdialog = true;
      this.$refs.popChildren.getTableRow(row, 1, this.tableData);
    },
    delDept(row) {
      //删除
      //删除选中表格数据
      let ids = [row.id];
      let obj2 = { domainId: this.$route.query.domainId }; //获取url域domainId
      if (Object.keys(row) != "") {
        this.$confirm("此操作将永久删除此对应数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delDepartmentsApi(ids, obj2).then((response) => {
              if (response.status == 200) {
                this.tableDatalist(); //表格列表
              }
            });
          })
          .catch(() => {
            // this.radio = ""; //清空选中
          });
      }
    },
    patchDel() {
      //批量删除
      let obj2 = { domainId: this.$route.query.domainId }; //获取url域domainId
      if (this.multipleSelection.length) {
        this.$confirm("此操作将永久删除此对应数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let ids = [];
            this.multipleSelection.forEach((item) => {
              ids.push(item.id);
            });
            delDepartmentsApi(ids, obj2).then((response) => {
              if (response.status == 200) {
                this.tableDatalist(); //表格列表
              }
            });
          })
          .catch(() => {
            // this.radio = ""; //清空选中
          });
      }
    },
    importDept() {
      this.showdialogImport = true;
    },
    moveDept() {
      this.showdialogMove = true;
      this.$refs.MovepopChildren.getTableRow(this.multipleSelection, 0);
    },
    ImDept() {
      this.showdialogIm = true;
      this.$refs.ImpopChildren.getTableRow(this.multipleSelection, 0);
    },
    saveok(row, scope) {
      //保存排序
      console.log(row);
      console.log(scope);
      let obj2 = { domainId: this.$route.query.domainId };
      displayOrderApi(row, obj2).then((response) => {
        if (response.status == 200) {
          this.tableDatalist(); //表格列表
          scope._self.$refs[`popover-${scope.$index}`][0].doClose();
        }
      });
    },
    close(row, scope) {
      //关闭排序
      this.tableDatalist(); //表格列表
      scope._self.$refs[`popover-${scope.$index}`][0].doClose();
    },
    totalMemberClick(row) {
      //点击部门成员数弹窗
      this.showdialogUser = true;
      this.$refs.UserpopChildren.getTableRow(row, 0);
    },
    refurlist() {
      //弹窗后刷新列表
      this.tableDatalist(); //表格列表
    },
  },
};
</script>
<style lang="scss">
.ContainerBox {
  .el-table tr td.is-left {
    text-align: left !important;
  }
  .remarkBox {
    .remarkInfo {
      background: #fafafa;
      color: #666666;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      line-height: 30px;
      padding: 10px;
      display: flex;
      .el-icon-flag {
        margin-top: 9px;
        color: #ffc108;
        margin-right: 10px;
      }
    }
  }
  .primaryColor {
    color: #108ee9;
  }
  .dangerColor {
    color: red;
  }
  .bluelink {
    color: #409eff;
    cursor: pointer;
  }
  .TableSelectBox {
    display: flex;
    background: #e6f3fc;
    color: #666666;
    border: 1px solid #d4f0fc;
    border-radius: 4px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 5px 0;
    span {
      padding: 0 5px;
      line-height: 20px;
      i {
        margin-left: 5px;
        margin-right: 5px;
        color: #2e8ad7;
      }
    }
  }
}

.displayOrderInput {
  display: flex;
  align-items: center;
  // .el-input{width: 80%;}
  i {
    margin-left: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
</style>
