<template>
  <el-dialog :visible.sync="visible" :title="title" :before-close="handleClose" custom-class="select-shell-drawer" width="1200px" append-to-body layout="flex">
    <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="orgTree" :treeData="store.orgData" @select="orgSelectionHandler" :model="currentOrg.name" placeholder="请选择组织" v-if="selectValueId === 'orgSel'"></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">
            <el-row class="header">
              <el-col :span="24" v-if="isSingle" 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 :span="24" v-if="!isSingle">
                <el-col :span="4" style="line-height: 30px" class="text-align-left">
                  <el-checkbox 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-col>
            </el-row>
            <div class="main" :style="{ height: height - 100 + 'px' }">
              <el-checkbox-group v-model="tempSelectionResult" size="mini" class="check-box">
                <el-checkbox v-for="item in dataList" :key="item.id" :label="item.id" @change="checkboxChangeHandler(item)" border>{{ item.realName }} </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.vue";

export default {
  name: "SelectUserForApp",
  props: {
    title: {
      type: String,
      default: "选择用户",
    },
    height: {
      type: Number,
      default: 500,
    },
    //是否为单选
    isSingle: {
      type: Boolean,
      default: false,
    },
    // // 已经选中的数据的集合
    // selectedDatas: {
    //   type: Array,
    //   default: []
    // },
    // 已经选中的数据的集合
    importData: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      // 模糊查询字段
      searchString: "",
      visible: false,
      // 所选组织
      currentOrg: {
        name: "",
        id: "",
      },
      // 所选角色
      currentRole: {
        name: "",
        id: "",
      },
      //表格数据
      dataList: [],
      dataListLoading: false,
      //当前页面索引
      pageIndex: 1,
      //当前页显示多少条
      pageSize: 50,
      //总页数
      totalPage: 0,
      defaultProps: {
        label: "name",
        id: "id",
      },
      store: {
        //组织目录数据
        orgData: [],
        roleData: [],
      },
      selectValueName: "无条件筛选",
      selectValueId: "noSel",
      selectData: [
        {
          name: "无条件筛选",
          id: "noSel",
        },
        {
          name: "按组织筛选",
          id: "orgSel",
        },
        {
          name: "按角色筛选",
          id: "roleSel",
        },
      ],
      tempSelectionResult: [],
      // 选择结果
      selectionResult: [],
      checkedAll: false,
      selectType: "",
      messageBox: "",
      //当前集团ID
      currentOrgGroupId: "",
      //当前应用ID
      currentAppId: "",
    };
  },
  components: {
    splitPane,
    SelectBox,
  },
  methods: {
    selectionHandler(data) {
      this.pageIndex = 1;
      this.totalPage = 0;
      this.selectValueName = data.name;
      this.selectValueId = data.id;
      if (data.id === "noSel") {
        this.currentRole.id = "";
        this.currentRole.name = "";
        this.currentOrg.id = "";
        this.currentOrg.name = "";
        this.getSysUsers();
      } else if (data.id === "orgSel") {
        this.currentRole.id = "";
        this.currentRole.name = "";
        if (this.store.orgData.length > 0) {
          this.currentOrg.id = this.store.orgData[0].id;
          this.currentOrg.name = this.store.orgData[0].name;
          this.getSysUsers();
        } else {
          this.currentOrg.id = "";
          this.currentOrg.name = "";
          this.dataList = [];
        }
      } else if (data.id === "roleSel") {
        this.currentOrg.id = "";
        this.currentOrg.name = "";
        if (this.store.roleData.length > 0) {
          this.currentRole.id = this.store.roleData[0].id;
          this.currentRole.name = this.store.roleData[0].name;
          this.getSysUsers();
        } else {
          this.currentRole.id = "";
          this.currentRole.name = "";
          this.dataList = [];
        }
      }
    },
    orgSelectionHandler(data) {
      this.currentOrg = data;
      this.currentRole.id = "";
      this.currentRole.name = "";
      this.pageIndex = 1;
      this.totalPage = 0;
      this.getSysUsers();
    },
    roleSelectionHandler(data) {
      this.currentRole = data;
      this.currentOrg.id = "";
      this.currentOrg.name = "";
      this.pageIndex = 1;
      this.totalPage = 0;
      this.getSysUsers();
    },
    //关闭前的回调
    handleClose(done) {
      done();
    },
    init(groupId, appId) {
      // 获取集团ID
      this.currentOrgGroupId = groupId;
      // 获取应用ID
      this.currentAppId = appId;
      this.visible = true;
      this.selectionResult = [];
      this.tempSelectionResult = [];
      if (this.importData != null && this.importData != undefined) {
        this.selectionResult = this.importData;
        this.importData.forEach((item) => {
          this.tempSelectionResult.push(item.id);
        });
      }
      this.selectValueName = "无条件筛选";
      this.selectValueId = "noSel";
      this.store.orgData = [];
      this.currentOrg.id = "";
      this.currentOrg.name = "";
      this.store.roleData = [];
      this.currentRole.id = "";
      this.currentRole.name = "";
      this.pageIndex = 1;
      this.totalPage = 0;
      // 请求组织目录数据
      this.getOrgData();
      // 请求角色树目录
      this.getRoleData();
      // 获得用户列表
      this.getSysUsers();
    },
    getOrgData() {
      this.$http({
        url: this.$http.adornUrl("/orgOrganizations"),
        method: "get",
        params: this.$http.adornParams({}),
      }).then((result) => {
        this.store.orgData = result.data.list;
      });
    },
    getRoleData() {
      this.$http({
        url: this.$http.adornUrl("/sysRoles/list/all"),
        method: "get",
        params: this.$http.adornParams({
          app_id: this.currentAppId,
        }),
      }).then((result) => {
        this.store.roleData = result.data.list;
      });
    },
    getSysUsers() {
      let orgId;
      if (this.currentOrg === undefined || this.currentOrg === null) {
        orgId = "";
      } else {
        orgId = this.currentOrg.id;
      }
      let roleId;
      if (this.currentRole === undefined || this.currentRole === null) {
        roleId = "";
      } else {
        roleId = this.currentRole.id;
      }
      this.dataListLoading = true;
      let url = "/sysUsers";
      let params = {
        groupId: this.currentOrgGroupId,
        organizationId: orgId,
        roleId: roleId,
        current: this.pageIndex,
        size: this.pageSize,
        searchString: this.searchString,
        // 查询启用用户，
        type: "2",
      };
      this.$http({
        url: this.$http.adornUrl(url),
        params: this.$http.adornParams(params),
        method: "get",
      })
        .then((response) => {
          this.dataList = response.data.page.records;
          this.totalPage = response.data.page.total;
          this.checkFlg();
          this.dataListLoading = false;
        })
        .catch(() => {
          this.dataList = [];
          this.dataListLoading = false;
        });
    },
    checkFlg() {
      this.checkedAll = false;
      if (this.dataList.length > 0) {
        let checkFLg = true;
        this.dataList.forEach((data) => {
          if (this.selectionResult.length > 0) {
            if (this.selectionResult.findIndex((item) => item.id === data.id) < 0) {
              checkFLg = false;
            }
          } else {
            checkFLg = false;
          }
        });
        if (checkFLg) {
          this.checkedAll = true;
        }
      }
    },
    //标签关闭处理
    tagCloseHandler(data) {
      this.tempSelectionResult = this.tempSelectionResult.filter((item) => item !== data.id);
      this.selectionResult = this.selectionResult.filter((item) => item.id !== data.id);
      this.checkFlg();
    },
    //清空所有选择
    clearResultHandler() {
      this.checkedAll = false;
      this.selectionResult = [];
      this.tempSelectionResult = [];
    },
    //提交数据处理
    submitResultHandler() {
      //提交结果
      //输出
      this.$emit("submit", this.selectionResult);
      this.visible = false;
    },
    //搜索处理
    searchHandler() {
      this.pageIndex = 1;
      this.totalPage = 0;
      this.getSysUsers();
    },
    //分页大小发生变化
    sizeChangeHandler(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getSysUsers();
    },
    // 分页空间 当前页改变 触发事件方法
    currentChangeHandler(val) {
      this.pageIndex = val;
      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.realName,
          });
          this.checkAllFlag();
        }
      } else {
        // 单选
        this.tempSelectionResult = [];
        this.selectionResult = [];
        this.tempSelectionResult.push(data.id);
        this.selectionResult.push({ id: data.id, name: data.realName });
      }
    },
    checkAllFlag() {
      let selectedIdList = [];
      this.selectionResult.forEach((selected) => {
        selectedIdList.push(selected.id);
      });
      if (this.dataList.length > 0) {
        let existAllFlag = true;
        this.dataList.forEach((item) => {
          if (selectedIdList.indexOf(item.id) < 0) {
            existAllFlag = false;
          }
        });
        if (existAllFlag) {
          this.checkedAll = true;
        }
      }
    }, //全选处理
    selectAllHandler(val) {
      //   console.log("选择发生变化", val);
      if (val) {
        //全选
        this.dataList.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.realName,
            });
          }
        });
      } else {
        //全不选
        this.dataList.forEach((item, index) => {
          this.tempSelectionResult = this.tempSelectionResult.filter((itemA) => itemA !== item.id);
          this.selectionResult = this.selectionResult.filter((itemB) => itemB.id !== item.id);
        });
      }
    },
  },
};
</script>
