<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)"
        type="close-circle"
        theme="filled"
        class="closeIcon"
        @click.stop="handleClear"
      />
    </span>
    <!-- 国际化选择新增弹框 -->
    <MegaModal
      width="1280px"
      :title="`${$t('PLACESELECT')}${$t('CHECK_OBJECT')}`"
      :visible="visible"
      :mask-closable="false"
      :destroy-on-close="true"
      @cancel="closeDialog"
    >
      <div class="modal_content">
        <MomTable
          ref="MomTable"
          :row-key="rowKey"
          :query-param="queryParam"
          :query-param-item="queryParamItem"
          :columns="columns"
          :data-source="tableData"
          :row-selection="rowSelection"
          :show-util-operator="false"
          :mega-extend="{
            rowAction: false,
          }"
          :total="total"
          :page.sync="page"
          @beforeSearch="beforeSearch"
          @search="search"
        />
      </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: String,
      default: "code",
    },
    // 回传的key
    rowKey: {
      type: String,
      default: "code",
    },
    // 当前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 [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否显示清除按钮
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      date: new Date().getTime(),
      visible: false, // 弹框显示、隐藏
      tableData: [],
      unitList: [],
      // 查询的表单的配置项
      queryForm: {
        pcFrmName: "", // 表单编码
      },
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
      total: 0,
      page: 1,
      dataSource: [], // 表格数据
      defaultList: [
        {
          dataIndex: "moldCode", // 系称
          title: () => this.$t("MOLD_CODE"),
          minWidth: 200,
        },
        {
          dataIndex: "moldName", // 名称
          title: () => this.$t("MOLD") + this.$t("NAME"),
          minWidth: 200,
        },
      ],
      columnsList: [],
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      defaultSelectedList: [],
      // 查询的表单的配置项
      queryParam: {
        name: "",
      },
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        name: {
          label: () => `${this.$t("NAME")}`,
        },
      });
    },
    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("CHECK_OBJECT"),
        },
      });
    },
    columns() {
      return [...this.defaultList, ...this.columnsList];
    },
  },
  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.value = "";
    },
    // 获取数据字典
    beforeSearch() {},
    /**
     * 获取table的数据
     */
    search(params) {
      this.tableData = [];
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold/search`, {
          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();
        });
    },
    // 监听确认按钮事件
    handleConfirm() {
      // input显示的值
      this.value = this.selectedRows.map((item) => item[this.showKey]).join();
      // 回传 keys rows
      this.$emit(
        "confirm",
        this.selectedKeys,
        this.selectedRows,
        this.currentIndex
      );
      this.visible = false;
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
    },
    // 清空数据
    handleClear() {
      this.value = "";
      this.selectedKeys = [];
      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])) {
          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">
.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%;
  .modal_left {
    width: 200px;
    border-right: 1px solid #eee;
  }
  .modal_right {
    width: calc(100% - 200px);
    height: 100%;
  }
}
// /deep/ .ant-tree-switcher {
//   border: 1px solid red;
//   &::before {
//     position: absolute;
//     top: 0;
//     left: 0;
//     width: 21px;
//     height: 21px;
//     border: 1px solid red;
//     content: "";
//     font-size: 16px;
//   }
// }
</style>
