<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')}${$t('MOLD')}`,
        visible: visible,
      }"
      :modal-listeners="{
        ok: handleConfirm,
        cancel: closeDialog,
      }"
      :table-props="{
        rowKey: rowKey,
        queryParam: queryForm,
        queryParamItem: queryFormItem,
        columns: tableColumns,
        dataSource: tableData,
        megaExtend: { rowAction: false },
        wholeExtraHeight: 70,
        total,
        page,
        showUtilOperator: false,
        initCall: false,
        rowSelection: rowSelectionOne,
        customRow: (record) => {
          return {
            on: {
              click: () => handleRowClick(record),
            },
          };
        },
      }"
      :table-listeners="{
        beforeSearch: beforeSearch,
        reset: handleReset,
        search: searchPageData,
        'update:page': (current) => {
          page = current;
        },
      }"
    >
      <template slot="imgUrl" slot-scope="text, record">
        <img class="eqp_picture" :src="record.imgUrl || defaultImg" alt="" />
      </template>
      <template slot="lockFlag" slot-scope="text, record">
        <span v-if="text === 'Y'">{{
          $t("MOLD") +
          getAttrValue(typeList, record.lockType) +
          $t("APPLICATION_FORM") +
          "-" +
          record.lockName
        }}</span>
      </template>
    </MomModalTable>
  </div>
</template>
<script>
import { uniqBy } from "lodash";
import VueBarcode from "vue-barcode";
import ApiConstant from "@/api/ApiConstant";
import MomModalTable from "@/components/MomModalTable";
import { fetchFileUrl } from "@/utils/file";

import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: {
    MomModalTable,
    // eslint-disable-next-line vue/no-unused-components
    SelectSearch,
    // eslint-disable-next-line vue/no-unused-components
    VueBarcode,
  },
  props: {
    // 需要展示的key
    showKey: {
      type: String,
      default: "id",
    },
    // 回传的key
    rowKey: {
      type: String,
      default: "id",
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    // 是否显示slot
    showSlot: {
      type: Boolean,
      default: true,
    },
    // 是否显示清除按钮
    showClear: {
      type: Boolean,
      default: true,
    },
    defaultSelectedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
    // 接口请求api
    requestApi: {
      type: String,
      default: "/api/epm/mam/mold/search",
    },
    partReturnCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // eslint-disable-next-line
      defaultImg: require("@/assets/img/attachmentImg.png"),
      visible: false, // 弹框显示、隐藏
      tableData: [],
      // 查询的表单的配置项
      queryForm: {
        moldIdList: "",
        moldTypeIdList: "",
      },
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
      total: 0,
      page: 1,
      initHeight: 0,
      typeList: [],
      selectedRowKeysOne: [],
      tableColumns: [
        {
          dataIndex: "moldCode", // 编码
          title: () => this.$t("MOLD_CODE"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "moldName", // 名称
          title: () => this.$t("MOLD") + this.$t("NAME"),
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "moldName" },
        },
        {
          dataIndex: "moldTypeName", // 模具类型名称
          title: () => this.$t("MOLD_TYPE") + this.$t("NAME"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "lockFlag",
          align: "left",
          ellipsis: true,
          sorter: false,
          title: () => this.$t("APPLICATION_STATUS"), // 管控方式
          scopedSlots: { customRender: "lockFlag" },
        },
      ],
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  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,
          },
        }),
      };
    },
    rowSelectionOne() {
      return {
        selectedRowKeys: this.selectedKeys,
        type: "checkbox",
        onChange: (selectedRowKeys, data) => {
          this.selectedKeys = selectedRowKeys;
          this.setSelectedPageRows();
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.lockFlag === "Y",
          },
        }),
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        moldIdList: {
          itemType: "custom",
          label: () => this.$t("MOLD") + this.$t("NAME"),
          customRender: () => {
            return (
              <SelectSearch
                ref={"SelectSearch"}
                queryListKey="moldName"
                requestApi={"/api/epm/mam/mold/search"}
                option-label={"moldName"}
                option-value={"id"}
                needDisabled={false}
                isReset={this.isReset}
                onChange={this.onSelectSearchChange}
              ></SelectSearch>
            );
          },
        },
        moldTypeIdList: {
          itemType: "custom",
          label: () => this.$t("MOLD_TYPE") + this.$t("NAME"),
          customRender: () => {
            return (
              <SelectSearch
                ref={"SelectSearchMoldType"}
                queryListKey="moldTypeName"
                requestApi={"/api/epm/mam/mold-type/search"}
                option-label={"moldTypeName"}
                option-value={"id"}
                needDisabled={false}
                isReset={this.isReset}
                onChange={this.onSelectSearchChangeMoldType}
              ></SelectSearch>
            );
          },
        },
      });
    },
  },
  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 = "";
    },
    onSelectSearchChange(e, ids) {
      this.isReset = false;
      this.queryForm.moldIdList = ids.join(",");
    },
    onSelectSearchChangeMoldType(e, ids) {
      this.isReset = false;
      this.queryForm.moldTypeIdList = ids.join(",");
    },
    // 重置搜索监听事件
    handleReset() {
      this.isReset = true;
      this.$refs.MomModalTable.$refs.MomTable.search();
    },
    // 获取数据字典
    beforeSearch() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:LOCK_FORM_TYPE`
        ), // 锁定单据类型
      ]).then(([typeRes]) => {
        this.typeList = typeRes.data.data;
      });
    },
    /**
     * 获取table的数据
     */
    searchPageData(params) {
      const options = {
        partReturnCode: this.partReturnCode,
        scrapFlag: "Y",
      };
      const searchParams = {
        ...params,
        ...options,
      };
      this.tableData = [];
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}${this.requestApi}`, {
          params: searchParams,
        })
        .then((res) => {
          const { records, total } = res.data.data;
          if (records && records.length > 0) {
            records.map((item, index) => {
              if (item.imgUrl) {
                records[index].imgUrl = fetchFileUrl(item.imgUrl, this);
              }
              return item;
            });
          }
          this.tableData = records;
          this.total = total;
          // 数据需要禁用时使用
          // 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.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", [], []);
    },
    handleRowClick(record) {
      if (record.lockFlag === "Y") return;
      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();
    },
    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">
.closeIcon {
  position: absolute;
  right: 10px;
  top: 14px;
  font-size: 12px;
  cursor: pointer;
}
.eqp_picture {
  width: 50px;
  height: 50px;
}
</style>
