<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" style="height: 90px">
            <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="organizationTree" :treeData="organizationData" @select="organizationSelectionHandler" :model="currentOrganization.name" placeholder="请选择业务单元"></Select-Box>
              </el-col>
              <el-col :span="8">
                <Select-Box ref="depTree" v-if="selectValueId === 'depSel'" :treeData="depData" @select="depSelectionHandler" :model="currentDep.name" placeholder="请选择部门"></Select-Box>
              </el-col>
              <el-col :span="8" :style="{ marginTop: selectValueId === 'depSel' ? '8px' : '0' }">
                <el-input v-model.trim="searchString" placeholder="请输入姓名/曾用名/姓名拼音/手机号码进行查询" size="small" @change="searchChangeHandler" 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">
            <el-row class="header">
              <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="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-row>
            <div class="select-person-box__main" v-loading="loading" :style="{ height: height - 140 + 'px' }">
              <el-checkbox-group v-model="tempSelectionResult" size="mini" class="check-box">
                <el-checkbox v-for="item in tableData" :key="item.id" :label="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 height="36px">选择结果：</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: "SelectUserForGroup",
  props: {
    title: {
      type: String,
      default: "选择用户",
    },
    height: {
      type: Number,
      default: 500,
    },
    //是否为单选
    isSingle: {
      type: Boolean,
      default: false,
    },
    // 选中数据的回显数据
    importData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 传入数据:
    sourceData: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  components: {
    splitPane,
    SelectBox,
  },
  computed: {},
  watch: {},
  data() {
    return {
      searchString: "",
      tableData: [],
      visible: false,
      currentGroupId: "",
      //当前选择业务单元
      currentOrganization: {
        name: "",
        id: "",
      },
      checkedAll: false,
      //当前选择部门
      currentDep: {
        name: "",
        id: "",
      },
      loading: false,
      //业务单元树数据
      organizationData: [],
      //集团树数据
      depData: [],
      //分页 当前页
      pageIndex: 1,
      //分页 大小
      pageSize: 50,
      //分页 总个数
      totalPage: 0,
      //选择结果
      selectionResult: [],
      //暂存选择数据
      tempSelectionResult: [],
      messageBox: "",
      selectValueName: "按组织筛选",
      selectValueId: "orgSel",
      selectData: [
        {
          name: "按组织筛选",
          id: "orgSel",
        },
        {
          name: "按部门筛选",
          id: "depSel",
        },
      ],
      userInfo: "",
    };
  },
  methods: {
    //初始化
    init() {
      this.visible = true;
      this.selectionResult = this.importData;
      this.selectValueId = "orgSel";
      this.selectValueName = "按组织筛选";
      this.loading = true;
      this.tempSelectionResult = [];
      this.pageIndex = 1;
      this.pageSize = 50;
      this.searchString = "";
      this.totalPage = 0;
      this.importData.forEach((item) => {
        this.tempSelectionResult.push(item.id);
      });
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      this.currentGroupId = this.userInfo.user.groupId;
      this.getOrganizationData();
    },
    //关闭前的回调
    handleClose(done) {
      done();
    },
    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;
        }
      }
    },
    //请求业务单元表格数据
    getOrganizationData() {
      let url = "/orgOrganizations/list/all";
      this.$http({
        url: this.$http.adornUrl(url),
        method: "get",
        params: this.$http.adornParams({
          groupId: this.currentGroupId,
        }),
      }).then((result) => {
        if (result.data.code === 40000) {
          if (result.data.list.length > 0) {
            this.organizationData = result.data.list;
            this.currentOrganization.id = this.organizationData[0].id;
            this.currentOrganization.name = this.organizationData[0].name;
            if (this.selectValueId === "orgSel") {
              // 获取集团下的所有用户
              this.getUserData();
            } else {
              this.getDepData();
            }
          } else {
            this.tableData = [];
            this.organizationData = [];
            this.loading = false;
            this.currentOrganization = {
              id: "",
              name: "",
            };
          }
        } else {
          this.$message({
            type: "danger",
            message: result.data.msg,
          });
        }
      });
    },
    // 获取部门树
    getDepData() {
      this.$http({
        url: this.$http.adornUrl("/orgDepartments"),
        method: "get",
        params: this.$http.adornParams({
          organizationId: this.currentOrganization.id,
          withSon: false,
        }),
      }).then((result) => {
        if (result.data.code === 40000) {
          if (result.data.list.length > 0) {
            this.depData = result.data.list;
            this.currentDep.id = this.depData[0].id;
            this.currentDep.name = this.depData[0].name;
            this.getUserData();
          } else {
            this.tableData = [];
            this.depData = [];
            this.loading = false;
            this.currentDep = {
              id: "",
              name: "",
            };
          }
        } else {
          this.$message({
            type: "danger",
            message: result.data.msg,
          });
        }
      });
    },
    // 获取用户列表
    getUserData() {
      this.checkedAll = false;
      this.tableData = [];
      this.$http({
        url: this.$http.adornUrl("/sysUsers/list/forGroupOrOrgOrDep"),
        data: this.$http.adornData({
          current: this.pageIndex,
          size: this.pageSize,
          searchString: this.searchString,
          depId: this.currentDep.id,
          groupId: this.currentGroupId,
          orgId: this.currentOrganization.id,
          selectValueId: this.selectValueId,
        }),
        method: "post",
      }).then((result) => {
        if (result.data.code === 40000) {
          if (result.data.page.records.length > 0) {
            result.data.page.records.forEach((item) => {
              this.tableData.push({ id: item.id, name: item.realName });
            });
          }
          this.loading = false;
          //重置选择结果
          this.totalPage = result.data.page.total;
          this.checkAllFlag();
        } else {
          this.$message({
            type: "danger",
            message: result.data.msg,
          });
        }
      });
    },
    // 筛选条件选择处理
    selectionHandler(data) {
      this.pageIndex = 1;
      this.totalPage = 0;
      this.selectValueName = data.name;
      this.selectValueId = data.id;
      if (this.organizationData.length > 0) {
        this.currentOrganization.id = this.organizationData[0].id;
        this.currentOrganization.name = this.organizationData[0].name;

        if (this.selectValueId === "orgSel") {
          // 获取集团下的所有用户
          this.getUserData();
        } else {
          //请求业务单元数据
          this.getDepData();
        }
      }
    },
    //业务单元选择处理
    organizationSelectionHandler(data) {
      this.currentOrganization = data;
      if (this.selectValueId === "orgSel") {
        this.getUserData();
      } else {
        this.getDepData();
      }
    },
    //部门选择处理
    depSelectionHandler(data) {
      this.currentDep = data;
      this.loading = true;
      this.pageIndex = 1;
      this.pageSize = 50;
      this.totalPage = 0;
      this.checkedAll = false;
      this.getUserData();
    },
    //标签关闭处理
    tagCloseHandler(data) {
      this.tempSelectionResult = this.tempSelectionResult.filter((item) => item !== data.id);
      this.selectionResult = this.selectionResult.filter((item) => item.id !== data.id);
      this.checkedAll = false;
    },
    //清空所有选择
    clearResultHandler() {
      this.checkedAll = false;
      this.tempSelectionResult = [];
      this.selectionResult = [];
    },
    //提交数据处理
    submitResultHandler() {
      //提交结果
      //输出
      this.$emit("submit", this.selectionResult);
      this.visible = false;
    },
    //搜索框值变化处理
    searchChangeHandler(val) {
      if (!this.searchString) {
        this.pageIndex = 1;
        this.totalPage = 0;
        this.tableData = [];
        this.getUserData();
      }
    },
    //搜索处理
    searchHandler() {
      this.tableData = [];
      this.pageIndex = 1;
      this.totalPage = 0;
      this.getUserData();
    },
    //全选处理
    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);
        });
      }
    },
    //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 });
      }
    },
    //分页大小发生变化
    sizeChangeHandler(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getUserData();
    },
    // 分页空间 当前页改变 触发事件方法
    currentChangeHandler(val) {
      this.pageIndex = val;
      this.getUserData();
    },
  },
};
</script>
