<template>
  <MegaSplitPanes class="setting-user-page">
    <MegaSplitPane size="18">
      <a-tree
        v-if="treeData.length"
        :block-node="true"
        :default-expand-all="true"
        :tree-data="treeData"
        :replace-fields="{
          children: 'children',
          key: 'id',
          value: 'id',
          title: 'label',
        }"
        @select="handleNodeClick"
      >
      </a-tree>
      <div v-else>
        {{ $t("NO_DATA") }}
      </div>
    </MegaSplitPane>
    <MegaSplitPane size="82">
      <MomTable
        ref="MomTable"
        row-key="id"
        :row-selection="rowSelection"
        :columns="columns"
        :data-source="tableData"
        :query-param="queryParam"
        :query-param-item="queryParamItem"
        :action-buttons="actionButtons"
        :page.sync="page"
        :total="total"
        :mega-extend="{
          rowAction: {
            width: 172,
          },
        }"
        @beforeSearch="beforeSearch"
        @search="searchPageData"
        @copy="handleCopy"
        @edit="handleEdit"
        @delete="handleDelete"
      >
        <div slot="toolbar" class="button-top-table">
          <a-button
            v-if="hasAuth('USER_MANAGEMENT:ADD')"
            type="primary"
            @click="handleAdd"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('USER_MANAGEMENT:EXPORT')"
            class="btn__green-1"
            icon="to-top"
            :disabled="!tableData.length"
            @click="handleExportExcel"
          >
            {{ $t("EXPORT") }}
          </a-button>
          <MomImportButton
            v-if="hasAuth('USER_MANAGEMENT:IMPORT')"
            object-name="USER"
          />
          <a-button
            v-if="hasAuth('USER_MANAGEMENT:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
          <a-button
            v-if="hasAuth('USER_MANAGEMENT:PRINT')"
            type="primary"
            @click="handPrint"
          >
            <Icon type="icon-dayinguanli05-dayinshouquan" :size="16"></Icon>
            {{ $t("PRINT_LOGIN_CODE") }}
          </a-button>
        </div>
        <span slot="sex" slot-scope="text">
          {{ getAttrValue(sexTypeList, text) }}
        </span>
        <span slot="lockFlag" slot-scope="text">
          <span v-if="text == 'Y'" style="color: #0fd19c">
            {{ text === "Y" ? "启用" : "禁用" }}
          </span>
          <span v-else style="color: #d45f5f">
            {{ text === "Y" ? "启用" : "禁用" }}
          </span>
        </span>
        <div slot="lockFlag" slot-scope="text, record">
          <span v-if="record.lockFlag == 'N'" style="color: #0fd19c">{{
            formatData(lockStatusList, record.lockFlag)
          }}</span>
          <span v-else style="color: #d45f5f">{{
            formatData(lockStatusList, record.lockFlag)
          }}</span>
        </div>
        <span slot="enableFlag" slot-scope="text, record">
          <span v-if="record.enableFlag == 'Y'" style="color: #0fd19c">
            {{ formatData(enableFlaglist, record.enableFlag) }}
          </span>
          <span v-else style="color: #d45f5f">
            {{ formatData(enableFlaglist, record.enableFlag) }}
          </span>
        </span>
      </MomTable>
    </MegaSplitPane>
  </MegaSplitPanes>
</template>
<script>
import { SplitPanes as MegaSplitPanes, Icon } from "@mega-design/ui-vue";
import { mapState } from "vuex";
import { exportExcel } from "@/utils";
import ApiConstant from "@/api/ApiConstant";
import MomImportButton from "@/components/MomImportButton";
import FieldMixin from "@/components/ExtendAndAuthField/mixin";
import { ELabel } from "@/utils/print/eLabel";

export default {
  components: {
    MegaSplitPanes,
    MomImportButton,
    // eslint-disable-next-line vue/no-unused-components
    Icon,
    MegaSplitPane: MegaSplitPanes.Pane,
  },
  mixins: [FieldMixin],
  data() {
    return {
      uploadUrl: `${ApiConstant.PREFIX_CORE}/api/mdm/user/upload`,
      treeData: [],
      sortParams: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      sexTypeList: [], // 用户性别列表
      statusList: [], // 用户状态列表
      tableData: [],
      enableFlaglist: [],
      // 表格列配置项
      columns: [
        {
          dataIndex: "userName",
          title: () => this.$t("USER_NAME"),
          minWidth: 120,
          ellipsis: true,
        },
        {
          dataIndex: "name",
          ellipsis: true,
          title: () => this.$t("USER_REAL_NAME"),
          width: 120,
        },
        {
          dataIndex: "sex",
          ellipsis: true,
          title: () => this.$t("GENDER"),
          width: 90,
          sorter: false,
          scopedSlots: { customRender: "sex" },
        },
        {
          dataIndex: "enableFlag",
          ellipsis: true,
          title: () => this.$t("ORG_ENABLE_STATUS"),
          width: 120,
          sorter: false,
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "lockFlag",
          ellipsis: true,
          title: () => this.$t("ORG_LOCK_STATUS"),
          width: 120,
          sorter: false,
          scopedSlots: { customRender: "lockFlag" },
        },
        {
          dataIndex: "mobilePhone",
          ellipsis: true,
          title: () => this.$t("PHONE_NO"),
          sorter: false,
          width: 150,
        },
        {
          dataIndex: "deptName",
          ellipsis: true,
          title: () => this.$t("DEPARTMENT_NAME"),
          width: 200,
        },
        {
          dataIndex: "updateBy",
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ],
      detailWidth: 350,
      lockStatusList: [],
      total: 0,
      page: 1,
      // 当前点击节点的类型和编码
      currentClickNode: {},
      tableNameList: [
        {
          key: "sys_user",
          tab: "用户管理",
        },
      ],
      dataAttr: {
        tableColumns: "columns",
        queryFormItem: "queryParamItem",
        queryForm: "queryParam",
      },
      eLabelResponse: "",
      eLabel: null, // elabel对象
      // 查询的表单的配置项
      queryParam: {
        userName: "", // 用户名
        name: "", // 姓名
        enableFlag: "", // 状态
        lockFlag: "", // 状态
        mobilePhone: "", // 手机号码
        deptName: "", // 部门名称
      },
      selectedRowKeys: [],
      actionButtons: [
        (h, { record }) => {
          return (
            this.hasAuth("USER_MANAGEMENT:COPY") &&
            record.mgrType !== "SUPER_ADMIN" &&
            record.mgrType !== "SYSTEM_ADMIN" && (
              <a-button type="link" onClick={() => this.handleCopy(record)}>
                <a-icon type="copy" title={this.$t("COPY")} />
              </a-button>
            )
          );
        },
        (h, { record }) => {
          return (
            this.hasAuth("USER_MANAGEMENT:EDIT") &&
            record.mgrType !== "SUPER_ADMIN" &&
            record.mgrType !== "SYSTEM_ADMIN" && (
              <a-button type="link" onClick={() => this.handleEdit(record)}>
                <a-icon type="edit" title={this.$t("EDIT")} />
              </a-button>
            )
          );
        },
        (h, { record }) => {
          return (
            this.hasAuth("USER_MANAGEMENT:DELETE") &&
            record.mgrType !== "SUPER_ADMIN" &&
            record.mgrType !== "SYSTEM_ADMIN" &&
            record.id !== this.user.id && (
              <a-button type="link" onClick={() => this.handleDelete(record)}>
                <a-icon type="delete" title={this.$t("DELETE")} />
              </a-button>
            )
          );
        },
        (h, { record }) =>
          record.enableFlag === "Y" &&
          record.mgrType !== "SUPER_ADMIN" &&
          record.mgrType !== "SYSTEM_ADMIN" &&
          record.id !== this.user.id &&
          this.hasAuth("USER_MANAGEMENT:ENABLED") && (
            <a-button
              type="link"
              title={this.$t("DISABLED")}
              onClick={() =>
                this.handleStatus(
                  { status: "N", id: record.id, enableFlag: "enableFlag" },
                  "DISABLED_USER_INFO",
                  "DISABLED",
                  "DISABLE_SUCCESS"
                )
              }>
              <Icon
                type="icon-ins-stop"
                size={15}
                class="text-error"
                title={this.$t("DISABLED")}
              />
            </a-button>
          ),
        (h, { record }) =>
          record.enableFlag === "N" &&
          record.mgrType !== "SUPER_ADMIN" &&
          record.mgrType !== "SYSTEM_ADMIN" &&
          record.id !== this.user.id &&
          this.hasAuth("USER_MANAGEMENT:ENABLED") && (
            <a-button
              type="link"
              title={this.$t("ENABLED")}
              onClick={() =>
                this.handleStatus(
                  { status: "Y", id: record.id, enableFlag: "enableFlag" },
                  "ENABLED_USER_INFO",
                  "ENABLED",
                  "ENABLE_SUCCESS"
                )
              }>
              <Icon
                type="icon-ins-check-circle"
                class="text-success"
                title={this.$t("ENABLED")}
              />
            </a-button>
          ),
        (h, { record }) =>
          record.lockFlag === "N" &&
          record.mgrType !== "SUPER_ADMIN" &&
          record.mgrType !== "SYSTEM_ADMIN" &&
          this.hasAuth("USER_MANAGEMENT:LOCK") && (
            <a-button
              type="link"
              title={this.$t("LOCK")}
              onClick={() =>
                this.handleStatus(
                  { status: "Y", id: record.id },
                  "LOCK_USER_INFO",
                  "LOCK",
                  "LOCK_SUCCESS"
                )
              }>
              <a-icon type="lock" title={this.$t("LOCK")} />
            </a-button>
          ),
        (h, { record }) =>
          record.lockFlag === "Y" &&
          record.mgrType !== "SUPER_ADMIN" &&
          record.mgrType !== "SYSTEM_ADMIN" &&
          this.hasAuth("USER_MANAGEMENT:LOCK") && (
            <a-button
              type="link"
              title={this.$t("UNLOCK")}
              onClick={() =>
                this.handleStatus(
                  { status: "N", id: record.id },
                  "UNLOCK_USER_INFO",
                  "UNLOCK",
                  "UNLOCK_SUCCESS"
                )
              }>
              <a-icon type="unlock" title={this.$t("UNLOCK")} />
            </a-button>
          ),
        (h, { record }) =>
          this.hasAuth("USER_MANAGEMENT:RESET_PASSWORD") && (
            <a-button
              title={this.$t("RESET_PASSWORD")}
              type="link"
              onClick={() => this.handleResetPwd(record)}>
              <Icon
                type="icon-cur-reload"
                size={15}
                title={this.$t("RESET_PASSWORD")}
              />
            </a-button>
          ),
      ],
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.auth?.user?.user || {},
    }),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 表格搜索配置项
    queryParamItem() {
      return {
        userName: {
          itemType: "input",
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("USER_NAME"),
        },
        name: {
          itemType: "input",
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("USER_REAL_NAME"),
        },
        enableFlag: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("ORG_ENABLE_STATUS"),
        },
        lockFlag: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("ORG_LOCK_STATUS"),
        },
        mobilePhone: {
          itemType: "input",
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("PHONE_NO"),
        },
        deptName: {
          itemType: "input",
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("DEPARTMENT_NAME"),
        },
      };
    },
  },
  mounted() {
    this.getTreeData();
    this.eLabel = new ELabel();
  },
  methods: {
    // 下载模板
    handleDownload() {
      const a = document.createElement("a");
      a.href = "/template/用户导入模板.xlsx";
      a.click();
    },
    handleResetPwd({ id }) {
      this.$confirm({
        title: this.$t("RESET_PASSWORD"),
        content: this.$t("CONFIRM_RESET_PASSWORD"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/sys/user/reset-pwd/${id}`)
            .then(() => {
              this.$message.success(this.$t("RESET_PASSWORD_SUCCESS"));
            });
        },
      });
    },
    // 导出
    handleExportExcel() {
      const params = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
        ...this.currentClickNode,
        ...this.queryParam,
      };
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/sys/user/export`,
        method: "get",
        params,
        responseType: "blob",
      }).then((res) => {
        exportExcel(res.data, `${this.$t("USER_MANAGEMENT")}.xls`);
      });
    },
    /**
     *获取左侧完整部门树图
     */
    getTreeData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`)
        .then((res) => {
          // 设置数据isLeaf字段值为bool类型
          const fn = (data) => {
            data.forEach((item) => {
              // eslint-disable-next-line no-param-reassign
              item.isLeaf = [1, "1"].includes(item.isLeaf);
              if (item?.children?.length) {
                fn(item.children);
              }
            });
          };
          fn(res.data.data);
          this.treeData = res.data.data;
        });
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 获取数据字典
    beforeSearch() {
      Promise.all([
        this.getDictByCode("DIC:COMMON:ENABLE_FLAG"),
        this.getDictByCode("DIC:COMMON:SEX_TYPE"),
        this.getDictByCode("DIC:CORE:USER_LOCK"),
        this.queryField(),
      ]).then(([statusRes, sexTypeRes, lockRes]) => {
        this.queryParamItem.lockFlag.options = lockRes.data.data;
        this.enableFlaglist = statusRes.data.data;
        this.lockStatusList = lockRes.data.data;
        this.queryParamItem.enableFlag.options = statusRes.data.data;
        this.sexTypeList = sexTypeRes.data.data;
      });
    },
    tableColumnsFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        if (obj[val]) {
          this.columns.forEach((item, index) => {
            if (item.dataIndex === val) {
              this.columns.splice(index, 1);
            }
          });
        }
      }
    },
    /**
     * 获取右侧table的数据
     */
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/user/search`, {
          params: {
            ...params,
            deptId: this.currentClickNode.deptId || null,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 点击节点查询数据
    handleNodeClick(node) {
      this.currentClickNode = {};
      // eslint-disable-next-line prefer-destructuring
      this.currentClickNode.deptId = node[0];
      this.$refs.MomTable?.query();
    },
    handleAdd() {
      this.$router.push({
        path: "/upms/system/setting/user/add",
      });
    },
    handleCopy(row) {
      this.$router.push({
        path: "/upms/system/setting/user/add",
        query: {
          id: row.id,
        },
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/upms/system/setting/user/edit",
          query: {
            id: row.id,
          },
        },
        vm: this,
        del: false,
      });
    },
    handleStatus(record, infoText, confirmButtonText, tips) {
      this.$confirm({
        title: this.$t(confirmButtonText),
        content: this.$t(infoText),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status, enableFlag } = record;
          if (enableFlag) {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/sys/user/enable/${id}/${status}`
              )
              .then((res) => {
                this.$message.success(this.$t(tips));
                this.$refs.MomTable?.query();
              });
          } else {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/sys/user/lock/${id}/${status}`
              )
              .then((res) => {
                this.$message.success(this.$t(tips));
                this.$refs.MomTable?.query();
              });
          }
        },
      });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(`${ApiConstant.PREFIX_CORE}/api/sys/user/batch-delete`, {
                params: {
                  ids: this.selectedRowKeys.join(","),
                },
              })
              .then((res) => {
                this.selectedRowKeys = [];
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 打印登陆码
    handPrint() {
      if (this.selectedRowKeys.length > 0) {
        const ids = this.selectedRowKeys.join();
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/sys/user/print-user?ids=${ids}`)
          .then((res) => {
            if (res.data.code === 200) {
              this.response = JSON.stringify(res.data.data, null, "\t");
              if (!res.data.data[0].PRINT_NAME) {
                this.$message.error(this.$t("PRINTER_CONNECTION_FAILED"));
                return;
              }
              if (!res.data.data[0].PRINT_IP_PORT) {
                this.$message.error(this.$t("PRINTER_CONNECTION_FAILED"));
                return;
              }
              if (!res.data.data[0].LABEL_FILE) {
                this.$message.error(this.$t("NO_TEMPLATE_FILE"));
                return;
              }
              res.data.data.forEach((item) => {
                this.callELabel(item);
              });
            }
          });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 调用ELabel
    callELabel(data) {
      this.eLabel.disconnect();
      this.eLabel = null;
      this.eLabel = new ELabel();
      this.eLabel.onData = (res) => {
        this.eLabelResponse = res;
      };
      // 建立连接
      this.eLabel.ipAddress = data.PRINT_IP_PORT;
      this.eLabel.connect();
      // 初始化命令
      const command = this.eLabel.COMMAND;
      command.Command = this.eLabel.ACTIONS.PRINT;
      command.PrinterName = data.PRINT_NAME;
      command.LabelFile = data.LABEL_FILE;
      command.ColumnName = Object.keys(data);
      command.ValueList = this.transfer(Object.values(data));
      // 请求
      setTimeout(() => {
        this.eLabel.sendData(JSON.stringify(command));
      }, 500);
    },
    // 数据处理
    transfer(list) {
      // 计算请求长度
      let length = 1;
      list.forEach((item) => {
        if (Array.isArray(item)) {
          length = item.length;
        }
      });
      // 组成数据
      const result = [];
      // eslint-disable-next-line
      for (let i = 0; i < length; i++) {
        result.push(
          list.map((item) => {
            if (Array.isArray(item)) {
              return item[i];
            }
            return item.toString();
          })
        );
      }
      return result;
    },
    handleDelete({ id }) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/user/${id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.setting-user-page {
  position: absolute;
}

/deep/.form-header {
  height: 56px;
}
/deep/.btn-item {
  padding-left: 30px;
}

/deep/.ant-table td {
  white-space: nowrap;
}
/deep/.ant-btn-link {
  padding: 0;
}
</style>
