<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('PATROL')}${$t('OBJECT_GROUP')}`"
      :visible="visible"
      :mask-closable="false"
      :destroy-on-close="true"
      @cancel="closeDialog"
    >
      <div v-show="isFirst" class="first-step">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="{ span: 10 }"
          :wrapper-col="{ span: 14 }"
        >
          <a-row :gutter="24">
            <!-- <a-col :span="8">
              <a-form-model-item
                :label="`${$t('PATROL')}${$t('OBJECT_GROUP')}${$t('NAME')}`"
                prop="name"
                allow-clear
              >
                <a-input v-model="form.name" :placeholder="$t('PLACEENTER')" />
              </a-form-model-item>
            </a-col> -->
            <a-col :span="8">
              <a-form-model-item
                :label="`${$t('PATROL')}${$t('RESPONSIBLE_USER')}`"
                prop="responsibleUser"
              >
                <template>
                  <div style="position: relative">
                    <select-user
                      ref="selectUser"
                      v-model="form.responsibleUser"
                      :multiple="false"
                      :default-selected-rows="selectedUser"
                      @confirm="getReturnData"
                    />
                  </div>
                </template>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                :label="`${$t('PATROL')}${$t('OBJECT_GROUP')}${$t(
                  'HISTORY_RECORD'
                )}`"
                prop="groupId"
              >
                <SelectSearch
                  ref="SelectSearch"
                  :show-multiple="false"
                  request-api="/api/epm/pc-object-group/search"
                  option-label="name"
                  query-list-key="name"
                  :default-selected-keys="form.historyData"
                  :search-params="searchParams"
                  @change="onSelectSearchChange"
                >
                </SelectSearch>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="line_bg_gray"></div>
        <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"
            :page.sync="page"
            :total="total"
            :mega-extend="{
              rowAction: false,
              rowIndex: false,
            }"
            @beforeSearch="beforeSearch"
            @search="search"
          >
          </MomTable>
          <div v-if="false" 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 v-if="false" class="modal_right">
            <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"
              :pagination="false"
              :mega-extend="{
                rowAction: false,
                rowIndex: false,
              }"
              @beforeSearch="beforeSearch"
              @search="search"
            >
              <template slot="responsibleUser" slot-scope="text, row, index">
                <div style="position: relative">
                  <select-user
                    :ref="`selectUser${index}`"
                    v-model="row.responsibleUser"
                    :multiple="false"
                    :default-selected-rows="row.selectedUser"
                    :parent-params="{ curIndex: index }"
                    @confirm="getReturnDataItem"
                  />
                </div>
              </template>
              <template slot="order" slot-scope="text, row, index">
                <div style="position: relative">
                  <a-input-number v-model="row.order" :min="1" />
                  <span class="btn_move" @click="handleMoveTop(index)">{{
                    $t("CONFIGM")
                  }}</span>
                </div>
              </template>
              <template slot="operate" slot-scope="text, row, index">
                <div style="position: relative">
                  <span v-if="index === 0" class="btn_move active">{{
                    $t("MOVE_UP")
                  }}</span>
                  <span
                    v-if="index > 0"
                    class="btn_move"
                    @click="handleMoveUp(index)"
                    >{{ $t("MOVE_UP") }}</span
                  >
                  <span
                    v-if="index + 1 === tableData.length"
                    class="btn_move active"
                    >{{ $t("MOVE_DOWN") }}</span
                  >
                  <span
                    v-if="index + 1 < tableData.length"
                    class="btn_move"
                    @click="handleMoveDown(index)"
                    >{{ $t("MOVE_DOWN") }}</span
                  >
                  <span
                    v-if="index > 0"
                    class="btn_move"
                    @click="handleMoveTop(index)"
                    >{{ $t("TOPPING") }}</span
                  >
                </div>
              </template>
            </MomTable>
          </div>
        </div>
      </div>
      <div v-show="!isFirst">
        <a-form-model
          ref="ruleFormHistory"
          :model="formHistory"
          :rules="rules"
          :label-col="{ span: 10 }"
          :wrapper-col="{ span: 14 }"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item
                :label="`${$t('PATROL')}${$t('OBJECT_GROUP')}${$t('NAME')}`"
                prop="name"
                allow-clear
              >
                <a-input
                  v-model="formHistory.name"
                  :placeholder="$t('PLACEENTER')"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="line_bg_gray"></div>
        <div class="modal_content">
          <MomTable
            ref="MomTableHistory"
            :row-key="rowKey"
            :columns="columnsHistory"
            :data-source="tableDataHistory"
            :show-util-operator="false"
            :pagination="false"
            :mega-extend="{
              rowAction: false,
              rowIndex: false,
            }"
          >
            <template slot="responsibleUser" slot-scope="text, row, index">
              <div style="position: relative">
                <select-user
                  :ref="`selectUser${index}`"
                  v-model="row.responsibleUser"
                  :multiple="false"
                  :default-selected-rows="row.selectedUser"
                  :parent-params="{ curIndex: index }"
                  @confirm="getReturnDataItem"
                />
              </div>
            </template>
            <template slot="order" slot-scope="text, row, index">
              <div style="position: relative">
                <a-input-number
                  v-model="row.order"
                  :min="1"
                  @change="handleChangeOrder(row)"
                />
                <span class="btn_move" @click="handleMoveOrder(index, row)">{{
                  $t("CONFIRM")
                }}</span>
              </div>
            </template>
            <template slot="operate" slot-scope="text, row, index">
              <div style="position: relative">
                <span v-if="index === 0" class="btn_move active">{{
                  $t("MOVE_UP")
                }}</span>
                <span
                  v-if="index > 0"
                  class="btn_move"
                  @click="handleMoveUp(index)"
                  >{{ $t("MOVE_UP") }}</span
                >
                <span
                  v-if="index + 1 === tableDataHistory.length"
                  class="btn_move active"
                  >{{ $t("MOVE_DOWN") }}</span
                >
                <span
                  v-if="index + 1 < tableDataHistory.length"
                  class="btn_move"
                  @click="handleMoveDown(index)"
                  >{{ $t("MOVE_DOWN") }}</span
                >
                <span
                  v-if="index > 0"
                  class="btn_move"
                  @click="handleMoveTop(index)"
                  >{{ $t("TOPPING") }}</span
                >
              </div>
            </template>
          </MomTable>
        </div>
      </div>
      <template slot="footer">
        <a-button v-if="!isFirst" type="primary" @click="preStep">
          {{ $t("PREV_STEP") }}
        </a-button>
        <a-button v-else type="primary" @click="nextStep">
          {{ $t("NEXT_STEP") }}
        </a-button>
        <a-button v-if="!isFirst" 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";

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

export default {
  components: {
    MegaModal,
    SelectSearch,
    SelectUser,
  },
  props: {
    // 需要展示的key
    showKey: {
      type: String,
      default: "name",
    },
    // 回传的key
    rowKey: {
      type: String,
      default: "id",
    },
    // 当前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: [],
      tableDataHistory: [],
      unitList: [],
      selectedKeys: [],
      selectedHisKeys: [],
      selectedPageRows: {},
      value: undefined,
      page: 1,
      total: 0,
      treeData: [],
      dataSource: [], // 表格数据
      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: {
        // historyData: "",
        fabId: [],
        areaId: [],
        lineId: [],
      },
      form: {
        // name: "",
        responsibleUser: "",
      },
      formHistory: {
        name: "",
      },
      curIndex: 0,
      selectedUser: [],
      isFirst: true,
      fabIdList: [],
      areaIdList: [],
      searchParams: {
        pcObjectSourceId: "",
      },
      defaultSelectedRowsSec: [],
    };
  },
  computed: {
    rules() {
      return {
        name: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        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.queryParam.fabId && this.queryParam.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.queryParam.areaId && this.queryParam.areaId.length > 0) {
                this.getLine();
              }
            },
          },
        },
      });
    },
    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.defaultSelectedRowsSec.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,
          },
        }),
      };
    },
    rowSelectionHistory() {
      return {
        selectedRowKeys: this.selectedHisKeys,
        type: this.multiple ? "checkbox" : "radio",
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedHisKeys = selectedRowKeys;
        },
      };
    },
    columns() {
      return [...this.defaultList];
    },
    columnsHistory() {
      return [...this.defaultList, ...this.columnsList];
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    // 获取返回数据，点检分类
    onSelectSearchChange(e, item) {
      this.form.historyData = e;
      this.formHistory.name = item.name;
    },
    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.queryParamItem.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.queryParamItem.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.queryParamItem.lineId.options = res.data.data || [];
        });
    },
    // 获取区域
    getArea() {
      const params = {
        fabIdList: this.queryParam.fabId.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-area/list`, { params })
        .then((res) => {
          this.queryParamItem.areaId.options = res.data.data || [];
        });
    },
    // 获取产线
    getLine() {
      const params = {
        areaIdList: this.queryParam.areaId.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-line/list-by-area-code`, {
          params,
        })
        .then((res) => {
          this.queryParamItem.lineId.options = res.data.data || [];
        });
    },
    // 打开弹框事件
    openDialog() {
      this.visible = true;
      this.tableData = [];
      this.tableDataHistory = [];
      if (this.defaultSelectedRows.length > 0) {
        this.isFirst = false;
        this.formHistory.name = this.defaultSelectedRows[0].name;
        this.form.historyData = this.defaultSelectedRows[0].id;
        setTimeout(() => {
          this.getHistoryData();
        }, 500);
      } else {
        this.isFirst = true;
        this.$refs.MomTable?.query();
      }
    },
    // 获取数据字典
    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.searchParams.pcObjectSourceId = this.pcObjectSourceId;
            }
          });
          this.date = new Date().getTime();
        }
      });
    },
    // 点击节点查询数据
    handleNodeClick(node, event) {
      if (node.length > 0) {
        // eslint-disable-next-line prefer-destructuring
        this.pcObjectSourceId = node[0];
        this.searchParams.pcObjectSourceId = this.pcObjectSourceId;
        this.tableData = [];
        const curData = this.treeData.find((item) => item.id === node[0]);
        if (curData.sourceName === "设备") {
          this.queryParam = {
            historyData: "",
            lineId: [],
            fabId: [],
            areaId: [],
          };
        } else {
          this.queryParam = {
            historyData: "",
          };
        }
        // this.$refs.MomTable?.query();
      }
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      this.form.responsibleUser = selectedRows[0]?.userName;
      this.selectedUser = selectedRows;
      if (this.tableData.length > 0) {
        this.tableData.forEach((item) => {
          // eslint-disable-next-line no-param-reassign
          item.responsibleUser = selectedRows[0]?.userName;
          // eslint-disable-next-line no-param-reassign
          item.selectedUser = [{ userName: selectedRows[0]?.userName }];
        });
      }
    },
    getReturnDataItem(selectedKeys, selectedRows, parentParams) {
      const { curIndex } = parentParams;
      this.tableDataHistory[curIndex].responsibleUser =
        selectedRows[0]?.userName;
      this.tableDataHistory[curIndex].selectedUser = selectedRows;
    },
    // 上移
    handleMoveUp(index) {
      const curItem = this.tableDataHistory[index - 1];
      this.tableDataHistory.splice(index - 1, 1);
      this.tableDataHistory.splice(index, 0, curItem);
      this.tableDataOrder();
    },
    // 下移
    handleMoveDown(index) {
      const curItem = this.tableDataHistory[index + 1];
      this.tableDataHistory.splice(index + 1, 1);
      this.tableDataHistory.splice(index, 0, curItem);
      this.tableDataOrder();
    },
    // 置顶
    handleMoveTop(index) {
      const curItem = this.tableDataHistory[index];
      this.tableDataHistory.splice(index, 1);
      this.tableDataHistory.splice(0, 0, curItem);
      this.tableDataOrder();
    },
    handleChangeOrder(row) {
      this.$forceUpdate();
    },
    handleMoveOrder(index, { order }) {
      const curItem = this.tableDataHistory[index];
      this.tableDataHistory.splice(index, 1);
      this.tableDataHistory.splice(order - 1, 0, curItem);
      this.tableDataOrder();
    },
    /**
     * 获取table的数据
     */
    search(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);
              }
            });
          }
          const arr = [
            {
              dataIndex: "responsibleUser", // 巡检执行人
              title: () => this.$t("PATROL") + this.$t("RESPONSIBLE_USER"),
              sorter: false,
              minWidth: 200,
              scopedSlots: { customRender: "responsibleUser" },
            },
            {
              dataIndex: "order", // 设备顺序
              title: () => this.$t("EQP") + this.$t("ORDER"),
              sorter: false,
              width: 160,
              scopedSlots: { customRender: "order" },
            },
            {
              dataIndex: "operate", // 调整巡检顺序
              title: () =>
                this.$t("ADJUST") + this.$t("PATROL") + this.$t("ORDER"),
              sorter: false,
              width: 150,
              scopedSlots: { customRender: "operate" },
            },
          ];
          arr.forEach((item) => {
            this.columnsList.push(item);
          });
          this.$forceUpdate();
        });
      const { fabId, areaId, lineId } = this.queryParam;
      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,
        },
      ];
      const searchParams = {
        // page: 1,
        // size: 100000,
        ...params,
        enableFlag: "Y",
        extParamList,
        pcObjectSourceId: this.pcObjectSourceId,
      };
      // if (this.isFirst) {
      //   this.isFirst = false;
      //   return;
      // }
      // this.tableData = [];
      this.selectedKeys = [];
      // this.searchPageData(searchParams);
      if (this.form.historyData) {
        this.getHistoryData(searchParams);
      } else {
        this.searchPageData(searchParams);
      }
    },
    getHistoryData(searchParams) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pc-object-group/dynamic/${this.form.historyData}`
        )
        .then((res) => {
          const { records } = { ...res?.data?.data };
          if (records && records.length > 0) {
            this.tableDataHistory = records.map((item) => {
              // eslint-disable-next-line no-param-reassign
              item.selectedUser = [{ userName: item.responsibleUser }];
              return item;
            });
            this.defaultSelectedRowsSec = this.tableDataHistory;
            records.forEach((item) => {
              this.selectedHisKeys.push(item.id);
              this.selectedKeys.push(item.id);
            });
          }
          this.searchPageData(searchParams);
        });
    },
    searchPageData(searchParams) {
      if (!searchParams) return;
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/object-source/dynamic-search`,
          searchParams
        )
        .then((res) => {
          if (res.data.data.records.length > 0) {
            const arr = res.data.data.records.map((item) => {
              // eslint-disable-next-line no-param-reassign
              item.selectedUser = [{ userName: this.form.responsibleUser }];
              // eslint-disable-next-line no-param-reassign
              item.responsibleUser = this.form.responsibleUser;
              return item;
            });
            const arrKeys = res.data.data.records.map((item) => {
              return item.id;
            });
            this.tableData = [...this.tableData, ...arr];
            this.tableData = uniqBy(this.tableData, "code"); // 去重
            this.total = res.data.data.total;
          }
          // this.tableDataOrder();
        });
      this.setSelectedPageRows();
    },
    tableDataOrder() {
      if (this.tableDataHistory.length > 0) {
        // eslint-disable-next-line array-callback-return
        this.tableDataHistory.map((item, index) => {
          // eslint-disable-next-line no-param-reassign
          item.order = index + 1;
        });
      }
    },
    preStep() {
      this.isFirst = true;
      this.selectedKeys = this.tableDataHistory.map(
        (item) => item[this.rowKey]
      );
      this.$refs.MomTable?.search();
    },
    nextStep() {
      this.isFirst = false;
      this.tableDataHistory = [...this.selectedRows];
    },
    // 监听确认按钮事件
    handleConfirm() {
      if (this.tableDataHistory.length === 0) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      this.$refs.ruleFormHistory.validate((valid) => {
        if (valid) {
          const pcObjectGroupItemList = [];
          this.tableDataHistory.forEach((item) => {
            pcObjectGroupItemList.push({
              pcObjectId: item.id,
              pcObjectCode: item.code,
              pcObjectName: item.name,
              responsibleUser: item.responsibleUser,
            });
          });
          const params = {
            name: this.formHistory.name,
            pcObjectGroupItemList,
            tableName: "epm_eqp",
            pcObjectSourceId: this.pcObjectSourceId,
          };
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/epm/pc-object-group`, params)
            .then((res) => {
              this.$emit(
                "confirm",
                this.selectedHisKeys,
                this.tableDataHistory,
                this.pcObjectSourceId,
                this.currentIndex,
                res.data?.data,
                this.formHistory.name
              );
              this.visible = false;
            });
        }
      });
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
    },
    // 清空数据
    handleClear() {
      this.value = "";
      this.selectedKeys = [];
      this.selectedHisKeys = [];
      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">
.btn_move {
  color: @primary-color;
  margin: 0 5px;
  cursor: pointer;
}
.btn_move.active {
  color: #999;
}
.mega-design-business-table {
  margin: 10px;
}
.closeIcon {
  position: absolute;
  right: 10px;
  top: 14px;
  font-size: 12px;
  cursor: pointer;
}
.line_bg_gray {
  width: 100%;
  height: 8px;
  background-color: #eef1f4;
}
.modal_content {
  width: 100%;
  height: 100%;
  .modal_left {
    width: 200px;
    border-right: 1px solid #eee;
  }
  .modal_right {
    width: calc(100% - 200px);
    height: 100%;
  }
}
</style>
