<!-- 勿动 -->
<template>
  <div>
    <span v-if="showSlot" @click="openDialog">
      <slot>
        <a-input
          ref="blurInput"
          read-only
          :value="value || defaultValue"
          :placeholder="$t('PLACESELECT')"
        />
      </slot>
      <a-icon
        v-show="showClear && (value || defaultValue)"
        type="close-circle"
        theme="filled"
        class="closeIcon"
        @click.stop="handleClear"
      />
    </span>
    <MomModalTable
      ref="MomModalTable"
      :modal-props="{
        title: $t('SELECT_USER'),
        visible: visible,
      }"
      :modal-listeners="{
        ok: handleConfirm,
        cancel: closeDialog,
      }"
      :table-props="{
        rowKey: rowKey,
        queryParam: queryForm,
        queryParamItem: queryFormItem,
        columns: tableColumns,
        dataSource: tableData,
        megaExtend: { rowAction: false },
        rowSelection,
        total,
        page,
        showUtilOperator: false,
        wholeExtraHeight: 82,
        customRow: (record) => {
          return {
            on: {
              click: () => handleRowClick(record),
            },
          };
        },
      }"
      :table-listeners="{
        beforeSearch: beforeSearch,
        search: searchPageData,
        'update:page': (current) => {
          page = current;
        },
      }"
    >
      <template slot="lockFlag" slot-scope="text">
        <span :class="[text == 'N' ? 'text-success' : 'text-error']">
          {{ getAttrValue(queryFormItem.lockFlag.options, text) }}
        </span>
      </template>
      <span slot="mgrType" slot-scope="text">
        {{ getAttrValue(typeList, text) }}
      </span>
    </MomModalTable>
  </div>
</template>
<script>
import { uniqBy } from "lodash";
import ApiConstant from "@/api/ApiConstant";
import MomModalTable from "@/components/MomModalTable";

export default {
  components: {
    MomModalTable,
  },
  props: {
    // 需要展示的key
    showKey: {
      type: String,
      default: "userName",
    },
    // 回传的key
    rowKey: {
      type: String,
      default: "userName",
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    // 是否显示slot
    showSlot: {
      type: Boolean,
      default: true,
    },
    // 是否显示清除按钮
    showClear: {
      type: Boolean,
      default: true,
    },
    // 查询的数据去除掉系统管理员
    excludeAdmin: {
      type: String,
      default: "N",
    },
    defaultSelectedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
    searchParams: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      sexTypeList: [], // 用户性别列表
      statusList: [], // 用户状态列表
      typeList: [], // 用户类型列表
      visible: false, // 弹框显示、隐藏
      tableData: [],
      // 查询的表单的配置项
      queryForm: {
        userName: "", // 用户名
        name: "", // 姓名
        lockFlag: "", // 锁定状态
        mobilePhone: "", // 手机号码
        deptName: "", // 部门名称
      },
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
      total: 0,
      page: 1,
    };
  },
  computed: {
    defaultValue() {
      if (this.defaultSelectedKeys?.length) {
        return this.defaultSelectedKeys.join();
      }
      if (this.defaultSelectedRows?.length) {
        return this.defaultSelectedRows
          .map((item) => item[this.showKey])
          .join();
      }
      return undefined;
    },
    selectedRows() {
      let checked = Object.values(this.selectedPageRows).reduce(
        (res, item) => res.concat(item),
        []
      );

      const selectedRowsTmp = this.defaultSelectedRows.filter((item) =>
        this.selectedKeys.includes(item[this.rowKey])
      );

      if (this.multiple) {
        checked = uniqBy(checked.concat(selectedRowsTmp), this.rowKey);
      } else if (checked.length === 0) {
        checked.concat(selectedRowsTmp);
      }

      return checked;
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedKeys,
        type: this.multiple ? "checkbox" : "radio",
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedKeys = selectedRowKeys;
          this.setSelectedPageRows();
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.disabled,
          },
        }),
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        userName: {
          label: () => this.$t("USER_NAME"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        name: {
          label: () => this.$t("NAME"), // 姓名
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        lockFlag: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("ORG_LOCK_STATUS"),
        },
        mobilePhone: {
          label: () => this.$t("PHONE_NO"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        companyName: {
          label: () => this.$t("COMPANY_NAME"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        deptName: {
          label: () => this.$t("DEPARTMENT_NAME"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
      });
    },
    // 表格的配置项
    tableColumns() {
      return [
        {
          dataIndex: "userName",
          title: () => this.$t("USER_NAME"),
          width: 120,
          ellipsis: true,
        },
        {
          dataIndex: "name",
          title: () => this.$t("USER_REAL_NAME"),
          width: 180,
          ellipsis: true,
        },
        {
          dataIndex: "sexText",
          sorter: false,
          title: () => this.$t("GENDER"),
          width: 100,
          ellipsis: true,
        },
        {
          dataIndex: "lockFlag",
          title: () => this.$t("ORG_LOCK_STATUS"),
          width: 120,
          sorter: false,
          scopedSlots: { customRender: "lockFlag" },
        },
        {
          dataIndex: "mgrType",
          title: () => this.$t("TYPE"),
          sorter: false,
          scopedSlots: { customRender: "mgrType" },
          width: 125,
          ellipsis: true,
        },
        {
          dataIndex: "mobilePhone",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("PHONE_NO"),
          width: 200,
        },
        {
          dataIndex: "deptName",
          title: () => this.$t("DEPARTMENT_NAME"),
          width: 280,
          ellipsis: true,
        },
      ];
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
  },
  methods: {
    handleRowClick(record) {
      const index = this.selectedKeys.findIndex(
        (key) => key === record[this.rowKey]
      );
      if (index > -1) {
        this.selectedKeys.splice(index, 1);
      } else if (this.multiple) {
        this.selectedKeys.push(record[this.rowKey]);
      } else {
        this.selectedKeys = [record[this.rowKey]];
      }
      this.setSelectedPageRows();
    },
    // 打开弹框事件
    openDialog() {
      this.visible = true;
      const selectedKey = this.defaultSelectedRows
        .map((item) => item[this.rowKey])
        .concat(this.defaultSelectedKeys);
      this.selectedKeys = uniqBy([].concat(selectedKey));
      this.value = "";
    },
    beforeSearch() {
      Promise.all([
        this.getDictByCode("DIC:CORE:UESR_MGR_TYPE"),
        this.getDictByCode("DIC:COMMON:SEX_TYPE"),
        this.getDictByCode("DIC:CORE:USER_LOCK"),
      ]).then(([typeRes, sexTypeRes, lockRes]) => {
        this.typeList = typeRes.data.data;
        this.sexTypeList = sexTypeRes.data.data;
        this.queryFormItem.lockFlag.options = lockRes.data.data;
      });
    },
    /**
     * 获取table的数据
     */
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/user/search`, {
          params: {
            ...params,
            ...this.searchParams,
            enableFlag: "Y",
            excludeAdmin: this.excludeAdmin,
          },
        })
        .then((res) => {
          if (res.data.data.records.length > 0) {
            this.tableData = res.data.data.records.map((item) => ({
              ...item,
              sexText: this.getAttrValue(this.sexTypeList, item.sex),
              typeText: this.getAttrValue(this.typeList, item.type),
            }));
          } else {
            this.tableData = res.data.data.records;
          }
          // 数据需要禁用时使用
          // start
          this.defaultSelectedRows.forEach((itemA) => {
            const index = this.tableData.findIndex(
              (e) => e[this.rowKey] === itemA[this.rowKey]
            );
            if (index > -1) {
              this.$set(this.tableData[index], "disabled", itemA.disabled);
            } else {
              this.$set(this.tableData[index], "disabled", false);
            }
          });
          // end
          this.total = res.data.data.total;
          this.setSelectedPageRows();
        });
    },
    // 监听确认按钮事件
    handleConfirm() {
      // input显示的值
      this.value = this.selectedRows.map((item) => item[this.showKey]).join();
      // 回传 keys rows
      this.$emit("confirm", this.selectedKeys, this.selectedRows);
      this.visible = false;
    },
    clearForm() {
      this.$set(this, "queryForm", {
        userName: "", // 用户名
        name: "", // 姓名
        lockFlag: "", // 锁定状态
        mobilePhone: "", // 手机号码
        deptName: "", // 部门名称
      });
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
      this.clearForm();
    },
    // 清空数据
    handleClear() {
      this.value = "";
      this.selectedKeys = [];
      this.$emit("confirm", [], []);
    },
    setSelectedPageRows() {
      if (!this.multiple) {
        Object.keys(this.selectedPageRows).forEach((e) => {
          if (e !== this.page) {
            delete this.selectedPageRows[e];
          }
        });
      }
      this.tableData.forEach((item) => {
        if (this.selectedKeys.includes(item[this.rowKey])) {
          if (this.selectedPageRows[this.page]?.length) {
            !this.selectedPageRows[this.page]
              .map((e) => e[this.rowKey])
              .includes(item[this.rowKey]) &&
              this.selectedPageRows[this.page].push(item);
          } else {
            this.$set(this.selectedPageRows, this.page, [item]);
          }
        } else if (this.selectedPageRows[this.page]?.length) {
          const index = this.selectedPageRows[this.page].findIndex(
            (e) => e[this.rowKey] === item[this.rowKey]
          );
          index > -1 && this.selectedPageRows[this.page].splice(index, 1);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.closeIcon {
  position: absolute;
  right: 10px;
  top: 14px;
  font-size: 12px;
  cursor: pointer;
}
</style>
