<template>
  <div class="app-container">
    <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="$t('报工类型')" prop="feedbackType">
        <el-select v-model="queryParams.feedbackType" clearable>
          <el-option v-for="dict in dict.type.mes_feedback_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('common.workstation_name')" prop="workstationName">
        <el-input v-model="queryParams.workstationName" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('外协单号')" prop="assistProcessCode">
        <el-input v-model="queryParams.assistProcessCode" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('生产工单编号')" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('产品物料编码')" prop="itemCode">
        <el-input v-model="queryParams.itemCode" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('产品物料名称')" prop="itemName">
        <el-input v-model="queryParams.itemName" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('产品图号')" prop="customerDrawingNo">
        <el-input v-model="queryParams.customerDrawingNo" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('排产次数')" prop="taskBatch">
        <el-input v-model="queryParams.taskBatch" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('工序')" prop="processName">
        <el-input v-model="queryParams.processName" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('报工时间')" prop="feedbackTimeRange">
        <el-date-picker
          v-model="feedbackTimeRange"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 360px"
        />
      </el-form-item>
      <el-form-item :label="$t('销售订单号')" prop="orderCode">
        <el-input v-model="queryParams.orderCode" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('销售序号')" prop="orderSerial">
        <el-input v-model="queryParams.orderSerial" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('报工人')" prop="nickName">
        <el-input v-model="queryParams.nickName" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('记录人')" prop="recordUser">
        <el-input v-model="queryParams.recordUser" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:pro:feedback:add']">{{ $t('common.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:pro:feedback:edit']">{{ $t('common.edit') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:pro:feedback:remove']">{{ $t('common.del') }}</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-printer" size="mini" :disabled="single" @click="handleQrcode"
          v-hasPermi="['mes:pro:feedback:edit']">{{$t('打印二维码')}}</el-button>
        <el-button type="success" plain icon="el-icon-upload2" size="mini" :disabled="multiple" @click="handleSyncSap"
          v-hasPermi="['mes:pro:feedback:edit']">{{$t('推送SAP')}}</el-button>
        <el-button type="primary" size="mini" @click="handleExport">{{$t('导出')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="feedbackList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('报工类型')" align="center" width="80" prop="feedbackType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_feedback_type" :value="scope.row.feedbackType" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.workstation')" width="120" align="center" prop="workstationName" />
      <el-table-column :label="$t('common.workunit')" width="120" align="center" prop="workunitName" />
      <el-table-column :label="$t('外协单号')" width="150" align="center" prop="assistProcessCode" />
      <el-table-column :label="$t('生产工单编号')" width="150" align="center" prop="workorderCode" />
      <el-table-column :label="$t('产品图号')" width="150" align="center" prop="customerDrawingNo" />
      <el-table-column :label="$t('排产次数')" width="100" align="center" prop="taskBatch" />
      <el-table-column :label="$t('工序')" width="120" align="center" prop="processName" show-overflow-tooltip />
      <el-table-column :label="$t('销售订单号')" width="150" align="center" prop="orderCode" />
      <el-table-column :label="$t('销售序号')" width="150" align="center" prop="orderSerial" />
      <el-table-column :label="$t('产品物料编码')" width="120" align="center" prop="itemCode" />
      <el-table-column :label="$t('产品物料名称')" min-width="250" show-overflow-tooltip align="center" prop="itemName" />
      <el-table-column :label="$t('规格型号')" width="100" align="center" prop="specification" />
      <el-table-column :label="$t('报工数量')" align="center" prop="feedbackTime" width="180">
        <template slot-scope="scope">
          <span>{{ getSumNumber(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('合格数量')" width="100" align="center" prop="quantityQualify" />
      <el-table-column :label="$t('不合格数量')" width="100" align="center" prop="quantityUnqualify" />
      <el-table-column :label="$t('报工人')" width="100" align="center" prop="nickName" />
      <el-table-column :label="$t('SAP推送')" width="90" align="center" prop="sapPushStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.sapPushStatus === '1' ? 'success' : 'info'" size="mini">
            {{ scope.row.sapPushStatus === '1' ? $t('已推送') : $t('未推送') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('报工时间')" align="center" prop="feedbackTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.feedbackTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.option')" align="center" fixed="right" width="220px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-query" @click="handleView(scope.row)"
            v-hasPermi="['mes:pro:feedback:query']">{{$t('查看')}}</el-button>
          <el-button v-if="scope.row.sapPushStatus !== '1'" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['mes:pro:feedback:edit']">{{ $t('common.edit') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleModifyRecord(scope.row)"
            v-hasPermi="['mes:pro:feedback:query']">{{$t('修改记录')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产报工记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('报工类型')" prop="feedbackType">
              <el-select v-model="form.feedbackType" :disabled="optType === 'edit' || optType === 'view'" @change="handleFeedbackTypeChange">
                <el-option v-for="dict in dict.type.mes_feedback_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.feedbackType == 'ASSIST_PROCESS'" :span="8">
            <el-form-item :label="$t('外协单号')" prop="assistProcessCode">
              <el-input v-model="form.assistProcessCode">
                <el-button slot="append" icon="el-icon-search"
                  @click="$refs.assistProcessSelect.showFlag = true"></el-button>
              </el-input>
            </el-form-item>
            <assistProcessSelect v-if="open" ref="assistProcessSelect" @onSelected="onAssistProcessSelect">
            </assistProcessSelect>
          </el-col>
          <el-col v-if="form.feedbackType == 'ASSIST_PROCESS'" :span="8">
            <el-form-item :label="$t('是否关单')" prop="closeType">
              <el-radio-group v-model="form.closeType">
                <el-radio :label="1">{{$t('是')}}</el-radio>
                <el-radio :label="0">{{$t('否')}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <assistProcessSelect v-if="open" ref="assistProcessSelect" @onSelected="onAssistProcessSelect">
            </assistProcessSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('生产工单')" prop="workorderCode">
              <el-input :disabled="isWorkorderTaskDisabled" v-model="form.workorderCode">
                <el-button :disabled="isWorkorderTaskDisabled" slot="append" icon="el-icon-search"
                  @click="handleWorkorderSelect"></el-button>
              </el-input>
            </el-form-item>
            <WorkorderSelect v-if="open" ref="woSelect" @onSelected="onWorkorderSelected"></WorkorderSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('生产任务')" prop="taskCode">
              <el-input :disabled="isWorkorderTaskDisabled" v-model="form.taskCode">
                <el-button :disabled="isWorkorderTaskDisabled" slot="append" icon="el-icon-search"
                  @click="handleTaskSelect"></el-button>
              </el-input>
            </el-form-item>
            <ProtaskSelect v-if="open" ref="taskSelect" :workorderId="form.workorderId" @onSelected="onTaskSelected">
            </ProtaskSelect>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('产品编码')" prop="itemCode">
              <el-input v-model="form.itemCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('产品名称')" prop="itemName">
              <el-input v-model="form.itemName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('单位')" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('规格型号')" prop="specification">
              <el-input v-model="form.specification" type="textarea" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('报工数量')" prop="quantityFeedback">
              <el-input disabled v-model="form.quantityFeedback" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('良品报工')" prop="quantityQualify">
              <el-input-number :min="0" :disabled="optType === 'view'" @change="handleQuantityChanged" v-model="form.quantityQualify"
                />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('不良品报工')" prop="quantityUnqualify">
              <el-input-number :min="0" :disabled="optType === 'view'" @change="handleQuantityChanged" v-model="form.quantityUnqualify"
                />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('加工工时')" prop="machineTime">
              <el-input-number :min="0" :disabled="optType === 'view'" v-model="form.machineTime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('报工人')" prop="nickName">
              <el-input v-model="form.nickName" :disabled="optType === 'edit' || optType === 'view'">
                <el-button slot="append" :disabled="optType === 'edit' || optType === 'view'" @click="handleUserSelect" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <UserSingleSelect v-if="open" ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('报工时间')" prop="feedbackTime">
              <el-date-picker clearable v-model="form.feedbackTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                :disabled="optType === 'edit' || optType === 'view'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input v-model="form.remark" type="textarea" :disabled="optType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'">{{ $t('common.back') }}</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'">{{$t('保 存')}}</el-button>
        <!-- <el-button type="primary" @click="handleSubmit" v-if="form.status =='PREPARE' && optType !='view' && form.recordId !=null ">提交审批</el-button>
        <el-button type="success" @click="handleExecute" v-if="form.status =='APPROVING'  && form.recordId !=null">审批通过</el-button>
        <el-button type="danger" @click="handleReject" v-if="form.status =='APPROVING'  && form.recordId !=null">审批不通过</el-button> -->
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 修改记录 -->
    <el-dialog :title="$t('修改记录')" :visible.sync="modifyRecordOpen" width="900px" append-to-body>
      <el-table v-loading="modifyRecordLoading" :data="modifyRecordList" size="small">
        <el-table-column :label="$t('修改时间')" prop="createTime" width="160" />
        <el-table-column :label="$t('修改人')" prop="createBy" width="100" />
        <el-table-column :label="$t('修改内容')" min-width="400">
          <template slot-scope="scope">
            <span>{{ formatModifyBody(scope.row.requestBody) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>


import { listFeedback, getFeedback, delFeedback, addFeedback, updateFeedback, execute, syncSapBatch, listModifyRecord, listNextProcess } from "@/api/mes/pro/feedback";
import WorkorderSelect from "@/components/workorderSelect/single.vue"
import WorkstationSelect from "@/components/workstationSelect/simpletableSingle.vue"
import UserSingleSelect from "@/components/userSelect/single.vue"
import ProtaskSelect from "@/components/TaskSelect/taskSelectSingle.vue"
import assistProcessSelect from "./components/assistProcessSelect.vue"
import { postPrintPdf } from '@/utils/ruoyi'
import dayjs from 'dayjs'
export default {
  name: "Feedback",
  components: { WorkorderSelect, WorkstationSelect, UserSingleSelect, ProtaskSelect, assistProcessSelect },
  dicts: ['mes_order_status', 'mes_feedback_type'],
  data() {
    return {
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产报工记录表格数据
      feedbackList: [],

      selectRow: [],
      feedbackTimeRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      modifyRecordOpen: false,
      modifyRecordLoading: false,
      modifyRecordList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        feedbackType: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        workorderId: null,
        assistProcessCode: null,
        workorderCode: null,
        workorderName: null,
        taskId: null,
        taskCode: null,
        itemId: null,
        itemCode: null,
        itemCode: null,
        itemName: null,
        customerDrawingNo: null,
        taskBatch: null,
        processName: null,
        feedbackTimeStart: null,
        feedbackTimeEnd: null,
        orderCode: null,
        orderSerial: null,
        unitOfMeasure: null,
        specification: null,
        quantity: null,
        quantityFeedback: null,
        quantityQualify: null,
        quantityUnqualify: null,
        feedbackTime: null,
        userName: null,
        nickName: null,
        feedbackChannel: null,
        machineTime: 0,
        recordUser: null,
        recordNick: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        feedbackType: [
          { required: true, message: this.$t('报工类型不能为空'), trigger: "change" }
        ],
        taskCode: [
          { required: true, message: this.$t('请选择生产任务'), trigger: ['blur', 'change'] }
        ],
        workorderCode: [
          { required: true, message: this.$t('生产工单不能为空'), trigger: ['blur', 'change'] }
        ],
        assistProcessCode: [
          { required: true, message: this.$t('外协工单不能为空'), trigger: ['blur', 'change'] }
        ],
        closeType: [
          { required: true, message: this.$t('是否关单不能为空'), trigger: ['blur', 'change'] }
        ],
        nickName: [
          { required: true, message: this.$t('请选择报工人'), trigger: ['blur', 'change'] }
        ],
        feedbackTime: [
          { required: true, message: this.$t('请选择报工时间'), trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    isWorkorderTaskDisabled() {
      return this.form.feedbackType === 'ASSIST_PROCESS' || this.optType === 'edit' || this.optType === 'view'
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getSumNumber(row) {
      const first = row.quantityQualify ? Number(row.quantityQualify) : 0
      const last = row.quantityUnqualify ? Number(row.quantityUnqualify) : 0
      return first + last
    },
    /** 查询生产报工记录列表 */
    getList() {
      this.loading = true;
      if (this.feedbackTimeRange && this.feedbackTimeRange.length === 2) {
        this.queryParams.feedbackTimeStart = this.feedbackTimeRange[0]
        this.queryParams.feedbackTimeEnd = this.feedbackTimeRange[1]
      } else {
        this.queryParams.feedbackTimeStart = null
        this.queryParams.feedbackTimeEnd = null
      }
      listFeedback(this.queryParams).then(response => {
        this.feedbackList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleFeedbackTypeChange(value) {
      console.log(value)
      if (value !== 'ASSIST_PROCESS') {
        this.form.assistProcessCode = null
        this.form.closeType = 0
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        feedbackType: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        routeId: null,
        routeCode: null,
        processId: null,
        processCode: null,
        processName: null,
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        taskId: null,
        taskCode: null,
        itemId: null,
        itemCode: null,
        itemCode: null,
        itemName: null,
        specification: null,
        assistProcessCode: null,
        closeType: 0,
        quantity: 0,
        machineTime: 0,
        quantityFeedback: 0,
        quantityQualify: 0,
        quantityUnqualify: 0,
        userName: null,
        nickName: null,
        feedbackChannel: null,
        feedbackTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        recordUser: null,
        recordNick: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    handleQuantityChanged() {
      this.form.quantityFeedback = this.form.quantityQualify + this.form.quantityUnqualify;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.feedbackTimeRange = []
      this.resetForm("queryForm");
      this.queryParams.feedbackTimeStart = null
      this.queryParams.feedbackTimeEnd = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.selectRow = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('添加生产报工记录');
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.sapPushStatus === '1') {
        this.$modal.msgWarning(this.$t('该报工记录已推送ERP，不允许修改'))
        return
      }
      this.reset();
      const recordId = row.recordId || this.ids
      getFeedback(recordId).then(response => {
        this.form = response.data;
        if (dayjs(response.data.feedbackTime, 'YYYY-MM-DD', true).isValid()) {
          this.form.feedbackTime = response.data.feedbackTime + ' 00:00:00'
        }
        this.open = true;
        this.title = this.$t('修改生产报工记录');
        this.optType = "edit";
      });
    },
    handleModifyRecord(row) {
      this.modifyRecordOpen = true
      this.modifyRecordLoading = true
      this.modifyRecordList = []
      listModifyRecord(row.recordId).then(res => {
        this.modifyRecordList = res.data || []
      }).finally(() => {
        this.modifyRecordLoading = false
      })
    },
    formatModifyBody(body) {
      if (!body) return ''
      try {
        const obj = JSON.parse(body)
        const before = obj.before || {}
        const after = obj.after || {}
        const parts = []
        if (before.quantityQualify !== after.quantityQualify) {
          parts.push(`合格: ${before.quantityQualify} → ${after.quantityQualify}`)
        }
        if (before.quantityUnqualify !== after.quantityUnqualify) {
          parts.push(`不合格: ${before.quantityUnqualify} → ${after.quantityUnqualify}`)
        }
        if (before.machineTime !== after.machineTime) {
          parts.push(`工时: ${before.machineTime || '-'} → ${after.machineTime || '-'}`)
        }
        if (before.remark !== after.remark) {
          parts.push(`备注: ${before.remark || '-'} → ${after.remark || '-'}`)
        }
        return parts.length ? parts.join('；') : body
      } catch (e) {
        return body
      }
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const recordId = row.recordId || this.ids;
      getFeedback(recordId).then(response => {
        this.form = response.data;
        if (dayjs(response.data.feedbackTime, 'YYYY-MM-DD', true).isValid()) {
          this.form.feedbackTime = response.data.feedbackTime + ' 00:00:00'
        }
        this.open = true;
        this.title = this.$t('查看生产报工单信息');
        this.optType = "view";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateFeedback(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.edit_success'));
              this.open = false;
              this.getList();

            });
          } else {
            addFeedback(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.add_success'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.status = "APPROVING";
          if (this.form.recordId != null) {
            updateFeedback(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('提交成功'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //审批通过执行
    handleExecute() {
      const recordIds = this.form.recordId;
      this.$modal.confirm(this.$t('确认执行报工？')).then(function () {
        return execute(recordIds)//执行报工
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('执行成功'));
        this.open = false;
      }).catch(() => { });
    },
    //审批不通过，拒绝
    handleReject() {
      this.form.status = "PREPARE";
      if (this.form.recordId != null) {
        updateFeedback(this.form).then(response => {
          this.$modal.msgSuccess(this.$t('提交成功'));
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$modal.confirm(this.$t('common.confirm_del_data')).then(function () {
        return delFeedback(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.del_success'));
      }).catch(() => { });
    },

    /** 批量推送 SAP */
    handleSyncSap() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgWarning(this.$t('请选择要推送的报工记录'))
        return
      }
      const pushedRows = this.selectRow.filter(row => row.sapPushStatus === '1')
      const recordIds = this.selectRow.filter(row => row.sapPushStatus !== '1').map(row => row.recordId)
      if (pushedRows.length > 0 && recordIds.length === 0) {
        this.$modal.msgWarning(this.$t('所选记录均已推送SAP，不能重复推送'))
        return
      }
      if (pushedRows.length > 0) {
        this.$modal.msgWarning(this.$t('已跳过') + pushedRows.length + this.$t('条已推送记录'))
      }
      if (recordIds.length === 0) {
        return
      }
      this.$modal.confirm(this.$t('确认将选中的报工记录推送至SAP？末道工序推生产入库，非末道工序推生产转移单。')).then(() => {
        this.loading = true
        return syncSapBatch(recordIds)
      }).then(response => {
        const result = response.data || {}
        const messages = result.messages || []
        const summary = `成功 ${result.successCount || 0} 条，失败 ${result.failCount || 0} 条`
        if (result.failCount > 0) {
          this.$alert([summary, ...messages].join('\n'), this.$t('推送结果'), { confirmButtonText: this.$t('确定') })
        } else {
          this.$modal.msgSuccess(summary)
        }
        this.getList()
      }).catch(() => {}).finally(() => {
        this.loading = false
      })
    },

    /** 二维码打印 */
    handleQrcode() {
      let workunitName = '';
      let detail = []
      if(this.selectRow.some(v => v.qrcode!=null)){
        this.$message.warning(this.$t('该数据是包装工序的报工，不能打印二维码'))
        return
      }
      this.selectRow.forEach((s, i) => {

        listNextProcess({ taskId: s.taskId }).then(workunit => {
          workunitName = workunit.data.workunitName;
          detail.push({
            "barcode": s.workorderCode,
            "showText": this.$t('编排单号') + s.arrangeCode + this.$t('\n工单号') + s.workorderCode + this.$t('\n数量') + s.quantityQualify + this.$t('\n下道工序机台:') + workunitName,
            "gp": i + 1
          })
          detail.push({
            "barcode": s.workorderCode,
            "showText": this.$t('编排单号') + s.arrangeCode + this.$t('\n工单号') + s.workorderCode + this.$t('\n数量') + s.quantityQualify + this.$t('\n下道工序机台:') + workunitName,
            "gp": i + 1
          })
          postPrintPdf(
            "qrcode-50*50-2",
            {
              detail
            }
          );
        });
      });

    },




    /** 导出按钮操作 */
    handleExport() {
      if (this.feedbackTimeRange && this.feedbackTimeRange.length === 2) {
        this.queryParams.feedbackTimeStart = this.feedbackTimeRange[0]
        this.queryParams.feedbackTimeEnd = this.feedbackTimeRange[1]
      } else {
        this.queryParams.feedbackTimeStart = null
        this.queryParams.feedbackTimeEnd = null
      }
      this.download1('mes/pro/feedback/list/export', {
        ...this.queryParams,
        pageNum: null,
        pageSize: null
      }, `feedback_${new Date().getTime()}.xlsx`)
    },
    //选择生产工单
    handleWorkorderSelect() {
      this.$refs.woSelect.showFlag = true;
    },
    onWorkorderSelected(row) {
      if (row != undefined && row != null) {
        this.form.workorderId = row.workorderId;
        this.form.workorderCode = row.workorderCode;
        this.form.workorderName = row.workorderName;
        this.form.itemId = row.productId;
        this.form.itemCode = row.productCode;
        this.form.itemName = row.productName;
        this.form.specification = row.productSpc;
        this.form.unitOfMeasure = row.unitOfMeasure;
      }
    },
    onAssistProcessSelect(row) {
      if (row != undefined && row != null) {
        this.form.workorderId = row.workorderId;
        this.form.workorderCode = row.workorderCode;
        this.form.taskId = row.taskId;
        this.form.taskCode = row.taskCode;
        this.form.assistProcessCode = row.assistProcessCode;
      }
    },
    handleTaskSelect() {
      this.$refs.taskSelect.showFlag = true;
      this.$refs.taskSelect.getList();
    },
    onTaskSelected(row) {
      debugger;
      if (row != undefined && row != null) {
        this.form.taskId = row.taskId;
        this.form.taskCode = row.taskCode;
        this.form.taskName = row.taskName;
        this.form.workstationId = row.workstationId;
        this.form.workstationCode = row.workstationCode;
        this.form.workstationName = row.workstationName;
        this.form.processId = row.processId;
        this.form.processCode = row.processCode;
        this.form.processName = row.processName;
        this.form.routeId = row.routeId;
        this.form.routeCode = row.routeCode;
        this.form.isCheck = row.isCheck;
        if (row.isCheck == 'N') {
          this.form.quantityUncheck = 0;
        } else {
          this.form.quantityQualify = 0;
          this.form.quantityUnqualify = 0;
        }
      }
    },
    //点击人员选择按钮
    handleUserSelect() {
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row) {
      this.form.nickName = row.nickName;
      this.form.userName = row.userName;
    }
  }
};
</script>
