<template>
  <ele-modal
    title="首件两检报工"
    :visible.sync="dialogVisible"
    width="95%"
    :before-close="handleClose"
    append-to-body
    :maxable="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="two-layout">
      <el-row :gutter="10" class="full-row">
        <el-col :span="12" class="full-col">
          <div class="pane">
            <div class="pane-title">首件两检</div>
            <div
              v-show="leftMode === 'list'"
              class="fill-box"
              v-loading="loading"
            >
              <ele-pro-table
                ref="table"
                row-key="id"
                :columns="columns"
                :datasource="list"
                cache-key="mes-ruleRecordsList-20260208-1"
                autoAmendPage
                :need-page="false"
                @refresh="getData"
                height="calc(80vh - 160px)"
              >
                <template v-slot:selfCheck="{ row }">
                  <el-button
                    type="primary"
                    @click="selfRequest(row)"
                    v-if="row.status == 0"
                    >自检请托</el-button
                  >
                  <el-button
                    type="primary"
                    :disabled="row.status != 0"
                    @click="reportClick(row, 1)"
                    >{{ row.status == 0 ? '报工' : '已报工' }}</el-button
                  >

                  <el-button
                    type="primary"
                    v-if="row.status == 2 || row.status == 3"
                    @click="reportClick(row, 1, 'detail')"
                    >详情</el-button
                  >
                </template>

                <template
                  v-slot:specialInspection="{ row }"
                  v-if="
                    $hasPermission(
                      'mes:firstarticledualinspectionitem:specialreport'
                    )
                  "
                >
                  <el-button
                    type="primary"
                    :disabled="row.status != 2"
                    @click="reportClick(row, 2)"
                    >{{ row.status == 3 ? '已报工' : '报工' }}</el-button
                  >

                  <el-button
                    type="primary"
                    v-if="row.status == 3"
                    @click="reportClick(row, 2, 'detail')"
                    >详情</el-button
                  >
                </template>

                <template v-slot:status="{ row }">
                  <el-tag v-if="row.status == 0">待自检</el-tag>
                  <el-tag v-if="row.status == 2">待专检</el-tag>
                  <el-tag v-if="row.status == 3">已完成</el-tag>
                </template>
              </ele-pro-table>
            </div>

            <self-inspection-reporting
              v-if="leftMode === 'report'"
              ref="selfReportingRef"
              @cancel="backToList"
              @success="reportSuccess"
            />

            <self-inspection-request
              v-if="leftMode === 'request'"
              ref="selfRequestRef"
              @cancel="backToList"
              @success="reportSuccess"
            />
          </div>
        </el-col>

        <el-col :span="12" class="full-col">
          <div class="pane">
            <div class="pane-title">工艺文件</div>

            <wokePopup ref="wokePopupRef"></wokePopup>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- <self-inspection-reporting
      ref="selfReportingRef"
      @refreshData="getData"
    ></self-inspection-reporting>
    <self-inspection-request
      ref="selfRequestRef"
      @refreshData="getData"
    ></self-inspection-request> -->
  </ele-modal>
</template>

<script>
  import { getQualityInspectionList } from '@/api/produce/qualityInspection.js';
  import dictMixins from '@/mixins/dictMixins';
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import selfInspectionReporting from './components/selfInspectionReporting.vue';
  import selfInspectionRequest from './components/selfInspectionRequest.vue';
  import wokePopup from '../picking/newWokePopup.vue';
  import { parameterGetByCode } from '@/api/system/dictionary-data';

  export default {
    mixins: [dictMixins, tableColumnsMixin],
    components: {
      selfInspectionReporting,
      selfInspectionRequest,
      wokePopup
    },
    data() {
      return {
        dialogVisible: false,
        loading: false,
        produceTaskInfo: null,
        workOrder: null,
        butLoad: false,
        list: [],
        type: '',
        leftMode: 'list',
        currentRow: null,
        reportType: null
      };
    },
    computed: {
      columns() {
        return [
          {
            width: 50,
            type: 'index',
            columnKey: 'index',
            label: '序号',
            align: 'center'
          },
          {
            prop: 'name',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'assignObjectName',
            label: '工位名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },

          {
            prop: 'deviceName',
            label: '设备名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },

          {
            prop: 'selfCheckUserName',
            label: '自检报工人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            prop: 'selfCheckTime',
            label: '自检时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },

          {
            prop: 'specialCheckUserName',
            label: '专检报工人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },

          {
            prop: 'specialCheckTime',
            label: '专检时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },

          {
            prop: 'status',
            slot: 'status',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },

          {
            label: '自检报工',
            align: 'center',
            width: 150,
            fixed: 'right',
            slot: 'selfCheck'
          },
          {
            label: '专检报工',
            align: 'center',
            width: 150,
            fixed: 'right',
            slot: 'specialInspection'
          }
        ];
      }
    },
    methods: {
      async open(workOrder, produceTaskInfo, type, req) {
        // 每次打开重置子界面，避免仍停留在上一次的报工/请托或残留行数据
        this.leftMode = 'list';
        this.currentRow = null;
        this.reportType = null;

        this.workOrder = workOrder;
        this.produceTaskInfo = produceTaskInfo;
        this.type = type;
        this.dialogVisible = true;
        this.getData();
        const res = await parameterGetByCode({
          code: 'mes_craft_file_by_category_code'
        });

        const byCategory = res?.value === '1';

        if (byCategory) {
          this.$refs.wokePopupRef.openTwo(req);
        } else {
          this.$refs.wokePopupRef.open(req);
        }
      },

      // 获取数据
      async getData() {
        this.loading = true;

        try {
          const isSourceTask = this.type == 1;

          const params = {
            produceTaskId: isSourceTask
              ? this.produceTaskInfo?.sourceTaskId
              : this.produceTaskInfo?.id,
            produceTaskInstanceId: isSourceTask
              ? this.produceTaskInfo?.id
              : this.workOrder?.taskId,
            ...(isSourceTask
              ? { type: 2, assigneeId: this.workOrder?.id }
              : { workOrderId: this.workOrder?.id })
          };

          const { list = [] } = await getQualityInspectionList(params);
          this.list = list;
        } catch (error) {
          this.list = [];
        } finally {
          this.loading = false;
        }
      },

      handleClose() {
        this.dialogVisible = false;
        this.leftMode = 'list';
        this.currentRow = null;
        this.reportType = null;
        this.$emit('close');
      },
      async handleUpdate() {
        try {
          this.butLoad = true;
          await this.getData();
          this.$message.success('已更新');
          this.butLoad = false;
        } catch (error) {
          this.butLoad = false;
        }
      },

      // selfRequest(row) {
      //   this.$refs.selfRequestRef.open(row, this.workOrder);
      // },
      selfRequest(row) {
        this.currentRow = row;
        this.leftMode = 'request';

        this.$nextTick(() => {
          this.$refs.selfRequestRef.open(row, this.workOrder);
        });
      },

      // reportClick(row, type, mode) {
      //   this.$refs.selfReportingRef.open(row, type, mode);
      // }
      reportClick(row, type, mode) {
        this.currentRow = row;
        this.reportType = type;
        this.leftMode = 'report';

        this.$nextTick(() => {
          this.$refs.selfReportingRef.open(row, type, mode);
        });
      },

      async backToList() {
        this.leftMode = 'list';
        await this.getData();
      },

      async reportSuccess() {
        this.leftMode = 'list';
        await this.getData();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .two-layout {
    height: 80vh;
    display: flex;
    flex-direction: column;
  }

  .full-row {
    flex: 1;
    height: 100%;
  }

  .full-col {
    height: 100%;
  }

  .pane {
    height: 100%;
    background: #fff;
    border-radius: 4px;
    padding: 10px;

    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  // .step-list {
  //   height: 60vh;
  //   display: flex;
  //   flex-direction: column;
  // }

  /* 表格父级 */
  .table-wrapper {
    flex: 1;
    min-height: 0;
    display: flex;
  }

  .pane-title {
    font-size: 16px;
    font-weight: 600;
    color: #03541c;
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;
  }
</style>
