<template>
  <div>
    <span v-if="showSlot" @click="openDialog">
      <slot>
        <a-input
          ref="blurInput"
          read-only
          :disabled="disabled"
          :value="value || defaultValue"
          :placeholder="$t('PLACESELECT')"
        />
      </slot>
      <a-icon
        v-show="showClear && (value || defaultValue) && !disabled"
        type="close-circle"
        theme="filled"
        class="closeIcon"
        @click.stop="handleClear"
      />
    </span>
    <!-- 国际化选择新增弹框 -->
    <MegaModal
      width="1080px"
      :title="`${$t('PLACESELECT')}${$t('MEMBER')}`"
      :visible="visible"
      :mask-closable="false"
      :destroy-on-close="true"
      @cancel="closeDialog"
    >
      <div class="modal_content flex">
        <a-tabs
          default-active-key="1"
          style="width: 100%"
          @tabClick="handleTabClick"
        >
          <a-tab-pane key="1" :tab="$t('USER')">
            <MomTable
              ref="MomTableSingle"
              row-key="userName"
              :query-param="queryParam"
              :query-param-item="queryParamItem"
              :columns="columns"
              :data-source="tableData"
              :row-selection="rowSelection"
              :show-util-operator="false"
              :total="total"
              :page.sync="page"
              :mega-extend="{
                rowAction: false,
              }"
              @beforeSearch="beforeSearch"
              @search="search"
            >
              <div slot="toolbar" class="button-top-table">
                <a-button @click="handleUserAdd">
                  <a-icon type="plus" /> {{ $t("ADD") }}
                </a-button>
              </div>
              <span slot="sex" slot-scope="text">
                {{ getAttrValue(sexTypeList, text) }}
              </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>
            </MomTable>
          </a-tab-pane>
          <a-tab-pane key="2" :tab="$t('RECEIVER_GROUP')">
            <MomTable
              ref="MomTableGroup"
              row-key="id"
              :query-param="queryParamGroup"
              :query-param-item="queryParamItemGroup"
              :columns="columnsGroup"
              :data-source="tableDataGroup"
              :row-selection="rowSelectionGroup"
              :show-util-operator="false"
              :total="totalGroup"
              :page.sync="pageGroup"
              :mega-extend="{
                rowAction: false,
              }"
              :pagination="{
                current: pageGroup,
                total: Number(totalGroup),
              }"
              @search="searchGroup"
            >
              <div slot="toolbar" class="button-top-table">
                <a-button @click="handleGroupAdd">
                  <a-icon type="plus" /> {{ $t("ADD") }}
                </a-button>
              </div>
            </MomTable>
          </a-tab-pane>
        </a-tabs>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="handleConfirm">
          <i class="iconfont icon-baocun"></i> {{ $t("SAVE") }}
        </a-button>
        <a-button class="iconfont icon-quxiao" @click="closeDialog">
          <i class="iconfont icon-quxiao"></i> {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaModal>
  </div>
</template>
<script>
import { uniqBy } from "lodash";
import { Modal as MegaModal } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaModal,
  },
  props: {
    // 需要展示的key
    showKey: {
      type: Array,
      default() {
        return ["userName", "groupName"];
      },
    },
    // 回传的key
    rowKey: {
      type: Array,
      default() {
        return ["userName", "id"];
      },
    },
    // 当前index
    currentIndex: {
      type: Number,
      default: 0,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    // 是否显示slot
    showSlot: {
      type: Boolean,
      default: true,
    },
    // 是否显示清除按钮
    showClear: {
      type: Boolean,
      default: true,
    },
    defaultSelectedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    pcObjectSourceIdItem: {
      type: String,
      default: "",
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultSelectedGroupRows: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否显示清除按钮
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      date: new Date().getTime(),
      visible: false, // 弹框显示、隐藏
      tableData: [],
      tableDataGroup: [],
      unitList: [],
      sexTypeList: [], // 用户性别列表
      lockStatusList: [],
      // 用户选中
      selectedKeys: [],
      selectedPageRows: {},
      total: 0,
      page: 1,
      // 接受组选中
      selectedGroupKeys: [],
      selectedPageGroupRows: {},
      totalGroup: 0,
      pageGroup: 1,
      value: undefined,
      columnsList: [],
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      pcObjectSourceId: "",
      defaultSelectedList: [],
      // 查询的表单的配置项
      queryParam: {
        userName: "",
      },
      queryParamGroup: {
        groupName: "",
      },
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        userName: {
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          label: () => this.$t("USER_NAME"),
        },
      });
    },
    queryParamItemGroup() {
      return this.$observable("queryParamItemGroup", {
        groupName: {
          label: () => this.$t("RECEIVING_GROUP_NAME"),
        },
      });
    },
    defaultValue() {
      if (this.defaultSelectedKeys?.length) {
        return this.defaultSelectedKeys.join();
      }
      let userKeys = [];
      let groupKeys = [];
      if (this.defaultSelectedRows?.length) {
        userKeys = this.defaultSelectedRows.map(
          (item) => item[this.showKey[0]]
        );
      }
      if (this.defaultSelectedGroupRows?.length) {
        groupKeys = this.defaultSelectedGroupRows.map(
          (item) => item[this.showKey[1]]
        );
      }
      const selectKeys = [...userKeys, ...groupKeys];
      if (selectKeys.length) {
        return selectKeys.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[0]])
      );
      if (this.multiple) {
        checked = uniqBy(checked.concat(selectedRowsTmp), this.rowKey[0]);
      } else if (checked.length === 0) {
        checked.concat(selectedRowsTmp);
      }

      return checked;
    },
    selectedGroupRows() {
      let checked = Object.values(this.selectedPageGroupRows).reduce(
        (res, item) => res.concat(item),
        []
      );

      const selectedRowsTmp = this.defaultSelectedGroupRows.filter((item) =>
        this.selectedGroupKeys.includes(item[this.rowKey[1]])
      );
      if (this.multiple) {
        checked = uniqBy(checked.concat(selectedRowsTmp), this.rowKey[1]);
      } 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,
          },
        }),
      };
    },
    rowSelectionGroup() {
      return {
        selectedRowKeys: this.selectedGroupKeys,
        type: this.multiple ? "checkbox" : "radio",
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedGroupKeys = selectedRowKeys;
          this.setSelectedPageGroupRows();
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.disabled,
          },
        }),
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        pcFrmName: {
          label: () => this.$t("CHECK_OBJECT"),
        },
      });
    },
    columns() {
      return [
        {
          dataIndex: "userName",
          title: () => this.$t("USER_NAME"),
          minWidth: 120,
        },
        {
          dataIndex: "employeeNo",
          title: () => this.$t("EMPLOYEE_NO"),
          width: 120,
        },
        {
          dataIndex: "name",
          title: () => this.$t("USER_REAL_NAME"),
          width: 120,
        },
        {
          dataIndex: "sex",
          title: () => this.$t("GENDER"),
          width: 90,
          sorter: false,
          scopedSlots: { customRender: "sex" },
        },
        {
          dataIndex: "lockFlag",
          title: () => this.$t("ORG_LOCK_STATUS"),
          width: 120,
          sorter: false,
          scopedSlots: { customRender: "lockFlag" },
        },
        {
          dataIndex: "mobilePhone",
          title: () => this.$t("PHONE_NO"),
          sorter: false,
          width: 150,
        },
      ];
    },
    columnsGroup() {
      return [
        {
          dataIndex: "groupCode",
          sorter: false,
          title: () => this.$t("RECEIVING_GROUP_CODE"),
          minWidth: 210,
        },
        {
          dataIndex: "groupName",
          title: () => this.$t("RECEIVING_GROUP_NAME"),
          minWidth: 210,
        },
      ];
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
  },
  methods: {
    // 获取数据字典
    beforeSearch() {
      Promise.all([
        this.getDictByCode("DIC:CORE:USER_LOCK"),
        this.getDictByCode("DIC:COMMON:SEX_TYPE"),
      ]).then(([lockRes, sexTypeRes]) => {
        this.lockStatusList = lockRes.data.data;
        this.sexTypeList = sexTypeRes.data.data;
      });
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 打开弹框事件
    openDialog() {
      if (this.disabled) return;
      this.visible = true;
      const selectedKey = this.defaultSelectedRows
        .map((item) => item[this.rowKey[0]])
        .concat(this.defaultSelectedKeys);
      this.selectedKeys = uniqBy([].concat(selectedKey));
      const selectedGroupKey = this.defaultSelectedGroupRows.map(
        (item) => item[this.rowKey[1]]
      );
      this.selectedGroupKeys = uniqBy([].concat(selectedGroupKey));
    },
    // 点击节点查询数据
    handleTabClick(key) {
      if (key === "1") {
        this.$refs.MomTableSingle?.query();
      } else {
        this.$refs.MomTableGroup?.query();
      }
    },
    /**
     * 获取table的数据
     */
    search(params) {
      this.tableData = [];
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/user/search-with-site`, {
          params: {
            ...params,
            enableFlag: "Y",
          },
        })
        .then((res) => {
          if (res.data.data.records.length > 0) {
            this.tableData = res.data.data.records;
          }
          // end
          this.total = res.data.data.total;
          this.setSelectedPageRows();
        });
    },
    searchGroup(params) {
      this.tableData = [];
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/receiver-group/search`, {
          params: {
            ...params,
            enableFlag: "Y",
          },
        })
        .then((res) => {
          if (res.data.data.records.length > 0) {
            this.tableDataGroup = res.data.data.records;
          }
          // end
          this.totalGroup = res.data.data.total;
          this.setSelectedPageRows();
        });
    },
    handleUserAdd() {
      this.$router.push({
        path: "/upms/system/setting/user",
      });
    },
    handleGroupAdd() {
      this.$router.push({
        path: "/upms/service/message/receiverGroup",
      });
    },
    // 监听确认按钮事件
    handleConfirm() {
      // input显示的值
      const selectedRows = this.selectedRows.map(
        (item) => item[this.showKey[0]]
      );
      const selectedGroupRows = this.selectedGroupRows.map(
        (item) => item[this.showKey[1]]
      );
      this.value = [...selectedRows, ...selectedGroupRows].join();
      // 回传 keys rows
      this.$emit(
        "confirm",
        this.selectedKeys,
        this.selectedRows,
        this.selectedGroupKeys,
        this.selectedGroupRows,
        this.currentIndex
      );
      this.visible = false;
      this.reset();
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
      this.reset();
    },
    reset() {
      this.queryParam.userName = "";
      this.queryParamGroup.groupName = "";
    },
    // 清空数据
    handleClear() {
      this.value = "";
      this.selectedKeys = [];
      this.selectedGroupKeys = [];
      this.$emit("confirm", [], [], [], [], this.currentIndex);
    },
    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[0]])) {
          if (this.selectedPageRows[this.page]?.length) {
            !this.selectedPageRows[this.page]
              .map((e) => e[this.rowKey[0]])
              .includes(item[this.rowKey[0]]) &&
              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[0]] === item[this.rowKey[0]]
          );
          index > -1 && this.selectedPageRows[this.page].splice(index, 1);
        }
      });
    },
    setSelectedPageGroupRows() {
      if (!this.multiple) {
        Object.keys(this.selectedPageGroupRows).forEach((e) => {
          if (e !== this.pageGroup) {
            delete this.selectedPageGroupRows[e];
          }
        });
      }
      this.tableDataGroup.forEach((item) => {
        if (this.selectedGroupKeys.includes(item[this.rowKey[1]])) {
          if (this.selectedPageGroupRows[this.page]?.length) {
            !this.selectedPageGroupRows[this.page]
              .map((e) => e[this.rowKey[1]])
              .includes(item[this.rowKey[1]]) &&
              this.selectedPageGroupRows[this.pageGroup].push(item);
          } else {
            this.$set(this.selectedPageGroupRows, this.pageGroup, [item]);
          }
        } else if (this.selectedPageGroupRows[this.pageGroup]?.length) {
          const index = this.selectedPageGroupRows[this.pageGroup].findIndex(
            (e) => e[this.rowKey[1]] === item[this.rowKey[1]]
          );
          index > -1 &&
            this.selectedPageGroupRows[this.pageGroup].splice(index, 1);
        }
      });
    },
  },
};
</script>
<style scoped lang="less">
.mega-design-business-table {
  margin: 10px;
}
.closeIcon {
  position: absolute;
  right: 10px;
  top: 14px;
  font-size: 12px;
  cursor: pointer;
}
// .mega-design-modal .ant-modal {
//   height: calc(100% - 150px);
// }
// .ant-modal-content {
//   height: 100%;
// }
.modal_content {
  width: 100%;
  height: 100%;
}
</style>
