<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :mega-extend="{
        rowIndex: false,
      }"
      @beforeSearch="beforeSearch"
      @search="search"
      @reset="handleReset"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button v-show="false">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:MOLD_SCRAP:SCRAP_RECORD:PREVIEW')"
          style="margin-left: 0 !important"
          :disabled="selectedRows.length !== 1"
          @click="handlePreview(selectedRows[0])"
        >
          <Icon type="eye" />
          {{ $t("PREVIEW") }}
        </a-button>
      </div>
      <template slot="code" slot-scope="text, record">
        <span class="eqpTypeSty" @click="handleItem(record)">{{
          record.code
        }}</span>
      </template>
      <template slot="checkStatus" slot-scope="text, record">
        <span class="status-box" :class="text">{{
          record.checkStatusName
        }}</span>
      </template>
    </MomTable>
    <MegaDrawer
      width="520"
      :is-show-footer="false"
      :title="$t('APPROVAL_DETAILS')"
      :visible="drawerVisible"
      :is-show-ok-btn="false"
      @close="handleCancel"
    >
      <div slot="main">
        <ExamineProgress :process-list="processList"></ExamineProgress>
      </div>
      <template slot="footer">
        <div></div>
      </template>
    </MegaDrawer>
  </div>
</template>

<script>
import moment from "moment";
import { uniqBy } from "lodash";
import { Icon } from "ant-design-vue";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";
import ExamineProgress from "@/components/epms/ExamineProgress";

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

export default {
  components: {
    Icon,
    ExamineProgress,
    MegaDrawer,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      modalVisible: false,
      isEdit: false,
      isView: false,
      editId: null,
      enableFlag: {
        prop: "enableFlag",
        defaultValue: "Y",
        enableValue: "Y",
        options: [
          { label: "全部", value: "" },
          { label: "启用", value: "Y" },
          { label: "禁用", value: "N" },
        ],
        optionsProps: {
          label: "label",
          value: "value",
        },
      },
      loading: false, // 表格loading
      confirmLoading: false,
      options: {
        allowDuplicateUploads: true,
        target: "/core/api/mom-file/update-one",
        testChunks: true,
        single: true,
        chunkSize: 10 * 1024 * 1024,
      },
      // 查询的表单的配置项
      queryParam: {
        name: "", // 申请单标题
        applyUserIdList: "", // 申请人
        dateArr: [],
      },
      columns: [
        {
          dataIndex: "code", // 编码
          title: () => this.$t("CODE"),
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "code" },
        },
        {
          dataIndex: "name", // 名称
          title: () => this.$t("APPLICATION_FORM_TITLE"),
          ellipsis: true,
          sorter: false,
          width: 260,
        },
        {
          dataIndex: "toLocation", // 报废仓
          title: () => this.$t("SCRAP_WAREHOUSE"),
          ellipsis: true,
          sorter: false,
          width: 260,
        },
        {
          dataIndex: "detailPreView", // 模具清单
          title: () => this.$t("MOLD_LIST"),
          ellipsis: true,
          sorter: false,
          width: 260,
        },
        {
          dataIndex: "checkStatus",
          align: "center",
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "checkStatus" },
          width: 130,
        },
        {
          dataIndex: "applyUserName", // 申请人员
          ellipsis: true,
          title: () => this.$t("APPLY_USER"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "applyTime", // 申请时间
          ellipsis: true,
          title: () => this.$t("APPLICATION_TIME"),
          width: 200,
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        (h, { record, index }) =>
          this.hasAuth("EPMS:MOLD_SCRAP:SCRAP_RECORD:PREVIEW") && (
            <Icon
              class={"btn_operate"}
              type="eye"
              title={this.$t("VIEW")}
              onClick={() => this.handlePreview(record)}
            />
          ),
      ],
      dataSource: [],
      stateList: [],
      typeList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      drawerVisible: false,
      processList: [], // 流程列表
      tableNameList: [
        {
          key: "epm_mold_scrap",
          tab: "模具报废",
        },
      ],
      dataAttr: {
        tableColumns: "columns",
        queryFormItem: "queryParamItem",
        queryForm: "queryParam",
      },
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        name: {
          label: () => `${this.$t("APPLICATION_FORM_TITLE")}`,
        },
        applyUserIdList: {
          label: () => this.$t("APPLICANT"), // 负责人
          itemType: "custom",
          customRender: () => {
            return (
              <SelectSearch
                isReset={this.isReset}
                show-multiple={true}
                option-label={"name"}
                option-value={"id"}
                requestApi={"/api/mdm/user/search-with-site"}
                onChange={this.onSelectSearchChange}
              />
            );
          },
        },
        dateArr: {
          itemType: "range",
          label: () => this.$t("DATE"),
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRows = [];
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
          } else {
            this.selectedRows = selectedRows;
          }
        },
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    // 选人组件返回数据
    onSelectSearchChange(e, info) {
      this.isReset = false;
      this.queryParam.applyUserIdList = info.join(",");
    },
    // 重置搜索监听事件
    handleReset() {
      this.isReset = true;
      this.$refs.MomTable?.search();
    },
    // 初始化数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:MOLD_MANAGE_TYPE`
        ), // 管控方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 禁用启用
      ]).then(([typeRes, enableStatus]) => {
        this.typeList = typeRes.data.data;
        this.stateList = enableStatus.data.data;
      });
    },
    beforeSearch() {
      return this.queryFieldExtend().then((res) => {
        if (res.data.data.fieldHiddenConfigList?.length) {
          const obj = {};
          res.data.data.fieldHiddenConfigList.forEach((item) => {
            obj[item.fieldName] = true;
          });
          // 处理查询条件的字段的隐藏和显示
          Object.keys(this.queryParamItem).forEach((item) => {
            this.hasFunction(obj, item);
          });
          // 处理表格的字段的隐藏和显示
          const arr = JSON.parse(JSON.stringify(this.columns));
          arr.forEach((item) => {
            this.tableColumnsFunction(obj, item.dataIndex);
          });
        }
      });
    },
    tableColumnsFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        if (obj[val]) {
          this.columns.forEach((item, index) => {
            if (item.dataIndex === val) {
              this.columns.splice(index, 1);
            }
          });
        }
      }
    },
    hasFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        if (obj[val]) {
          delete this.queryParamItem[val];
          delete this.queryParam[val];
        }
      }
    },
    // 监听搜索事件
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.dataSource = [];
      this.loading = true;
      const { dateArr } = this.queryParam;
      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,
        passFlag: "Y",
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold-scrap/search`, {
          params: searchParams,
        })
        .then((res) => {
          const { records, total } = { ...res?.data?.data };
          this.dataSource = records;
          this.total = total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleItem({ id }) {
      const params = {
        sourceTicketId: id,
        checkProcessType: "MOLD_SCRAP_CHECK", // 签核类型，模具报废
      };
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/epm-check-process-log/apply-process`,
          {
            params,
          }
        )
        .then((res) => {
          const list = res?.data?.data || [];
          this.processList = [...list];
        });
      this.drawerVisible = true;
    },
    handlePreview({ id }) {
      this.$router.push({
        path: "/eam/mold_management/scrap_record/preview",
        query: {
          id,
        },
      });
    },
    handleCancel() {
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="less">
@import "@/assets/css/status_epms.less";
.eqpTypeSty {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
.wrapClass .ant-modal {
  top: 0;
  padding-bottom: 0;
  .ant-modal-content {
    min-height: 100vh;
    border-left: 8px solid #f0f2f5;
    border-right: 8px solid #f0f2f5;
    .ant-modal-header {
      background: #fff;
      margin: 0 -8px;
      border-radius: 0;
    }
    .ant-modal-body {
      padding: 0;
      border-top: 8px solid #f0f2f5;
      .page-bottom-op {
        width: 100%;
      }
    }
  }
}
.status-box {
  &.ALREADY_REPAIR {
    .status-box-color(@success-color);
  }
  &.WAIT_CHECK {
    .status-box-color(rgba(255, 101, 0, 1));
  }
  &.WAIT_COMMIT {
    .status-box-color(rgba(28, 166, 254, 1));
  }
}
.btn_operate {
  color: @primary-color;
}
</style>
