<template>
  <ele-modal
    title="批量撤回工单"
    :visible.sync="visible"
    :before-close="handleCancel"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="70%"
    :maxable="true"
  >
    <el-card shadow="never">
      <seek-page
        :seekList="seekList"
        @search="search"
        :maxLength="4"
        style="margin-bottom: 15px"
      ></seek-page>
      <ele-pro-table
        ref="table"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        :cache-key="cacheKeyUrl"
        height="calc(100vh - 520px)"
        @selection-change="handleSelectionChange"
        :page-size="defPageSize"
        :initLoad="false"
      >
      </ele-pro-table>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        :loading="revokeLoading"
        @click="handleBatchRevoke"
        >批量撤回</el-button
      >
    </div>
  </ele-modal>
</template>

<script>
  import {
    producetaskrulerecordQueryRecordWorkOrderPage,
    batchRevokeOrder
  } from '@/api/recordRules/index';
  import { getteampage } from '@/api/main/index.js';
  import { getFactoryarea } from '@/api/factoryModel/index';

  export default {
    props: {
      pageName: {
        type: String,
        default: 'productionRecords'
      }
    },
    data() {
      return {
        visible: false,
        revokeLoading: false,
        selection: [],
        planTypeList: {
          productionRecords: 2,
          steamInjectionInspectionRecord: 3,
          solidWasteRecord: 4,
          qualityTestRecords: 5,
          QualityInspection: 7,
          boilerOperationRecord: 6,
          HaulSlag: 8,
          TransportAsh: 9
        },
        planCode: 0,
        columns: [
          {
            type: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            label: '工单单号',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'planCode',
            label: '计划单号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'ruleName',
            label: '记录规则名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'productLineName',
            label: '场站名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'teamName',
            label: '班组',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'createTime',
            label: '工单生成时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: '',
            label: '执行人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              if (row.executeUsers) {
                return row.executeUsers.map((i) => i.userName).join(',');
              }
              return '';
            }
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              const statusMap = {
                0: '未报工',
                1: '执行中',
                2: '已执行'
              };
              return statusMap[row.status] || '';
            }
          }
        ],
        cacheKeyUrl: `pcs-2511241029-${this.pageName + ''}-batchRevoke`,
        teamList: [],
        productLineList: []
      };
    },
    computed: {
      seekList() {
        return [
          {
            label: '关键字',
            value: 'keyword',
            type: 'input',
            width: '280px',
            placeholder: '工单单号，计划单号，记录规则名称'
          },
          {
            label: '场站',
            value: 'productLineId',
            type: 'select',
            planList: this.productLineList,
            placeholder: '请选择'
          },
          {
            label: '班组',
            value: 'teamId',
            type: 'select',
            planList: this.teamList,
            placeholder: '请选择'
          },
          {
            label: '状态',
            value: 'status',
            type: 'select',
            placeholder: '请输入',
            planList: [
              { value: 0, label: '未报工' },
              { value: 1, label: '执行中' },
              { value: 2, label: '已执行' }
            ]
          },
          {
            label: '创建时间：',
            value: 'createTime',
            type: 'date',
            dateType: 'datetimerange',
            placeholder: '',
            width: 380,
            valueAr: ['createTimeStart', 'createTimeEnd']
          }
        ];
      }
    },
    created() {
      getteampage({
        pageNum: 1,
        size: -1
      }).then((res) => {
        this.teamList =
          res.list.map((item) => {
            return {
              value: item.id,
              label: item.name
            };
          }) || [];
      });
      getFactoryarea({
        pageNum: 1,
        size: 999,
        type: 4
      }).then((res) => {
        this.productLineList =
          res.list.map((item) => {
            return {
              value: item.id,
              label: item.name
            };
          }) || [];
      });
    },
    methods: {
      open(planCode) {
        this.visible = true;
        this.selection = [];
        this.planCode = planCode;
        this.$nextTick(() => {
          this.$refs.table.reload();
        });
      },
      reload(where = {}) {
        this.$refs.table.reload({ where });
      },
      datasource({ page, limit, where, order }) {
        const body = {
          ...where,
          ...order,
          pageNum: page,
          size: limit,
          keyword: this.planCode,
          status: 1,
          planType: this.planTypeList[this.pageName]
        };
        return producetaskrulerecordQueryRecordWorkOrderPage(body);
      },
      search(where) {
        if (where.time) {
          where.createTimeStart = where.time[0];
          where.createTimeEnd = where.time[1];
          where.time = null;
        }
        this.reload(where);
      },
      handleSelectionChange(selection) {
        this.selection = selection;
      },
      handleCancel() {
        this.visible = false;
        this.selection = [];
      },
      async handleBatchRevoke() {
        if (!this.selection.length) {
          this.$message.warning('请至少选择一条工单');
          return;
        }
        try {
          this.revokeLoading = true;
          const ids = this.selection.map((item) => item.id);
          await batchRevokeOrder(ids);
          this.$message.success('批量撤回成功');
          this.visible = false;
          this.selection = [];
          this.$emit('refresh');
        } catch (error) {
          this.$message.error('批量撤回失败');
        } finally {
          this.revokeLoading = false;
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .dialog-footer {
    text-align: right;
  }
</style>
