<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('USE_HISTORY_FORM'),
        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: 92,
        initCall: false,
      }"
      :table-listeners="{
        beforeSearch: beforeSearch,
        search: searchPageData,
        'update:page': (current) => {
          page = current;
        },
      }"
    >
      <span slot="matUnit" slot-scope="text">
        {{ getAttrValue(unitList, text) }}
      </span>
      <template slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          getAttrValue(stateList, record.enableFlag)
        }}</span>
      </template>
    </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: "id",
    },
    // 回传的key
    rowKey: {
      type: String,
      default: "id",
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    // 是否显示slot
    showSlot: {
      type: Boolean,
      default: true,
    },
    // 点检分类id
    pcCategoryId: {
      type: String,
      default: "",
    },
    // 是否显示清除按钮
    showClear: {
      type: Boolean,
      default: true,
    },
    defaultSelectedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否需要点检分类
    needCategory: {
      type: Boolean,
      default: true,
    },
    // 点检项目api
    apiUrl: {
      type: String,
      default: "pcm/pc-frm",
    },
  },
  data() {
    return {
      visible: false, // 弹框显示、隐藏
      tableData: [],
      unitList: [],
      // 查询的表单的配置项
      queryForm: {
        pcFrmName: "", // 表单编码
      },
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
      total: 0,
      page: 1,
      initHeight: 0,
      stateList: [],
    };
  },
  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", {
        pcFrmName: {
          label: () => this.$t("FORM_NAME"),
        },
      });
    },
    // 表格的配置项
    tableColumns() {
      return [
        {
          dataIndex: "pcFrmName", // 点检表单名称
          title: () => `${this.$t("FORM_NAME")}`,
          ellipsis: true,
        },
        {
          dataIndex: "pcFrmVersion", // 点检项名称
          title: () => `${this.$t("EDITION")}`,
          width: 200,
          ellipsis: true,
        },
        {
          dataIndex: "enableFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          width: 200,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        {
          dataIndex: "updateTime", // 更新时间
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ];
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
  },
  methods: {
    // 打开弹框事件
    openDialog() {
      this.visible = true;
      const selectedKey = this.defaultSelectedRows
        .map((item) => item[this.rowKey])
        .concat(this.defaultSelectedKeys);
      this.selectedKeys = uniqBy([].concat(selectedKey));
      this.beforeSearch();
      this.$nextTick(() => {
        if (
          this.$refs.MomModalTable?.$refs?.MomTable?.search instanceof Function
        ) {
          this.$refs.MomModalTable.$refs.MomTable.search();
        }
      });
      this.value = "";
    },
    // 获取数据字典
    beforeSearch() {
      return Promise.all([
        this.getDictByCode("DIC:CORE:MATERIAL_UNIT"),
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 类型数据字典
      ]).then(([unitRes, enableStatus]) => {
        this.unitList = unitRes?.data?.data || [];
        this.stateList = enableStatus.data?.data || [];
      });
    },
    /**
     * 获取table的数据
     */
    searchPageData(params) {
      this.tableData = [];
      const req = {
        ...params,
        enableFlag: "Y",
      };
      if (this.needCategory) {
        req.pcCategoryId = this.pcCategoryId;
      }
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/${this.apiUrl}/search`, {
          params: {
            ...req,
          },
        })
        .then((res) => {
          if (res.data.data.records.length > 0) {
            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;
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
    },
    // 清空数据
    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 scoped lang="less">
@import "@/assets/css/status_epms.less";
.closeIcon {
  position: absolute;
  right: 10px;
  top: 14px;
  font-size: 12px;
  cursor: pointer;
}
</style>
