<template>
  <div>
    <PageTable ref="userTable" action="QueryUser" :columnsFn="generateColumns">
      <Form :model="formSearch" ref="roleFormSearch" slot="search-bar" :label-width="100">
        <Row :gutter="24">
          <Col span="8">
            <Form-item prop="userCode" :label="$t('module.userManage.account')">
              <Input class="w100" type="text" v-model="formSearch.userCode" maxlength="30"/>
            </Form-item>
          </Col>
          <Col span="8">
            <Form-item prop="userName" :label="$t('module.userManage.name')">
              <Input class="w100" type="text" v-model="formSearch.userName" maxlength="30"/>
            </Form-item>
          </Col>
          <Col span="8">
            <Form-item prop="total" :label="$t('module.userManage.assignRoles')">
              <Select class="w100" v-model="formSearch.total" clearable>
                <Option value="1">{{$t("common.yes")}}</Option>
                <Option value="0">{{$t("common.no")}}</Option>
              </Select>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="24">
          <Col span="6">
            <Form-item prop="enabled" :label="$t('module.userManage.status')">
              <Select class="w100" v-model="formSearch.enabled" clearable>
                <Option value="1">{{$t("common.enable")}}</Option>
                <Option value="0">{{$t("common.disable")}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col span="6">
            <Form-item prop="type" :label="$t('module.userManage.type')">
              <Select class="w100" v-model="formSearch.type" clearable>
                <Option value="0">{{$t('module.userManage.systemUser')}}</Option>
                <Option value="1">{{$t("module.userManage.LDAPUser")}}</Option>
                <Option value="2">{{$t('module.userManage.customUser')}}</Option>
              </Select>
            </Form-item>
          </Col>
          <Col span="6">
            <Form-item prop="effectBegin" :label="$t('module.userManage.validDateBegin')">
              <DatePicker class="w100" type="date" transfer="true" v-model="formSearch.effectBegin"></DatePicker>
            </Form-item>
          </Col>
          <Col span="6">
            <Form-item prop="effectEnd" :label="$t('module.userManage.validDateEnd')">
              <DatePicker class="w100" type="date" transfer="true" v-model="formSearch.effectEnd"></DatePicker>
            </Form-item>
          </Col>
        </Row>
      </Form>
      <div slot="handle-bar">
        <Button @click.native="formReset" type="text">{{$t("common.reset")}}</Button>
        <Button @click.native="search" type="ghost">{{$t("common.search")}}</Button>
      </div>
      <div slot="table-bar">
        <Button type="ghost" icon="plus-round" size="small" @click="edit()">{{$t("common.create")}}</Button>
        <!-- <Button type="ghost" icon="trash-a" size="small" @click="deleteUser">{{$t("common.delete")}}</Button> -->
        <Button type="ghost" icon="unlocked" size="small" @click="toggleLock(1)">{{$t("common.enable")}}</Button>
        <Button type="ghost" icon="locked" size="small" @click="toggleLock(0)">{{$t("common.disable")}}</Button>
        <Button type="ghost" icon="person-add" size="small" @click="importUser()">{{$t("module.userManage.importUser")}}</Button>
        <Button type="ghost" icon="person-add" size="small" @click="exportUser()">{{$t("module.userManage.exportUser")}}</Button>
        <!-- <Button type="ghost" icon="person-add" size="small" @click="importGroup()">{{$t("module.userManage.importFromEmployees")}}</Button> -->
      </div>
    </PageTable>
    <Modal v-model="modal" width="820" :closable="true">
      <div slot="header">
        <span class="send-mail-title">{{$t("module.userManage.importOrganizations")}}</span>
      </div>
      <div class="modal-group">
        <el-tree :data="baseData" :props="defaultProps" accordion lazy :load="loadNode" @node-expand="nodeExpand" @node-collapse="nodeCollapse" @node-click="nodeCallback"></el-tree>
      </div>
      <div class="modal-group-person">

        <div class="group-person-item" v-for="(item,index) in userList" :key="index" :class="item.isCheck?'active':''" @click="selectUser(item)">{{item.userName}}</div>
        <div class="transfer-panel-empty">{{$t("module.userManage.noData")}}</div>
      </div>
      <div class="modal-group-button">
        <div class="modal-center ivu-transfer-operation">
          <Button type="ghost" size="small" @click.native="plusUser">
            <Icon type="chevron-right"></Icon>
          </Button>
          <Button type="ghost" size="small" @click.native="minusUser">
            <Icon type="chevron-left"></Icon>
          </Button>
        </div>
      </div>
      <div class="modal-group-select">
        <div class="group-person-select" v-for="(item,index) in selectList" :key="index" :class="item.isCheck?'active':''" @click="deleteSelected(item)">{{item.value.userName}}</div>
        <div class="transfer-panel-empty">{{$t("module.userManage.noData")}}</div>
      </div>
      <div slot="footer">
        <Button type="ghost" @click.native="onCancel">{{$t("module.userManage.cancelImport")}}</Button>
        <Button type="primary" @click.native="onOk">{{$t("module.userManage.confirmImport")}}</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import UserEditPage from "./UserEdit.vue";
import ImportExcel from "./ImportExcel.vue";
import AssignDimension from "../dimension/AssignDimension.vue";
export default {
  name: 'user-list',
  components: {
  },
  data() {
    return {
      editIconLoading: false,
      formSearch: {
        userCode: "",
        userName: "",
        mobile: "",
        total: "",
        enabled: "",
        type: "",
        effectBegin: "",
        effectEnd: ''
      },
      file: {
        excelFile: ""
      },
      modal: false,
      baseData: [],
      currnodeId: "CR000",
      userListStore: {},
      userList: [],
      selectList: [],
      defaultProps: {
        children: "children",
        label: "name",
        depId: "CR000"
      },
      uploader: undefined,
      sortData: ""
    };
  },
  computed: {
    currentUser() {
      return this.$store.state.userInfo;
    }
  },
  created() {

  },
  mounted() {

  },

  methods: {
    generateColumns() {
      return [
        {
          type: "selection",
          width: 50,
          fixed: 'left'
        },
        {
          title: this.$t('common.operating'),
          width: 50,
          fixed: 'left',
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: this.getOperation(params.row.userId, params.row.version)
              }
            });
          }
        },
        {
          title: `${this.$t('module.userManage.account')}／LDAP ${this.$t('common.account')}`,
          width: 180,
          align: "center",
          key: "userCode",
          sortable: 'custom'
        },
        {
          title: this.$t('module.userManage.name'),
          width: 120,
          align: "center",
          key: "userName",
          sortable: 'custom'
        },
        {
          title: '职位',
          key: 'positionNames',
        },
        {
          title: this.$t('module.userManage.org'),
          width: 120,
          align: "center",
          key: "orgNames"
        },
        {
          title: this.$t('common.role'),
          width: 80,
          align: "center",
          key: "roleNames",
          render: (h, params) => {
            let roles = params.row.roleNames ? params.row.roleNames.split(",") : [];
            return h(
              "Poptip",
              {
                props: {
                  trigger: "hover",
                  title: (!!params.row.roleNames ? roles.length : 0) + this.$t('module.userManage.roles'),
                  placement: "bottom"
                }
              },
              [
                h("Tag", !!params.row.roleNames ? roles.length : 0),
                h(
                  "div",
                  {
                    slot: "content"
                  },
                  [
                    h(
                      "ul",
                      roles.map(item => {
                        return h(
                          "li",
                          {
                            style: {
                              textAlign: "center",
                              padding: "4px"
                            }
                          },
                          item
                        );
                      })
                    )
                  ]
                )
              ]
            );
          }
        },
        {
          title: this.$t('common.status'),
          width: 110,
          align: "center",
          key: "enabled",
          render: (h, params) => {
            // console.log(params.row.enabled, !!params.row.enabled);
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: !!params.row.enabled ? "blue" : "red"
                }
              },
              !!params.row.enabled ? this.$t('common.enable') : this.$t('common.disable')
            );
          }
        },
        {
          title: this.$t('module.userManage.type'),
          key: "type",
          align: "center",
          width: 120,
          render: (h, params) => {
            return h(
              "span",
              this.userTypeText(params.row.type)
            );
          }
        },
        /*{
          title: this.$t('module.userManage.validDateBegin'),
          key: "effectBegin",
          width: 110,
          align: "center",
          render: (h, params) => {
            return h('format', {
              props: {
                type: 'date',
                value: params.row.effectBegin,
                param: 'yyyy-MM-dd'
              }
            })
          }
        },
        {
          title: this.$t('module.userManage.validDateEnd'),
          key: "effectEnd",
          width: 110,
          align: "center",
          render: (h, params) => {
            return h('format', {
              props: {
                type: 'date',
                value: params.row.effectEnd,
                param: 'yyyy-MM-dd'
              }
            })
          }
        }*/
      ]
    },
    search(page) {
      this.$refs["userTable"].load(Object.assign({}, this.formSearch, {
        effectBegin: this.formSearch.effectBegin && new Date(this.formSearch.effectBegin).Format('yyyy-MM-dd'),
        effectEnd: this.formSearch.effectEnd && new Date(this.formSearch.effectEnd).Format('yyyy-MM-dd')
      }), page);
    },
    edit(id, version) {
      // if (this.editIconLoading) {
      //   return;
      // }
      new this.$sidelipPage(
        UserEditPage,
        {
          props: {
            id,
            version
          }
        },
        () => {
          this.search(!!id ? "" : 1);
        }
      );
      // this.editIconLoading = true;
      // setTimeout(() => this.editIconLoading = false, 1000);
    },
    editDimension(userId, version) {
      new this.$pageModal(
        AssignDimension,
        {
          props: {
            objectId: userId
          }
        }, (data) => {
        });
    },
    toggleLock(status) {
      let ids = this.getIds();
      if (ids == "") {
        this.$Message.warning({
          content: status == 0 ? this.$t('module.userManage.warning.selectUserByDisable') : this.$t('module.userManage.warning.selectUserByEnable'),
          duration: 1.5
        });
        return;
      }
      new $confirm(`${this.$t('common.confirm')} ${status == 0 ? this.$t('common.disable') : this.$t('common.enable')}?`, this).then(() => {
        this.$store
          .dispatch("ToggleLockUser", {
            ids,
            status
          })
          .then(res => {
            if (!res.success) {
              this.$Message.warning({
                content: res.msg,
                duration: 3
              });
              return;
            }
            this.search();
          });
      });
    },
    deleteUser(user) {
      let userCode = user.userCode;
      let currentUserCode = this.currentUser.userCode;
      if (userCode == currentUserCode) {
        this.$Message.warning({
          content: this.$t('module.userManage.warning.deleteCurrentUser'),
          duration: 1.5
        });
        return;
      }
      let id = user.userId;
      let deleteStr = this.getIds();
      if (deleteStr == "" && typeof id != "string") {
        this.$Message.warning({
          content: this.$t('module.userManage.warning.selectDeleteUser'),
          duration: 1.5
        });
        return;
      }
      new $confirm(`${this.$t('common.confirmDeletion')}`, this).then(() => {
        this.$store.dispatch("DeleteUser", {
          ids: typeof id == "string" ? id : this.getIds()
        }).then(res => {
          if (!res.success) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          this.search();
        });
      });
    },
    getIds() {
      let list = this.$refs["userTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.userId);
      }
      return ids.join(",");
    },
    importGroup() {
      // console.log(this.selectList);
      // console.log(this.userListStore);
      if (!!this.userListStore) {
        for (let i = 0; i < this.selectList.length; i++) {
          let item = this.selectList[i];
          if (
            this.userListStore[item.key] &&
            this.userListStore[item.key].length > 0
          ) {
            for (let k = 0; k < this.userListStore[item.key].length; k++) {
              let storeItem = this.userListStore[item.key][k];
              if (storeItem.userId == item.value.userId) {
                storeItem.isCheck = false;
              }
            }
          }
        }
      }
      this.userList = [];
      this.selectList = [];
      this.modal = true;
    },
    formReset() {
      this.$refs["roleFormSearch"].resetFields();
      this.search(1);
    },
    importUser() {
      //this.modal = true;
      new this.$pageModal(
        ImportExcel,
        {

        }, (data) => {
          this.search();
        }
      )
    },
    exportUser() {
      this.sortData = this.$refs["userTable"].getSortData();
      let ids = this.getIds();
      // if(!!ids){
        this.DownloadFile({
          url: '/sys/account/excel/export/sync',
          method: 'post',
          data: {
            sortDTO: {
              fieldName: this.sortData.fieldName,
              orderBy: this.sortData.orderBy
            },
            userCode: this.formSearch.userCode,
            userName: this.formSearch.userName,
            enabled: this.formSearch.enabled,
            total: this.formSearch.total,
            mobile: this.formSearch.mobile,
            type: this.formSearch.type,
            userIds: ids,
            effectBegin: this.formSearch.effectBegin,
            effectEnd: this.formSearch.effectEnd
          }
        }, this)
      // }else{
      //   this.$Message.warning({
      //     content: this.$t('module.userManage.selectExportItems'),
      //     duration: 2
      //   })
      // }
    },
    // 异步加载数据方法
    loadNode(node, resolve) {
      // console.log(node);
      if (node.data.depId) {
        this.currnodeId = node.data.depId;
        if (
          this.userListStore[this.currnodeId] &&
          this.userListStore[this.currnodeId].length > 0
        ) {
          this.userList = this.userListStore[this.currnodeId];
          return;
        }
        this.$store
          .dispatch("GetGroupByOrg", { orgId: this.currnodeId })
          .then(response => {
            let nextNodes = [];
            if (response.depList.length > 0) {
              for (let i = 0; i < response.depList.length; i++) {
                let depItem = response.depList[i];
                nextNodes.push({
                  name: depItem.orgName,
                  depId: depItem.orgId,
                  children: []
                });
                resolve(nextNodes);
              }
            } else {
              resolve(nextNodes);
            }
            this.userListStore[this.currnodeId] = response.empList;
            this.userList = this.userListStore[this.currnodeId];
            this.$forceUpdate();
          });
      } else {
        this.$store.dispatch("GetGroupByOrg", { orgId: this.currnodeId }).then(response => {
          for (let i = 0; i < response.depList.length; i++) {
            let item = response.depList[i];
            this.baseData.push({
              name: item.orgName,
              depId: item.orgId,
              children: []
            });
          }
          this.userListStore[this.currnodeId] = response.empList;
          for (
            let i = 0;
            i < this.userListStore[this.currnodeId].length;
            i++
          ) {
            let item = this.userListStore[this.currnodeId];
            item.isCheck = false;
          }
          this.$forceUpdate();
        });
      }
    },
    nodeCallback(data) {
      // console.log(data);
    },
    nodeCollapse(data, node) {
      this.userList = [];
    },
    nodeExpand(data, node) {
      this.userList = this.userListStore[data.depId];
      this.$forceUpdate();
    },
    // 选择人员方法
    selectUser(item) {
      item.isCheck = !item.isCheck;
      this.$forceUpdate();
    },
    // 删除选中的人员
    deleteSelected(item) {
      item.isCheck = !item.isCheck;
      this.$forceUpdate();
    },
    // 选中添加处理
    plusUser() {
      if (this.selectList <= 0) {
        for (let i = 0; i < this.userListStore[this.currnodeId].length; i++) {
          let noItem = this.userListStore[this.currnodeId][i];
          if (noItem.isCheck) {
            this.selectList.push({
              key: this.currnodeId,
              value: noItem,
              isCheck: false
            });
          }
        }
      } else {
        for (let i = 0; i < this.userListStore[this.currnodeId].length; i++) {
          let hasItem = this.userListStore[this.currnodeId][i];
          if (hasItem.isCheck) {
            let Index = "";
            Index = this.selectList.findIndex((item, index, arr) => {
              return hasItem.userId == item.value.userId;
            });
            // console.log(Index);
            if (Index < 0) {
              this.selectList.push({
                key: this.currnodeId,
                value: hasItem,
                isCheck: false
              });
            }
            Index = "";
          }
        }
      }
      this.$forceUpdate();
    },
    // 去掉选中处理
    minusUser() {
      let indexArr = [];
      for (let i = 0; i < this.selectList.length; i++) {
        let selItem = this.selectList[i];
        if (selItem.isCheck) {
          indexArr.push(i);
          let userIndex = "";
          userIndex = this.userListStore[
            selItem.key
          ].findIndex((value, index, arr) => {
            return value.userId == selItem.value.userId;
          });

          if (userIndex >= 0) {
            this.userListStore[selItem.key][userIndex].isCheck = false;
          }
          userIndex = "";
        }
      }
      for (let k = 0; k < indexArr.length; k++) {
        let i = this.selectList.findIndex(row => {
          return row.isCheck == true;
        });
        this.selectList.splice(i, 1);
      }
      this.$forceUpdate();
    },
    onOk() {
      if (this.selectList.length <= 0) {
        this.$Message.warning(this.$t('module.userManage.warning.selectFiles'));
        return;
      }
      let userList = [];
      for (let i = 0; i < this.selectList.length; i++) {
        let seItem = this.selectList[i];
        userList.push({
          userCode: seItem.value.userCode,
          userName: seItem.value.userName,
          userId: seItem.value.userId
        });
      }
      this.$store
        .dispatch("ImportGroup", { userList: userList })
        .then(response => {
          this.modal = false;
          if (response.statusCode != "0") {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          this.search(1);
        });
    },
    onCancel() {
      this.modal = false;
    },
    userTypeText(type) {
      switch (type) {
        case 0:
          return this.$t('module.userManage.systemUser');
        case 1:
          return this.$t('module.userManage.LDAPUser');
        case 2:
          return this.$t('module.userManage.customUser');
        default:
          return ''
      }
    },
    getOperation(userId, version) {
      let operations = [];
      operations.push(
        {
          loading: this.editIconLoading,
          type: "icon",
          icon: "md-create",
          text: this.$t('common.edit'),
          handle: () => {
            this.edit(userId, version);
          }
        }
      );
      let dimensionOperationType = this.$store.state.dimensionOperationType;
      if (dimensionOperationType != 1) {
        operations.push(this.getDimension(userId, version));
      }
      return operations;
    },
    getDimension(userId, version) {
      return {
        type: "icon",
        icon: "gear-b",
        text: this.$t('module.userManage.dimensionManage'),
        handle: () => {
          this.editDimension(userId, version);
        }
      };
    }
  }
};
</script>
<style lang="less">
.modal-group-person {
  .group-person-item {
    padding: 5px 10px;
    margin-bottom: 1px;
    // height: 20px;
    // line-height: 20px;
  }
  .group-person-item.active {
    background-color: #f8f8f9 !important;
  }
}
.transfer-panel-empty {
  display: block;
  color: #b4bccc;
}
.group-person-item + .transfer-panel-empty {
  display: none;
}
.group-person-select + .transfer-panel-empty {
  display: none;
}
.group-person-select {
  width: 100%;
  padding: 5px 10px;
  margin-bottom: 1px;
}
  .w100 {
    width: 100%;
  }
</style>
