<template>
  <el-dialog :visible.sync="visible" :title="title" :before-close="handleClose" custom-class="select-shell-drawer" width="1200px" append-to-body>
    <div class="split-pane" :style="{ height: height + 'px' }">
      <split-pane :default-percent="70" :min-percent="30" split="vertical">
        <template slot="paneL">
          <div class="select-header">
            <el-row :gutter="12" style="height: 100%">
              <el-col :span="8">
                <Select-Box ref="selectTree" @select="selectionHandler" :treeData="selectData" :model="selectValueName" placeholder="请选择筛选条件"></Select-Box>
              </el-col>
              <el-col :span="8">
                <Select-Box ref="depTree" :treeData="store.depData" @select="depSelectionHandler" :model="currentDep.name" placeholder="请选择部门" v-if="selectValueId === 'depSel'"></Select-Box>
              </el-col>
              <el-col :span="8">
                <Select-Box ref="roleTree" :treeData="store.roleData" @select="roleSelectionHandler" :model="currentRole.name" placeholder="请选择角色" v-if="selectValueId === 'roleSel'"></Select-Box>
              </el-col>
              <el-col :span="8">
                <el-input v-model="searchString" placeholder="请输入姓名/曾用名/姓名拼音/手机号码进行查询" size="small" clearable>
                  <el-button slot="append" size="small" type="success" icon="el-icon-search" @click="searchHandler"></el-button>
                </el-input>
              </el-col>
            </el-row>
          </div>
          <div class="select-person-box" :style="{ height: selectBodyHeight }">
            <el-row class="header">
              <el-col :span="24" style="text-align: right">
                <el-col :span="4" style="line-height: 30px" class="text-align-left">
                  <el-checkbox v-if="!isSingle" v-model="checkedAll" @change="selectAllHandler" label="全选">全选 </el-checkbox>
                </el-col>
                <el-col :span="isSingle ? 24 : 20" style="text-align: right">
                  <el-pagination
                    @size-change="sizeChangeHandler"
                    @current-change="currentChangeHandler"
                    :current-page="pageIndex"
                    :page-sizes="[50, 100, 150, 200]"
                    :page-size="pageSize"
                    :total="totalPage"
                    layout="total,  prev, pager, next, jumper, sizes"
                  >
                  </el-pagination>
                </el-col>
              </el-col>
            </el-row>
            <div class="select-person-box__main" v-loading="loading" :style="{ height: selectBodyMainHeight }">
              <el-checkbox-group v-model="tempSelectionResult" size="mini" class="check-box">
                <el-checkbox v-for="item in tableData" :label="item.id" :key="item.id" @change="checkboxChangeHandler(item)" border>{{ item.name }} </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </template>
        <template slot="paneR">
          <el-container class="select-result-box" direction="vertical">
            <el-header>选择结果：</el-header>
            <el-main>
              <div class="tags-box">
                <el-tag size="medium" style="margin: 0 5px 5px 0" v-for="item in selectionResult" :key="item.id" closable @close="tagCloseHandler(item)">{{ item.name }} </el-tag>
              </div>
              <div class="footer-box">
                <el-button size="small" @click="clearResultHandler">清空选择结果</el-button>
                <el-button type="success" size="small" @click="submitResultHandler">保存选择结果 </el-button>
              </div>
            </el-main>
          </el-container>
        </template>
      </split-pane>
    </div>
  </el-dialog>
</template>

<script>
import splitPane from "vue-splitpane";
import SelectBox from "./SelectBox";

export default {
  name: "SelectUserForSecretLevel",
  computed: {
    selectBodyMainHeight() {
      return this.height - 100 + "px";
    },
    selectBodyHeight() {
      return this.height - 50 + "px";
    },
  },
  props: {
    title: {
      type: String,
      default: "选择用户",
    },
    height: {
      type: Number,
      default: 540,
    },
    //选中数据的回显数据
    importData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //是否为单选
    isSingle: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 模糊查询字段
      searchString: "",
      visible: false,
      // 所选部门
      currentDep: {
        name: "",
        id: "",
      },
      // 所选角色
      currentRole: {
        name: "",
        id: "",
      },
      //表格数据
      tableData: [],
      dataListLoading: false,
      //当前页面索引
      pageIndex: 1,
      //当前页显示多少条
      pageSize: 50,
      //总页数
      totalPage: 0,
      defaultProps: {
        label: "name",
        id: "id",
      },
      store: {
        //部门目录数据
        depData: [],
        roleData: [],
      },
      selectValueName: "无条件筛选",
      selectValueId: "noSel",
      selectData: [
        {
          name: "无条件筛选",
          id: "noSel",
        },
        {
          name: "按部门筛选",
          id: "depSel",
        },
        {
          name: "按角色筛选",
          id: "roleSel",
        },
      ],
      // 单选
      tempSelectionResult: [],
      // 多选
      // 选择结果
      selectionResult: [],
      loading: false,
      checkedAll: false,
      selectType: "",
      messageBox: "",
    };
  },
  components: {
    splitPane,
    SelectBox,
  },
  methods: {
    selectionHandler(data) {
      this.selectValueName = data.name;
      this.selectValueId = data.id;
      if (data.id === "noSel") {
        this.currentRole.id = "";
        this.currentRole.name = "";
        this.currentDep.id = "";
        this.currentDep.name = "";
        this.getSysUsers();
      } else if (data.id === "depSel") {
        this.currentRole.id = "";
        this.currentRole.name = "";
        if (this.store.depData.length > 0) {
          this.currentDep.id = this.store.depData[0].id;
          this.currentDep.name = this.store.depData[0].name;
        } else {
          this.currentDep.id = "";
          this.currentDep.name = "";
        }
        this.getSysUsers();
      } else if (data.id === "roleSel") {
        this.currentDep.id = "";
        this.currentDep.name = "";
        if (this.store.roleData.length > 0) {
          this.currentRole.id = this.store.roleData[0].id;
          this.currentRole.name = this.store.roleData[0].name;
        } else {
          this.currentRole.id = "";
          this.currentRole.name = "";
        }
        this.getSysUsers();
      }
    },
    depSelectionHandler(data) {
      this.currentDep = data;
      this.currentRole.id = "";
      this.currentRole.name = "";
      this.checkedAll = false;
      this.getSysUsers();
    },
    roleSelectionHandler(data) {
      this.currentRole = data;
      this.currentDep.id = "";
      this.currentDep.name = "";
      this.checkedAll = false;
      this.getSysUsers();
    },
    //关闭前的回调
    handleClose(done) {
      done();
    },
    init() {
      this.tableData = [];
      this.visible = true;
      this.selectionResult = [];
      this.tempSelectionResult = [];
      this.selectionResult = this.importData;
      this.importData.forEach((item) => {
        this.tempSelectionResult.push(item.id);
      });
      this.selectValueName = "无条件筛选";
      this.selectValueId = "noSel";
      this.store.depData = [];
      this.currentDep.id = "";
      this.currentDep.name = "";
      this.store.roleData = [];
      this.currentRole.id = "";
      this.currentRole.name = "";
      let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      // 请求部门目录数据
      this.getDepData(userInfo.user.organizationId);
      // 请求角色树目录
      this.getRoleData();
      // 获得用户列表
      this.getSysUsers();
    },
    getDepData(organizationId) {
      let url = "/orgDepartments";
      this.$http({
        url: this.$http.adornUrl(url),
        method: "get",
        params: this.$http.adornParams({
          organizationId: organizationId,
          withSon: false,
        }),
      }).then((result) => {
        if (result.data.code === 40000) {
          this.store.depData = result.data.list;
        } else {
          this.store.depData = [];
        }
      });
    },
    getRoleData() {
      this.$http({
        url: this.$http.adornUrl("/sysRoles/list/all"),
        method: "get",
        params: this.$http.adornParams({
          app_id: this.$cookie.get("appName"),
        }),
      }).then((result) => {
        this.store.roleData = result.data.list;
      });
    },
    getSysUsers() {
      this.checkedAll = false;
      this.tableData = [];
      let depId = this.currentDep.id;
      let roleId = this.currentRole.id;
      this.dataListLoading = true;
      let url = "/sysUsers/listForDepOrRole";
      let params = {
        depId: depId,
        roleId: roleId,
        current: this.pageIndex,
        size: this.pageSize,
        searchString: this.searchString,
      };

      this.$http({
        url: this.$http.adornUrl(url),
        data: this.$http.adornData(params),
        method: "post",
      })
        .then((response) => {
          response.data.page.records.forEach((item) => {
            this.tableData.push({ id: item.id, name: item.realName });
          });
          this.totalPage = response.data.page.total;
          this.dataListLoading = false;
          this.checkAllFlag();
        })
        .catch(() => {
          this.tableData = [];
          this.dataListLoading = false;
        });
    },
    //标签关闭处理
    tagCloseHandler(data) {
      this.selectionResult = this.selectionResult.filter((item) => item.id !== data.id);
      this.tempSelectionResult = this.tempSelectionResult.filter((item) => item !== data.id);
      this.checkedAll = false;
    },
    //清空所有选择
    clearResultHandler() {
      this.selectionResult = [];
      this.checkedAll = false;
      this.tempSelectionResult = [];
    },
    //提交数据处理
    submitResultHandler() {
      //提交结果
      //输出
      this.$emit("submit", this.selectionResult);
      this.visible = false;
    },
    //搜索处理
    searchHandler() {
      this.pageIndex = 1;
      this.getSysUsers();
    },
    //分页大小发生变化
    sizeChangeHandler(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.tableData = [];
      this.getSysUsers();
    },
    // 分页空间 当前页改变 触发事件方法
    currentChangeHandler(val) {
      this.pageIndex = val;
      this.tableData = [];
      this.getSysUsers();
    },
    //checkbox 变化处理
    checkboxChangeHandler(data) {
      //是否单选
      if (!this.isSingle) {
        // 多选
        let has = false;
        this.selectionResult.forEach((item, index) => {
          if (item.id === data.id) {
            this.selectionResult.splice(index, 1);
            has = true;
            this.checkedAll = false;
          }
        });
        if (!has) {
          this.selectionResult.push({
            id: data.id,
            name: data.name,
          });
          this.checkAllFlag();
        }
      } else {
        // 单选
        this.tempSelectionResult = [];
        this.selectionResult = [];
        this.tempSelectionResult.push(data.id);
        this.selectionResult.push({ id: data.id, name: data.name });
      }
    },
    selectAllHandler(val) {
      if (val) {
        //全选
        this.tableData.forEach((item, index) => {
          let has = this.tempSelectionResult.indexOf(item.id);
          if (has === -1) {
            this.tempSelectionResult.push(item.id);
            this.selectionResult.push({
              id: item.id,
              name: item.name,
            });
          }
        });
      } else {
        //全不选
        this.tableData.forEach((item, index) => {
          this.tempSelectionResult = this.tempSelectionResult.filter((itemA) => itemA !== item.id);
          this.selectionResult = this.selectionResult.filter((itemB) => itemB.id !== item.id);
        });
      }
    },
    checkAllFlag() {
      let selectedIdList = [];
      this.selectionResult.forEach((selected) => {
        selectedIdList.push(selected.id);
      });
      if (this.tableData.length > 0) {
        let existAllFlag = true;
        this.tableData.forEach((item) => {
          if (selectedIdList.indexOf(item.id) < 0) {
            existAllFlag = false;
          }
        });
        if (existAllFlag) {
          this.checkedAll = true;
        }
      }
    },
  },
};
</script>
