<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,
      }"
      :auto-adaptive-width="false"
      @beforeSearch="beforeSearch"
      @search="search"
      @edit="handleEdit"
      @copy="handleCopy"
      @delete="handleDelete"
      @reset="handleReset"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('EPMS:EQP_BORROW:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomEditButton
          v-if="hasAuth('EPMS:EQP_BORROW:ADD')"
          type="copy"
          text="COPY"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:EQP_BORROW:EDIT')"
          :disabled="
            selectedRowKeys.length !== 1 ||
            !(
              selectedStatus.length === 1 && selectedStatus[0] === 'WAIT_COMMIT'
            )
          "
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <a-button
          v-if="hasAuth('EPMS:EQP_BORROW:ADD')"
          :disabled="
            selectedRowKeys.length === 0 ||
            !(
              selectedStatus.length === 1 && selectedStatus[0] === 'WAIT_COMMIT'
            )
          "
          @click="handleAudit"
        >
          <i class="iconfont icon-fabu1" />{{ $t("COMMIT_AUDIT") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:EQP_BORROW:DELETE')"
          :disabled="
            selectedRowKeys.length === 0 ||
            !(
              selectedStatus.length === 1 && selectedStatus[0] === 'WAIT_COMMIT'
            )
          "
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="name" slot-scope="text, record">
        <span class="name_link" @click="handleView(record)">
          {{ record.name }}
        </span>
      </div>
      <template slot="code" slot-scope="text, record">
        <span class="name_link" @click="handleItem(record)">{{
          record.code
        }}</span>
      </template>
      <template slot="checkStatusName" slot-scope="text, record">
        <span
          class="status-box"
          :class="{
            WAIT_COMMIT: record.checkStatus === 'WAIT_COMMIT',
            CHECKING: !['WAIT_COMMIT', 'PASS'].includes(record.checkStatus),
            PASS: record.checkStatus === 'PASS',
          }"
        >
          {{ record.checkStatusName }}
        </span>
      </template>
      <div slot="transferType" slot-scope="text, record">
        {{ formatData(transferTypeList, record.type) }}
      </div>
      <div slot="eqpNameList" slot-scope="text, record">
        {{ getEqpNameList(record.eqpBorrowItemBPOList) }}
      </div>
    </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 { uniqBy } from "lodash";
import moment from "moment";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import FieldExtendMixin from "@/mixins/fieldExtend";
import ApiConstant from "@/api/ApiConstant";
import MomEditButton from "@/components/MomEditButton";
import ExamineProgress from "@/components/epms/ExamineProgress";

export default {
  components: { MomEditButton, MegaDrawer, ExamineProgress },
  mixins: [FieldExtendMixin],
  data() {
    return {
      transferTypeList: [],
      loading: false, // 表格loading
      // 查询的表单的配置项
      queryParam: {
        name: "",
        dateArr: [],
      },
      startTime: "",
      endTime: "",
      drawerVisible: false,
      processList: [], // 流程列表
      isFirst: true,
      columns: [
        {
          dataIndex: "code", // 申请单编码
          title: () => this.$t("APPLICATION_FORM_CODE"),
          sorter: false,
          ellipsis: true,
          width: 300,
          scopedSlots: { customRender: "code" },
        },
        {
          dataIndex: "name", // 申请单标题
          title: () => this.$t("APPLICATION_FORM_TITLE"),
          sorter: false,
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: "name" },
        },
        {
          dataIndex: "toLocation", // 目标位置
          title: () => this.$t("TRANSFER_TARGET_POSITION"),
          sorter: false,
          ellipsis: true,
          width: 300,
        },
        {
          dataIndex: "eqpBorrowItemBPOList", // 设备清单
          title: () => this.$t("EQUIPMENT_LIST"),
          sorter: false,
          ellipsis: true,
          width: 500,
          scopedSlots: { customRender: "eqpNameList" },
        },
        {
          dataIndex: "checkStatus",
          align: "left",
          sorter: true,
          ellipsis: true,
          width: 200,
          title: () => this.$t("FORM") + this.$t("STATUS"), // 表单状态
          scopedSlots: { customRender: "checkStatusName" },
        },
        {
          dataIndex: "applyUserName", // 更新人员
          sorter: false,
          ellipsis: true,
          title: () => this.$t("APPLICANT"),
          width: 150,
        },
        {
          dataIndex: "applyTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("APPLICATION_TIME"),
          width: 200,
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        (h, value, a, b) => {
          const { text, record } = value;
          if (
            this.hasAuth("EPMS:EQP_BORROW:EDIT") &&
            record.checkStatus === "WAIT_COMMIT"
          ) {
            return (
              <span
                class="text-primary cursor-pointer"
                onClick={() => this.handleAudit(record)}
              >
                <i
                  class="iconfont icon-fabu1"
                  title={this.$t("COMMIT_AUDIT")}
                />
              </span>
            );
          }
          return null;
        },
        (h, { record }) =>
          this.hasAuth("EPMS:EQP_BORROW:ADD") && (
            <a-icon
              type="copy"
              title={this.$t("COPY")}
              onClick={() => this.handleCopy(record)}
            />
          ),
        (h, { record }) =>
          this.hasAuth("EPMS:EQP_BORROW:EDIT") &&
          record.checkStatus === "WAIT_COMMIT" && (
            <a-icon
              type="edit"
              title={this.$t("EDIT")}
              onClick={() => this.handleEdit(record)}
            />
          ),
        (h, { record }) =>
          this.hasAuth("EPMS:EQP_BORROW:DELETE") &&
          record.checkStatus === "WAIT_COMMIT" && (
            <a-icon
              type="delete"
              title={this.$t("DELETE")}
              onClick={() => this.handleDelete(record)}
            />
          ),
      ],
      dataSource: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      tableNameList: [
        {
          key: "epm_eqp_borrow",
          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"), // 申请单标题
          itemType: "custom",
          customRender: () => {
            return (
              <SelectSearch
                isReset={this.isReset}
                show-multiple={true}
                need-disabled={false}
                option-label={"name"}
                query-list-key={"name"}
                requestApi={"/api/epm/eam/eqp-borrow/search"}
                onChange={this.onSelectSearchChange}
              />
            );
          },
        },
        dateArr: {
          itemType: "custom",
          label: () => this.$t("DATE"),
          customRender: () => {
            return (
              <div class={"flex"}>
                <a-date-picker
                  style={"width: 48%"}
                  allowClear={false}
                  disabledDate={this.disabledStartDateSec}
                  v-model={this.startTime}
                  onChange={() => {
                    this.changeStartTime();
                  }}
                />
                <span>~</span>
                <a-date-picker
                  style={"width: 48%"}
                  allowClear={false}
                  disabledDate={this.disabledEndDate}
                  v-model={this.endTime}
                  onChange={() => {
                    this.changeEndTime();
                  }}
                />
              </div>
            );
          },
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          const selectedStatus = selectedRows.length
            ? selectedRows.map((row) => row.checkStatus)
            : [];
          this.selectedStatus = Array.from(new Set(selectedStatus));
          // if (this.selectedRowKeys.length) {
          //   this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
          // } else {
          //   this.selectedRows = selectedRows;
          // }
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.defaultFlag === "Y",
          },
        }),
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:EQP_BORROW_TYPE`
        ), // 移转类型
      ]).then(([typeRes]) => {
        this.transferTypeList = typeRes.data?.data;
      });
    },
    formatData(data, status = "") {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    getEqpNameList(list) {
      const nameList = list.map((item) => item.eqpName);
      return nameList.join();
    },
    onSelectSearchChange(e, info) {
      this.isReset = false;
      this.queryParam.name = info;
    },
    changeStartTime() {
      if (this.isFirst) {
        this.endTime = "";
        this.isFirst = false;
      }
    },
    changeEndTime() {
      if (this.isFirst) {
        this.startTime = "";
        this.isFirst = false;
      }
    },
    disabledStartDateSec(startValue) {
      const toDay = new Date().getTime();
      if (!this.endTime) {
        return startValue.valueOf() >= toDay;
      }
      const endValue = moment(this.endTime);
      return (
        startValue.valueOf() > endValue.valueOf() ||
        startValue.valueOf() >= toDay
      );
    },
    disabledEndDate(endValue) {
      const toDay = new Date().getTime();
      if (!this.startTime) {
        return endValue.valueOf() >= toDay;
      }
      const startValue = moment(this.startTime);
      return (
        startValue.valueOf() > endValue.valueOf() || endValue.valueOf() >= toDay
      );
    },
    handleReset() {
      this.isReset = true;
      this.queryParam.name = "";
      this.startTime = "";
      this.endTime = "";
      this.dataSource = [];
      this.page = 1;
      this.$refs.MomTable?.search();
    },
    // 获取字段扩展数据
    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 = [];
      const { name } = params;
      const { startTime, endTime } = this;
      const searchParams = {
        ...params,
        idList: name && name.length > 0 ? name.join() : "",
        startTime: startTime
          ? `${moment(new Date(startTime)).format("YYYY-MM-DD")} 00:00:00`
          : "",
        endTime: endTime
          ? `${moment(new Date(endTime)).format("YYYY-MM-DD")} 23:59:59`
          : "",
      };
      delete searchParams.name;
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-borrow/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleEdit(row) {
      this.$router.push({
        path: "/eam/account_management/equipment_borrow/edit",
        query: {
          id: row.id,
        },
      });
    },
    // 监听详情点击事件
    handleView({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/account_management/equipment_borrow/view",
      });
    },
    handleItem({ id }) {
      const params = {
        sourceTicketId: id,
        checkProcessType: "MOLD_SCRAP_CHECK", // 签核类型，模具报废
      };
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-borrow/get-by-id/${id}`
        )
        .then((res) => {
          const list = res.data.data?.epmCheckProcessLogBPOList || [];
          this.processList = [...list];
        });
      this.drawerVisible = true;
    },
    handleCancel() {
      this.drawerVisible = false;
    },
    handleAudit(row) {
      let params = {};
      if (row.id) {
        params = {
          ids: [row.id],
        };
      } else {
        params = {
          ids: this.selectedRowKeys,
        };
      }
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-borrow/commit-to-check`,
          params
        )
        .then(() => {
          this.$message.success(this.$t("SUBMIT") + this.$t("SUCCEEDED"));
          this.selectedRowKeys = [];
          this.selectedRows = [];
          this.$refs.MomTable?.query();
        });
    },
    handleAdd() {
      this.$router.push({
        path: "/eam/account_management/equipment_borrow/add",
      });
    },
    handleCopy(row) {
      this.$router.push({
        path: "/eam/account_management/equipment_borrow/add",
        query: {
          id: row.id,
        },
      });
    },
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-borrow/${row.id}`
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleBatchDelete() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const params = {
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/epm/eam/eqp-borrow/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.selectedRowKeys = [];
              this.selectedRows = [];
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .error-type .ant-form-item-children {
  display: flex;
}
.tips-icon {
  width: 50px;
  text-align: center;
  font-size: 20px;
  color: #ff9041;
}
.name_link {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
</style>
