<template>
  <div>
    <MegaModal
      width="1200px"
      :title="$t('SELECT_CANDIDATE')"
      :visible.sync="visible"
      :dialog-style="{ top: '30px' }"
      @cancel="closeDialog"
      @ok="handleConfirm"
    >
      <MomTable
        :row-key="rowKey"
        :columns="tableColumns"
        :data-source="tableData"
        :query-param="queryForm"
        :query-param-item="queryFormItem"
        :show-util-operator="false"
        :total="total"
        :page.sync="page"
        :mega-extend="{
          rowAction: false,
        }"
        :scroll="{ x: true, y: 400 }"
        :row-selection="rowSelection"
        :destroy-on-close="true"
        @search="searchPageData"
      >
        <div slot="toolbar" class="candidate-tip">
          <a-alert type="warning" show-icon class="text-warning">
            <span slot="message" class="text-warning">
              {{ $t("CANDIDATE_SELECT_TIP") }}
            </span>
          </a-alert>
        </div>
        <span slot="userType" slot-scope="text">
          {{ getAttrValue(typeList, text) }}
        </span>
      </MomTable>
      <a-form-model ref="ruleForm" :model="form">
        <a-form-model-item
          prop="comment"
          :label="$t('OPINION')"
          :rules="{
            required: requiredComment,
            message: $t('PLACEENTER'),
            trigger: 'blur',
          }"
        >
          <a-textarea
            v-model="form.comment"
            allow-clear
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
      </a-form-model>
    </MegaModal>
  </div>
</template>
<script>
import { Modal as MegaModal } from "@mega-design/ui-vue";

export default {
  components: {
    MegaModal,
  },
  props: {
    url: {
      type: String,
      default: undefined,
    },
    visible: {
      type: Boolean,
      default: false, // 弹框显示、隐藏
    },
    requiredComment: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default() {
        return {};
      },
    },
    showKey: {
      type: String,
      default: "name",
    },
    rowKey: {
      type: String,
      default: "id",
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    defaultSelectedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      sexTypeList: [], // 用户性别列表
      statusList: [], // 用户状态列表
      typeList: [], // 用户类型列表
      treeData: [],
      tableData: [],
      // 查询的表单的配置项
      queryForm: {
        userName: "", // 用户名
        employeeNo: "", // 关联员工工号
        name: "", // 姓名
        status: "", // 状态
        mobilePhone: "", // 手机号码
        deptName: "", // 部门名称
        postName: "", // 岗位代码
      },
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
      total: 0,
      page: 1,
      form: {
        comment: undefined,
      },
    };
  },
  computed: {
    defaultValue() {
      if (this.defaultSelectedKeys?.length) {
        return this.defaultSelectedKeys.join();
      }
      if (this.defaultSelectedRows?.length) {
        const newArr = [];
        this.defaultSelectedRows.forEach((item) => {
          newArr.push(item[this.showKey]);
        });
        return newArr.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();
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        userName: {
          label: () => this.$t("USER_NAME"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        employeeNo: {
          label: () => this.$t("EMPLOYEE_NO"), // 员工工号
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        name: {
          label: () => this.$t("NAME"), // 姓名
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        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 },
        },
        postName: {
          label: () => this.$t("POSITION_MAME"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        },
        status: {
          itemType: "select",
          label: () => this.$t("STATUS"),
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    // 表格的配置项
    tableColumns() {
      return [
        {
          dataIndex: "userName",
          title: () => this.$t("USER_NAME"),
          width: 120,
        },
        {
          dataIndex: "employeeNo",
          title: () => this.$t("EMPLOYEE_NO"),
          width: 180,
        },
        {
          dataIndex: "name",
          title: () => this.$t("USER_REAL_NAME"),
          width: 180,
        },
        {
          dataIndex: "sexText",
          sorter: false,
          title: () => this.$t("GENDER"),
          width: 100,
        },
        {
          dataIndex: "userType",
          title: () => this.$t("TYPE"),
          sorter: false,
          scopedSlots: { customRender: "userType" },
          width: 125,
        },
        {
          dataIndex: "mobilePhone",
          sorter: false,
          title: () => this.$t("PHONE_NO"),
          width: 200,
        },
        {
          dataIndex: "deptName",
          title: () => this.$t("DEPARTMENT_NAME"),
          width: 280,
        },
        {
          dataIndex: "postName",
          sorter: false,
          width: 200,
          title: () => this.$t("POSITION_MAME"),
        },
      ];
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
    visible: {
      handler(val) {
        if (val) {
          this.form.comment = undefined;
        }
      },
    },
  },
  methods: {
    // 获取数据字典
    beforeSearch() {
      return Promise.all([
        this.getDictByCode("DIC:CORE:USER_TYPE"),
        this.getDictByCode("DIC:COMMON:SEX_TYPE"),
      ]).then(([typeRes, sexTypeRes]) => {
        this.typeList = typeRes.data.data;
        this.sexTypeList = sexTypeRes.data.data;
      });
    },
    /**
     * 获取table的数据
     */
    searchPageData(params) {
      this.$axios
        .get(this.url, {
          params: {
            ...params,
            ...this.params,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.userVOIPage.records.map((item) => ({
            ...item,
            sexText: this.getAttrValue(this.sexTypeList, item.sex),
            typeText: this.getAttrValue(this.typeList, item.type),
          }));
          this.total = res.data.data.userVOIPage.total;

          this.setSelectedPageRows();
        });
    },
    // 监听确认按钮事件
    handleConfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const newArr = [];
          this.selectedRows.forEach((item) => {
            newArr.push(item[this.showKey]);
          });
          this.value = newArr.join();
          this.$emit(
            "confirm",
            this.selectedKeys,
            this.selectedRows,
            this.form
          );
        }
      });
    },
    closeDialog() {
      this.$emit("cancel");
    },
    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>
