<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 flex">
        <div class="modal_left">
          <a-tree
            :key="date"
            style="padding-right: 10px"
            :block-node="true"
            :default-expand-all="true"
            :default-selected-keys="defaultSelectedList"
            :show-icon="true"
            show-line
            :tree-data="treeData"
            :replace-fields="{
              children: 'children',
              key: 'id',
              value: 'id',
              title: 'sourceName',
            }"
            @select="handleNodeClick"
          >
            <template slot="switcherIcon">
              <i class="iconfont icon-kaoshi"></i>
            </template>
          </a-tree>
        </div>
        <div class="modal_right">
          <MomTable
            ref="MomTable"
            :row-key="rowKey"
            :query-param="sourceName === '设备' ? queryParam2 : queryParam"
            :query-param-item="
              sourceName === '设备' ? queryParamItem2 : queryParamItem
            "
            :columns="columns"
            :data-source="tableData"
            :row-selection="rowSelection"
            :show-util-operator="false"
            :mega-extend="{
              rowAction: false,
            }"
            :total="total"
            :page.sync="page"
            @beforeSearch="beforeSearch"
            @reset="handleReset"
            @search="search"
          >
          </MomTable>
        </div>
      </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 [];
      },
    },
    pcObjectSourceIdItem: {
      type: String,
      default: "",
    },
    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,
      treeData: [],
      dataSource: [], // 表格数据
      sourceName: "",
      defaultList: [
        {
          dataIndex: "code", // 系称
          title: () => this.$t("CODE"),
          minWidth: 200,
        },
        {
          dataIndex: "name", // 名称
          title: () => this.$t("NAME"),
          minWidth: 200,
        },
      ],
      columnsList: [],
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      pcObjectSourceId: "",
      defaultSelectedList: [],
      // 查询的表单的配置项
      queryParam: {
        name: "",
      },
      queryParam2: {
        name: "",
        fabId: [],
        areaId: [],
        lineId: [],
        eqpTypeId: [],
      },
      fabIdList: [],
      areaIdList: [],
      isReset: false,
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        name: {
          label: () => `${this.$t("NAME")}`,
        },
      });
    },
    queryParamItem2() {
      return this.$observable("queryParamItem2", {
        name: {
          label: () => `${this.$t("NAME")}`,
        },
        lineId: {
          itemType: "select",
          label: () => this.$t("PRODUCTION_LINE"),
          mode: "multiple",
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "lineName",
            value: "id",
          },
        },
        fabId: {
          itemType: "select",
          label: () => this.$t("FAC_SHOP"),
          mode: "multiple",
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "fabName",
            value: "id",
          },
          on: {
            change: () => {
              if (this.queryParam2.fabId && this.queryParam2.fabId.length > 0) {
                this.getArea();
              }
            },
          },
        },
        areaId: {
          itemType: "select",
          label: () => this.$t("FAC_AREA"),
          mode: "multiple",
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "areaName",
            value: "id",
          },
          on: {
            change: () => {
              if (
                this.queryParam2.areaId &&
                this.queryParam2.areaId.length > 0
              ) {
                this.getLine();
              }
            },
          },
        },
        eqpTypeId: {
          itemType: "custom",
          label: () => this.$t("EQP_TYPE"),
          customRender: () => {
            return (
              <SelectSearch
                ref="SelectSearch"
                queryListKey="eqpTypeName"
                requestApi="/api/epm/eam/eqp-type/search"
                option-label="eqpTypeName"
                needDisabled={false}
                isReset={this.isReset}
                onChange={this.onSelectSearchChange}
              ></SelectSearch>
            );
          },
        },
      });
    },
    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,
    },
  },
  mounted() {
    this.init();
  },
  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() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/object-source/list-all`
        ),
      ]).then(([objectSourceRes]) => {
        this.treeData = objectSourceRes?.data?.data || [];
        if (
          objectSourceRes?.data?.data &&
          objectSourceRes?.data?.data.length > 0
        ) {
          objectSourceRes?.data?.data.forEach((item, index) => {
            if (item.sourceName === "设备") {
              this.pcObjectSourceId = this.pcObjectSourceIdItem || item.id;
              this.defaultSelectedList[0] = JSON.parse(
                JSON.stringify(this.pcObjectSourceId)
              );
              this.sourceName = "设备";
            }
          });
          this.date = new Date().getTime();
        }
      });
    },
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/mdm/fac-fab/list-by-factory-code`
        ),
      ]).then(([facRes]) => {
        const { data } = facRes.data;
        this.queryParamItem2.fabId.options = facRes.data.data || [];
        if (data && data.length > 0) {
          data.forEach((item) => {
            this.fabIdList.push(item.id);
          });
          this.getAreaByFab();
        }
      });
    },
    // 获取区域
    getAreaByFab() {
      const params = {
        fabIdList: this.fabIdList.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-area/list`, { params })
        .then((res) => {
          const { data } = res.data;
          if (data && data.length > 0) {
            this.queryParamItem2.areaId.options = res.data.data || [];
            data.forEach((item) => {
              this.areaIdList.push(item.id);
            });
            this.getLineByArea();
          }
        });
    },
    // 获取产线
    getLineByArea() {
      const params = {
        areaIdList: this.areaIdList.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-line/list-by-area-code`, {
          params,
        })
        .then((res) => {
          this.queryParamItem2.lineId.options = res.data.data || [];
        });
    },
    // 获取区域
    getArea() {
      const params = {
        fabIdList: this.queryParam2.fabId.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-area/list`, { params })
        .then((res) => {
          this.queryParamItem2.areaId.options = res.data.data || [];
        });
    },
    // 获取产线
    getLine() {
      const params = {
        areaIdList: this.queryParam2.areaId.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-line/list-by-area-code`, {
          params,
        })
        .then((res) => {
          this.queryParamItem2.lineId.options = res.data.data || [];
        });
    },
    onSelectSearchChange(e, list) {
      this.isReset = false;
      this.queryParam2.eqpTypeId = list;
    },
    // 点击节点查询数据
    handleNodeClick(node, info) {
      if (node.length > 0) {
        // eslint-disable-next-line prefer-destructuring
        this.pcObjectSourceId = node[0];
        const selectData = this.treeData.find((item) => item.id === node[0]);
        this.sourceName = selectData.sourceName;
        this.$refs.MomTable?.query();
      }
    },
    /**
     * 获取table的数据
     */
    search(params) {
      if (this.sourceName === "设备") {
        const { fabId, areaId, lineId, eqpTypeId } = this.queryParam2;
        const extParamList = [
          {
            tableName: "epm_eqp",
            fieldName: "LOCATION_FIRST_ID", // 车间
            searchType: "IN",
            searchValueList: fabId,
          },
          {
            tableName: "epm_eqp",
            fieldName: "LOCATION_SECOND_ID", // 区域
            searchType: "IN",
            searchValueList: areaId,
          },
          {
            tableName: "epm_eqp",
            fieldName: "LOCATION_THIRD_ID", // 产线
            searchType: "IN",
            searchValueList: lineId,
          },
          {
            tableName: "epm_eqp",
            fieldName: "EQP_TYPE_ID", // 产线
            searchType: "IN",
            searchValueList: eqpTypeId,
          },
        ];
        const searchParams = {
          // page: 1,
          // size: 100000,
          ...params,
          enableFlag: "Y",
          extParamList,
          pcObjectSourceId: this.pcObjectSourceId,
        };
        this.searchPageData(searchParams, params);
      } else {
        this.nomalSearch(params);
      }
    },
    nomalSearch(params) {
      this.columnsList = [];
      this.tableData = [];
      if (!this.pcObjectSourceId) return;
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/object-source/list-column`,
          {
            params: {
              ...params,
              enableFlag: "Y",
              pcObjectSourceId: this.pcObjectSourceId,
            },
          }
        )
        .then(({ data }) => {
          if (data?.data && data.data.length > 0) {
            data.data.forEach((item) => {
              const columnsItem = { ...this.columnsItem };
              columnsItem.dataIndex = item.columnName;
              columnsItem.title = () => this.$t(`${item.i18NCode}`);
              if (["code"].includes(item.columnName)) {
                this.defaultList[0].title = () => this.$t(`${item.i18NCode}`);
              }
              if (["name"].includes(item.columnName)) {
                this.defaultList[1].title = () => this.$t(`${item.i18NCode}`);
              }
              if (!["code", "name"].includes(item.columnName)) {
                this.columnsList.push(columnsItem);
              }
            });
          }
          this.$forceUpdate();
        });
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/object-source/dynamic-search`,
          {
            params: {
              ...params,
              enableFlag: "Y",
              pcObjectSourceId: this.pcObjectSourceId,
            },
          }
        )
        .then((res) => {
          if (res.data.data.records.length > 0) {
            this.tableData = res.data.data.records;
          }
          // end
          this.total = res.data.data.total;
          this.setSelectedPageRows();
        });
    },
    searchPageData(searchParams, params) {
      if (!searchParams) return;
      this.columnsList = [];
      this.tableData = [];
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/object-source/list-column`,
          {
            params: {
              ...params,
              enableFlag: "Y",
              pcObjectSourceId: this.pcObjectSourceId,
            },
          }
        )
        .then(({ data }) => {
          if (data?.data && data.data.length > 0) {
            data.data.forEach((item) => {
              const columnsItem = { ...this.columnsItem };
              columnsItem.dataIndex = item.columnName;
              columnsItem.title = () => this.$t(`${item.i18NCode}`);
              if (["code"].includes(item.columnName)) {
                this.defaultList[0].title = () => this.$t(`${item.i18NCode}`);
              }
              if (["name"].includes(item.columnName)) {
                this.defaultList[1].title = () => this.$t(`${item.i18NCode}`);
              }
              if (!["code", "name"].includes(item.columnName)) {
                this.columnsList.push(columnsItem);
              }
            });
          }
          this.$forceUpdate();
        });
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/object-source/dynamic-search`,
          searchParams
        )
        .then((res) => {
          if (res.data.data.records.length > 0) {
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
          }
          this.setSelectedPageRows();
          // this.tableDataOrder();
        });
    },
    // 监听确认按钮事件
    handleConfirm() {
      // input显示的值
      this.value = this.selectedRows.map((item) => item[this.showKey]).join();
      // 回传 keys rows
      this.$emit(
        "confirm",
        this.selectedKeys,
        this.selectedRows,
        this.pcObjectSourceId,
        this.currentIndex
      );
      this.visible = false;
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
    },
    handleReset() {
      this.isReset = true;
      this.$refs.MomTable.search();
    },
    // 清空数据
    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>
