<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>
    <!-- 国际化选择新增弹框 -->
    <MegaModal
      width="1280px"
      :title="`${$t('PLACESELECT')}${$t('EQUIPMENT_LIST')}`"
      :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="['']"
            :show-icon="true"
            show-line
            :tree-data="treeData"
            :replace-fields="{
              children: 'children',
              key: 'key',
              value: 'id',
              title: 'title',
            }"
            @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="queryForm"
            :query-param-item="queryFormItem"
            :columns="tableColumns"
            :data-source="tableData"
            :row-selection="rowSelection"
            :show-util-operator="false"
            :mega-extend="{
              rowAction: false,
            }"
            :total="total"
            :page.sync="page"
            @beforeSearch="beforeSearch"
            @search="searchPageData"
            @reset="handleReset"
          >
            <template slot="imgUrl" slot-scope="text, record">
              <img
                class="eqp_picture"
                :src="record.imgUrl || defaultImg"
                alt=""
              />
            </template>
            <template slot="enableFlag" slot-scope="text">
              <span class="status-box" :class="'able' + text">{{
                getAttrValue(stateList, text)
              }}</span>
            </template>
          </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 moment from "moment";
import { Modal as MegaModal } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";
import { fetchFileUrl } from "@/utils/file";

export default {
  components: {
    MegaModal,
  },
  mixins: [FieldExtendMixin],
  props: {
    // 需要展示的key
    showKey: {
      type: String,
      default: "id",
    },
    // 回传的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 [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      date: new Date().getTime(),
      // eslint-disable-next-line global-require
      defaultImg: require("@/assets/img/eqp_01.png"),
      visible: false, // 弹框显示、隐藏
      tableData: [],
      unitList: [],
      // 查询的表单的配置项
      queryForm: {
        eqpCode: "",
        eqpId: [],
        dateArr: [],
      },
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
      total: 0,
      page: 1,
      eqpPage: 1,
      eqpTypePage: 1,
      initHeight: 0,
      stateList: [],
      searchEqpList: [],
      searchEqpTypeList: [],
      treeData: [
        {
          title: "所有设备",
          key: "",
          id: "1-1",
        },
        {
          title: "按保养次数选设备",
          key: "orderByPm",
          id: "1-1-1",
        },
        {
          title: "按维修次数选设备",
          key: "orderByRepair",
          id: "1-1-2",
        },
      ],
      searchType: "",
      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,
          },
        }),
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        eqpCode: {
          label: () => this.$t("EPMS_EQP_CODE"), // 设备编码
        },
        dateArr: {
          itemType: "range",
          label: () => this.$t("DATE"),
        },
        eqpId: {
          itemType: "custom",
          label: () => this.$t("EQUIPMENT_NAME"),
          customRender: () => {
            return (
              <SelectSearch
                ref={"SelectSearch"}
                queryListKey="eqpName"
                requestApi={"/api/epm/eam/eqp/search"}
                option-label={"eqpName"}
                needDisabled={false}
                isReset={this.isReset}
                onChange={this.onSelectSearchChange}
              ></SelectSearch>
            );
          },
        },
      });
    },
    // 表格的配置项
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "imgUrl",
          width: 100,
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "imgUrl" },
          title: () => this.$t("CORE_PICTURE"), // 图片
        },
        {
          dataIndex: "eqpCode",
          width: 180,
          ellipsis: true,
          scopedSlots: { customRender: "eqpCode" },
          title: () => this.$t("EPMS_EQP_CODE"), // 设备编码
        },
        {
          dataIndex: "eqpName",
          width: 180,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EQUIPMENT_NAME"), // 设备名称
        },
        {
          dataIndex: "operateCount",
          width: 100,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("TIMES"), // 次数
        },
        {
          dataIndex: "eqpTypeName",
          width: 180,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EQP_TYPE"), // 设备类型
        },
        {
          dataIndex: "location",
          width: 360,
          ellipsis: true,
          title: () => this.$t("POSITION"), // 位置
        },
      ]);
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    onSelectSearchChange(e, info) {
      this.isReset = false;
      this.queryForm.eqpId = info.join(",");
    },
    // 打开弹框事件
    openDialog() {
      this.visible = true;
      const selectedKey = this.defaultSelectedRows
        .map((item) => item[this.rowKey])
        .concat(this.defaultSelectedKeys);
      this.selectedKeys = uniqBy([].concat(selectedKey));
      this.searchPageData();
      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 || [];
      });
    },
    // 点击节点查询数据
    handleNodeClick(node) {
      if (node.length > 0) {
        // eslint-disable-next-line prefer-destructuring
        this.searchType = node[0];
        this.$refs.MomTable?.query();
      }
    },
    // 重置搜索
    handleReset() {
      this.queryForm.eqpId = [];
      this.isReset = true;
      this.$refs.MomTable?.search();
    },
    /**
     * 获取table的数据
     */
    searchPageData(params) {
      const { dateArr, eqpId } = this.queryForm;
      const startDate = dateArr?.length
        ? moment(dateArr[0]).format("YYYY-MM-DD")
        : "";
      const endDate = dateArr?.length
        ? moment(dateArr[1]).format("YYYY-MM-DD")
        : "";
      const searchParams = {
        ...params,
        startDate,
        endDate,
        eqpIdList: eqpId || "", // && eqpId.length > 0 ? eqpId.join(",") : "",
        enableFlag: "Y",
        searchType: this.searchType,
      };
      delete searchParams.eqpId;
      delete searchParams.dateArr;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp/search`, {
          params: searchParams,
        })
        .then((res) => {
          // 数据需要禁用时使用
          // 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);
            }
          });
          // end
          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 = this.fieldExResDataFn(records);
          this.total = 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">
@import "@/assets/css/status_epms.less";
.closeIcon {
  position: absolute;
  right: 10px;
  top: 14px;
  font-size: 12px;
  cursor: pointer;
}
.modal_content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  .modal_left {
    width: 170px;
    border-right: 1px solid #eee;
  }
  .modal_right {
    width: calc(100% - 180px);
    height: 100%;
  }
}
.sitemore {
  width: 260px !important;
}
.eqp_picture {
  width: 50px;
  height: 50px;
}
</style>
