<template>
  <view class="commonBody">
    <view class="prod-body">
      <view class="prod-body-left">
        <!--        <view class="prod-body-left-btns">-->
        <!--          <view class="workstation">-->
        <!--            工作站名称：-->
        <!--            {{ this.vuex_workstation == null ? '请选择工作站' : this.vuex_workstation.workstationName }}-->
        <!--            &lt;!&ndash;            <u-icon name="edit-pen-fill" size="46" color="#2979ff"></u-icon>&ndash;&gt;-->
        <!--          </view>-->
        <!--          <u-button type="primary" @click="changeWorkstation">切换工作站</u-button>-->
        <!--          &lt;!&ndash;                  <u-button type="primary" @click="commonClick('')">生产任务</u-button>&ndash;&gt;-->
        <!--          &lt;!&ndash;                  <u-button type="primary" @click="commonClick('KnifeTemp')">刀模上架</u-button>&ndash;&gt;-->
        <!--          &lt;!&ndash;                  <u-button type="primary" @click="commonClick('')">生产投料</u-button>&ndash;&gt;-->
        <!--        </view>-->
        <view>
          <u-form :model="tableParams" labelAlign="right" class="tableForm">
            <u-form-item label="编排单号" label-width="70px" name="arrangeCode">
              <uni-easyinput type="text" suffixIcon="scan" v-model="tableParams.arrangeCode" @iconClick="iconClickArrangeCode" placeholder="请输入编排单号" />
            </u-form-item>
            <u-form-item label="生产工单编号" label-width="100px" name="workorderCode">
              <uni-easyinput type="text" suffixIcon="scan" v-model="tableParams.workorderCode" @iconClick="iconClickWorkorderCode" placeholder="请输入生产工单编号" />
            </u-form-item>
            <u-form-item name="allowProduce" label-width="80px" label="当前可加工">
              <uni-data-checkbox v-model="tableParams.allowProduce" @change="getTaskList" :localdata="allowProduceLocal"></uni-data-checkbox>
            </u-form-item>
            <u-form-item name="allowProduce">
              <u-button @click="getTaskList" type="primary" size="medium">搜索</u-button>
            </u-form-item>
          </u-form>
        </view>
        <view class="prod-body-left-task">
          <zb-table
            ref="zbtable"
            :columns="tableColumn"
            :stripe="true"
            rowKey="taskWorkunitId"
            :isTrClassStyle="isTrClassStyle"
            @rowClick="rowClick"
            @toggleRowSelection="toggleRowSelection"
            @toggleAllSelection="toggleAllSelection"
            :border="true"
            :data="tableData"
          ></zb-table>
        </view>
        <view class="prod-body-left-num">可选订单数：{{ tableData.length }}</view>
        <!-- <view class="prod-body-left-bom"> -->
        <!--          <view class="prod-body-left-bom-type">-->
        <!--            <u-subsection :list="typeList" :current="currentType" type="primary" font-size="28"-->
        <!--                          @change="typeChange"></u-subsection>-->
        <!--          </view>-->
        <!--          <view class="prod-body-left-bom-table">-->
        <!--            <u-form>-->
        <!--              <u-row gutter="16">-->
        <!--                <u-col span="3">-->
        <!--                  <u-form-item label="任务单号" label-width="150">-->
        <!--                    {{ curTaskInfo.taskCode }}-->
        <!--                  </u-form-item>-->
        <!--                </u-col>-->
        <!--                <u-col span="4">-->
        <!--                  <u-form-item label="物料条码" label-width="150">-->
        <!--                    <SearchInput v-model="materialRecordInfo.materialBatchNumber" placeholder="请输入物料条码"-->
        <!--                                 hassearchbtn="true"-->
        <!--                                 @inputchange="(val)=>{materialRecordInfo.materialBatchNumber=val}"/>-->
        <!--                  </u-form-item>-->
        <!--                </u-col>-->
        <!--                <u-col span="2">-->
        <!--                  <u-form-item label="数量">-->
        <!--                    <u-number-box :min="0" v-model="materialRecordInfo.quantity"></u-number-box>-->
        <!--                  </u-form-item>-->
        <!--                </u-col>-->
        <!--                <u-col span="1">-->
        <!--                  <u-button type="primary" size="mini" @click="commonClick('MaterialUsageRecord')">添加</u-button>-->
        <!--                </u-col>-->
        <!--                <u-col span="1">-->
        <!--                </u-col>-->
        <!--                <u-col span="5">-->
        <!--                </u-col>-->
        <!--              </u-row>-->
        <!--            </u-form>-->
        <!-- <zb-table :columns="issusLineColumn" :stripe="true" :fit="true" :border="true" :data="issusLineList"></zb-table> -->
        <!--          </view>-->
        <!-- </view> -->
      </view>
      <scroll-view class="prod-body-right" scroll-y>
        <view style="text-align: center; line-height: 80rpx; font-size: 28rpx; font-weight: 600">
          {{ this.vuex_workunit == null ? '请选择工作单元' : this.vuex_workunit.workunitName }}
        </view>
        <u-button type="warning" @click="commonClick('KnifeTemp')">刀模版上下机</u-button>
        <u-button type="primary" @click="commonClick('Refresh')">刷新</u-button>
        <u-button type="success" @click="commonClick('StartTask')">开始作业</u-button>
        <u-button type="warning" @click="commonClick('StopTask')">暂停作业</u-button>
        <u-button type="success" @click="commonClick('Prod')">生产报工</u-button>
        <u-button type="primary" @click="commonClick('FinshTask')">完成作业</u-button>
        <u-button type="primary" @click="commonClick('abnormal')">异常报告</u-button>
        <u-button type="primary" @click="commonClick('FeedingInspection')">投料校验</u-button>
        <u-button type="primary" @click="commonClick('RecoilMaterial')">反冲料登记</u-button>
        <u-button type="primary" @click="commonClick('MaterialRequest')">领料申请</u-button>
        <u-button type="primary" @click="commonClick('MaterialReturn')">退料申请</u-button>
        <u-button type="primary" @click="commonClick('jobAssignment')">作业分派</u-button>
        <u-button type="success" @click="commonClick('StockIn')">完工入库申请</u-button>
        <u-button type="primary" @click="commonClick('ViewPpicture')">查看图片</u-button>
      </scroll-view>
    </view>

    <u-modal
      title="生产报工"
      @confirm="handleSubmitfeedback"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="proVisible"
      width="1800rpx"
    >
      <view>
        <scroll-view style="max-height: 600px" scroll-y="true" class="scroll-Y">
          <view class="feedback-card" v-for="(feedback, i) in feedbackForms" :key="i">
            <u-form label-width="80px" :model="feedback" :rules="rules" labelAlign="right">
              <u-row>
                <u-col span="6">
                  <u-form-item label="任务单号:" prop="quantity">
                    {{ feedback.taskCode }}
                  </u-form-item>
                </u-col>
                <u-col span="6">
                  <u-form-item label="工序:" prop="nickName">
                    {{ feedback.processName }}
                  </u-form-item>
                </u-col>
              </u-row>
              <u-row>
                <u-col span="6">
                  <u-form-item label="报工总数量:" prop="quantity">
                    {{ feedback.quantityQualify + feedback.quantityUnqualify }}
                  </u-form-item>
                </u-col>
                <u-col span="6">
                  <u-form-item label="报工人:" prop="nickName">
                    <u-input v-model="feedback.nickName"></u-input>
                    <u-button @tap="getCode(feedback)" type="success" size="mini">报工人员</u-button>
                  </u-form-item>
                </u-col>
              </u-row>

              <u-row>
                <u-col span="6">
                  <u-form-item label="编排单号:" prop="quantity">
                    {{ feedback.arrangeCode }}
                  </u-form-item>
                </u-col>
                <u-col span="6">
                  <u-form-item label="生产工单:" prop="workorderId">
                    <uni-data-select v-model="feedback.workorderId" :localdata="feedback.workorderOption" @change="workorderSelect($event, i)"></uni-data-select>
                  </u-form-item>
                </u-col>
              </u-row>
              <u-row>
                <u-col span="6">
                  <u-form-item label="合格品数量:" prop="quantityQualify">
                    <u-number-box :min="0" @change="quantityChanged" v-model="feedback.quantityQualify"></u-number-box>
                  </u-form-item>
                </u-col>
                <u-col span="6">
                  <u-form-item label="不良品数量:" prop="quantityUnqualify">
                    <u-number-box :min="0" @change="quantityChanged" v-model="feedback.quantityUnqualify"></u-number-box>
                  </u-form-item>
                </u-col>
              </u-row>
              <u-row v-if="!feedback.isLastProcess">
                <u-col span="6">
                  <u-form-item label="是否打印:" prop="print">
                    <view class="uni-list-item__extra">
                      <u-radio-group v-model="feedback.whether">
                        <u-radio :name="1">是</u-radio>
                        <u-radio :name="0">否</u-radio>
                      </u-radio-group>
                    </view>
                  </u-form-item>
                </u-col>
                <u-col span="6">
                  <u-form-item v-if="feedback.whether == '1'" label="打印内容:" prop="printContents">
                    {{ feedback.printContents }}
                    <!-- <u-input v-model="feedback."></u-input> -->
                  </u-form-item>
                </u-col>
              </u-row>
              <view v-if="feedback.isLastProcess">
                <u-row>
                  <u-col span="6">
                    <u-form-item label="工单指令:" prop="workorderSoDirectiveId">
                      <uni-data-select v-model="feedback.workorderSoDirectiveId" :localdata="feedback.directiveList"></uni-data-select>
                    </u-form-item>
                  </u-col>
                  <u-col span="6">
                    <u-form-item label="工单SIZE:" prop="workorderSoSizeItemId">
                      <uni-data-select v-model="feedback.workorderSoSizeItemId" :localdata="feedback.sizeList"></uni-data-select>
                    </u-form-item>
                  </u-col>
                </u-row>
                <u-row>
                  <u-col span="3">
                    <u-form-item label="净重(KG):" prop="netWeight">
                      <u-number-box :min="0" :positive-integer="false" :input-width="150" v-model="feedback.netWeight"></u-number-box>
                    </u-form-item>
                  </u-col>
                  <u-col span="3">
                    <u-form-item label="小包数:" prop="minPackageNum">
                      <u-number-box :min="0" :positive-integer="false" :input-width="150" v-model="feedback.minPackageNum"></u-number-box>
                    </u-form-item>
                  </u-col>
                  <u-col span="6">
                    <u-form-item label="打印模板:" prop="printTemplate">
                      <u-input v-model="feedback.printTemplate" placeholder="请选择打印模板"></u-input>
                      <u-button @tap="getPrintTemplate(feedback)" type="success" style="margin-left: 20rpx" size="mini">选择打印模板</u-button>
                    </u-form-item>
                  </u-col>
                </u-row>
              </view>
            </u-form>
            <view v-if="feedback.isLastProcess">
              <u-tabs :list="listTabPro" :is-scroll="false" :show-bar="false" :current="feedback.currentTabPro" @change="handleChangeTabPro($event, feedback)"></u-tabs>
              <!-- 指令列表 -->
              <view v-show="feedback.currentTabPro === 0">
                <zb-table :columns="feedback.tableDirectiveColumn" :stripe="true" :border="true" :data="feedback.tableDirectiveData"></zb-table>
              </view>
              <!-- SIZE列表 -->
              <view v-show="feedback.currentTabPro === 1">
                <zb-table :columns="feedback.tableSizeColumn" :stripe="true" :border="true" :data="feedback.tableSizeData"></zb-table>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-modal>
    <u-modal
      title="选择打印模板"
      @confirm="handleSubmitPrintTemplate"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="printTemplateVisible"
      width="1300rpx"
    >
      <view class="feedback-card">
        <print-template ref="printTemplateRef" :data="printTemplateData" />
      </view>
    </u-modal>

    <u-modal
      title="刀模版上下机"
      @confirm="knifeTemp()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="knifeTempVisible"
      width="1600rpx"
    >
      <!-- <u-form label-width="130px" :model="knifeTempSearch" :rules="rules">
        <u-row>
          <u-col span="6">
            <u-form-item label="扫描刃模版条码" prop="quantity">
              <u-input v-model="knifeTempSearch.knifeTempCode"></u-input>
            </u-form-item>
          </u-col>
          <u-col span="6">
            <u-form-item label="扫描库位条码" prop="nickName">
              <u-input v-model="knifeTempSearch.locationCode"></u-input>
            </u-form-item>
          </u-col>
        </u-row>
      </u-form> -->
      <dModelList :data="dModelData" @action="upDownGetList" />
    </u-modal>
    <!-- //生产报工报工人员 -->
    <u-modal
      title="报工人员"
      @confirm="userDetermine()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="userTempVisible"
      width="1300rpx"
    >
      <view class="feedback-card">
        <userPersonnel ref="userPersonnelRef" v-if="userTempVisible" :data="usePersonData" />
      </view>
    </u-modal>
    <u-modal
      title="暂停原因"
      @confirm="stopReasonSubmit()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="stopReasonVisible"
      width="1300rpx"
    >
      <view class="feedback-card" style="height: 200px">
        <u-form label-width="120px" :model="stopReasonForm" :rules="rules">
          <u-form-item label="暂停原因" prop="reason">
            <!-- <uni-data-select v-model="stopReasonForm.reason" :localdata="exception" @change="stopReas"></uni-data-select> -->
            <uni-data-select v-model="stopReasonForm.reason" :localdata="causeList" @change="stopCause"></uni-data-select>
          </u-form-item>
          <u-form-item label="暂停描述" prop="desc">
            <!-- <uni-data-selec v-model="stopReasonForm.desc" :localdata="reasonList"  type=“textarea”></uni-data-select> -->
            <u-input v-model="stopReasonForm.desc" type="textarea"></u-input>
          </u-form-item>
        </u-form>
      </view>
    </u-modal>

    <u-modal
      title="异常报告"
      @confirm="newlyAddss()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '60px', 'padding-top': '0px' }"
      v-model="errorVisible"
      width="1300rpx"
    >
      <view class="feedback-card">
        <u-form label-width="70px" labelAlign="right" :model="ExceptionForms" :rules="rules">
          <!--     <u-form-item label="异常时间" prop="abnormalTime">
             <u-input   :border="true" v-model="ExceptionForms.abnormalTime"></u-input>
              <uni-datetime-picker class="times" type="date" :clear-icon="false" v-model="ExceptionForms.abnormalTime" />
            </u-form-item> -->

          <u-row>
            <u-col span="6">
              <u-form-item label="异常类型" prop="abnormalType">
                <uni-data-select v-model="ExceptionForms.abnormalType" :localdata="exception" @change="stopReas"></uni-data-select>
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="原因" prop="abnormalReason">
                <uni-data-select v-model="ExceptionForms.abnormalReason" :localdata="reasonList"></uni-data-select>
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="编批单号" prop="batchNumber">
                <!--  <u-input :border="true" v-model="ExceptionForms.batchNumber"  ></u-input> -->
                {{ ExceptionForms.batchNumber }}
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="工序" prop="processName">
                <!-- <u-input :border="true" v-model="ExceptionForms.processName"></u-input> -->
                {{ ExceptionForms.processName }}
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="作业单元" prop="workstationName">
                <!-- <u-input :border="true" v-model="ExceptionForms.workstationName"></u-input> -->
                {{ ExceptionForms.workstationName }}
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
    </u-modal>
    <u-modal
      title="投料校验"
      @confirm="feedingInspectionScan()"
      show-cancel-button
      confirmText="继续扫码"
      cancelText="关闭"
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="feedingInspectionVisible"
      width="1300rpx"
    >
      <view class="list-bar">
        <scroll-view scroll-y="true" scroll-x="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <uni-table border stripe :loading="loading" emptyText="未查询到数据">
            <uni-tr>
              <uni-th width="100px" align="center">操作</uni-th>
              <uni-th width="65px" align="center">状态</uni-th>
              <uni-th width="110px" align="center">产品物料编码</uni-th>
              <uni-th width="110px" align="center">产品物料名称</uni-th>
              <uni-th width="80px" align="center">领料数量</uni-th>
              <uni-th width="110px" align="center">批次号</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in feedingInspectionList" :key="index">
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" size="mini" type="primary" @click="validateFeedingInspection(line)">校验</button>
                </view>
              </uni-td>
              <uni-td align="center">{{ line.attr3 == 1 ? '校验' : '未校验' }}</uni-td>
              <uni-td align="center">{{ line.itemCode }}</uni-td>
              <uni-td align="center">{{ line.itemName }}({{ line.specification }})/{{ line.unitOfMeasure }}</uni-td>
              <uni-td align="center">{{ line.quantityIssued }}</uni-td>
              <uni-td align="center">{{ line.batchCode }}</uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal
      title="反冲料登记"
      @confirm="recoilMaterialScan()"
      show-cancel-button
      confirmText="继续扫码"
      cancelText="关闭"
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="recoilMaterialVisible"
      width="1300rpx"
    >
      <view class="list-bar">
        <scroll-view scroll-y="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <uni-table ref="qcTable" border stripe :loading="loading" emptyText="未查询到数据">
            <uni-tr>
              <uni-th width="100px" align="center">操作</uni-th>
              <uni-th width="110px" align="center">产品物料编码</uni-th>
              <uni-th width="110px" align="center">产品物料名称</uni-th>
              <uni-th width="110px" align="center">批次号</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in recoilMaterialList" :key="index">
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" size="mini" type="primary" @click="recoilMaterialDelete(line)">删除</button>
                </view>
              </uni-td>
              <uni-td align="center">{{ line.itemCode }}</uni-td>
              <uni-td align="center">{{ line.itemName }}({{ line.specification }})/{{ line.unitOfMeasure }}</uni-td>
              <uni-td align="center">{{ line.batchNo }}</uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal
      title="领料申请"
      @confirm="materialRequestSave()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="materialRequestVisible"
      width="1300rpx"
    >
      <view class="list-bar">
        <u-form label-width="100px" :model="curTaskInfo">
          <u-row>
            <u-col span="6">
              <u-form-item label="编排单号">
                {{ curTaskInfo.arrangeCode }}
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="生产工单" prop="workorderCode">
                <uni-data-select v-model="curTaskInfo.workorderCode" @change="materialReturnWorkorderProcessItem" :localdata="curTaskInfo.workorderOption"></uni-data-select>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
        <scroll-view scroll-y="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <uni-table ref="materialRequestTable" border stripe :loading="loading" emptyText="未查询到数据">
            <uni-tr>
              <uni-th width="100px" align="center">操作</uni-th>
              <uni-th width="110px" align="center">产品物料编码</uni-th>
              <uni-th width="110px" align="center">产品物料名称</uni-th>
              <uni-th width="80px" align="center">领取数量</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in materialRequestArrays" :key="index">
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" size="mini" type="primary" @click="materialRequestFormShow(line)">补料</button>
                </view>
              </uni-td>
              <uni-td align="center">{{ line.itemCode }}</uni-td>
              <uni-td align="center">{{ line.itemName }}({{ line.specification }})/{{ line.unitOfMeasure }}</uni-td>
              <uni-td align="center">{{ line.applyNum }}</uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal
      title="领料申请数量"
      @confirm="materialRequestSetting()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="materialRequestFormVisible"
      width="700rpx"
    >
      <view class="">
        <u-form label-width="100px">
          <u-row>
            <u-col>
              <u-form-item label="产品物料名称">
                {{ materialRequestFormData.itemName }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-form-item label="领料数量">
                <u-number-box v-model="materialRequestFormData.applyNum" :long-press="false" :positive-integer="false" :size="50" :input-width="190"></u-number-box>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
    </u-modal>

    <u-modal
      title="退料申请"
      @confirm="materialReturnSave()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="materialReturnVisible"
      width="1600rpx"
    >
      <view class="list-bar">
        <u-form :model="materialReturnFormData" label-width="100px">
          <u-row>
            <u-col span="6">
              <u-form-item label="编排单号">
                {{ curTaskInfo.arrangeCode }}
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="生产工单" prop="workorderCode">
                <uni-data-select v-model="materialReturnFormData.workorderCode" @change="materialReturnWorkorderChange" :localdata="curTaskInfo.workorderOption"></uni-data-select>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
        <scroll-view scroll-y="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <uni-table ref="qcTable" border stripe :loading="loading" emptyText="未查询到数据">
            <uni-tr>
              <uni-th width="60px" align="center">操作</uni-th>
              <uni-th width="110px" align="center">产品物料编码</uni-th>
              <uni-th width="110px" align="center">产品物料名称</uni-th>
              <uni-th width="80px" align="center">领料数量</uni-th>
              <uni-th width="80px" align="center">本次退料数</uni-th>
              <uni-th width="80px" align="center">累计退料数</uni-th>
              <uni-th width="110px" align="center">批次号</uni-th>
              <uni-th width="60" align="center">合格</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in materialReturnList" :key="index">
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" size="mini" type="primary" @click="materialReturnFormShow(line)">退料</button>
                </view>
              </uni-td>
              <uni-td align="center">{{ line.itemCode }}</uni-td>
              <uni-td align="center">{{ line.itemName }}({{ line.specification }})/{{ line.unitOfMeasure }}</uni-td>
              <uni-td align="center">{{ line.quantityIssued }}</uni-td>
              <uni-td align="center">{{ line.applyNum }}</uni-td>
              <uni-td align="center">{{ line.totalBackNum }}</uni-td>
              <uni-td align="center">{{ line.batchCode }}</uni-td>
              <uni-td align="center">{{ line.isQualified == 1 ? '是' : '' }}{{ line.isQualified == 0 ? '否' : '' }}</uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal
      title="退料申请数量"
      @confirm="materialReturnSetting()"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="materialReturnFormVisible"
      width="700rpx"
    >
      <view class="">
        <u-form label-width="100px">
          <u-row>
            <u-col>
              <u-form-item label="产品物料名称">
                {{ materialReturnFormData.itemName }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-form-item label="退料数量">
                <u-number-box v-model="materialReturnFormData.applyNum" :long-press="false" :positive-integer="false" :size="50" :input-width="190"></u-number-box>
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col>
              <u-form-item label="是否合格" prop="printName">
                <view class="uni-list-item__extra">
                  <u-radio-group v-model="materialReturnFormData.isQualified">
                    <u-radio name="1">是</u-radio>
                    <u-radio name="0">否</u-radio>
                  </u-radio-group>
                </view>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
    </u-modal>
    <u-modal
      title="详细数据"
      :showConfirmButton="true"
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="showRowDeatilFlag"
      width="1800rpx"
    >
      <view class="">
        <zb-table :columns="tableDetailColumn" :stripe="true" :border="true" :data="tableDataDetail"></zb-table>
      </view>
    </u-modal>
    <!-- //查询图片生产工单 -->
    <u-modal
      title="生产工单"
      show-cancel-button
      :show-confirm-button="false"
      cancel-text="返回"
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="materialReturn"
      width="1300rpx"
    >
      <view class="list-bar">
        <scroll-view scroll-y="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <uni-table ref="qcTable" border stripe :loading="loading" emptyText="未查询到数据">
            <uni-tr>
              <uni-th width="100px" align="center">操作</uni-th>
              <uni-th width="110px" align="center">工单编码</uni-th>
              <uni-th width="110px" align="center">工单名称</uni-th>
              <uni-th width="80px" align="center">来源类型</uni-th>
              <uni-th width="80px" align="center">产品名称</uni-th>
              <uni-th width="110px" align="center">编排单号</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in viewSopPicture" :key="index">
              <uni-td align="center">
                <view class="uni-group">
                  <!-- <button class="uni-button" size="mini" type="primary" @click="materialReturnFormShow(line)">退料 -->
                  <!-- <button class="uni-button" size="mini" type="primary" @click="viewSopsShow()">查看 -->
                  <button class="uni-button" size="mini" type="primary" @click="viewSopsShow(line)">查看</button>
                </view>
              </uni-td>
              <uni-td align="center">{{ line.workorderCode }}</uni-td>
              <uni-td align="center">{{ line.workorderName }}</uni-td>
              <uni-td align="center">{{ line.orderSource }}</uni-td>
              <uni-td align="center">{{ line.productName }}</uni-td>
              <uni-td align="center">{{ line.arrangeCode }}</uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>
    <u-modal
      title="显示图片"
      show-cancel-button
      :show-confirm-button="false"
      cancel-text="返回"
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="material"
      width="680px"
    >
      <view class="list-bar">
        <scroll-view scroll-y="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <view style="display: flex; justify-content: space-between; flex-wrap: wrap">
            <image v-for="(line, index) in viewSop" :key="index" @click="onPreviewTap(line)" style="padding: 10px" class="u-avatar-demo" :src="line" mode="aspectFill"></image>
          </view>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal
      title="作业分派"
      @confirm="handleSubmitJobAssignment"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="jobAssignmentVisible"
      width="1200rpx"
    >
      <view class="feedback-card">
        <u-form :mode="jobAssignmentForm" label-width="100px">
          <u-form-item label="排产数量">
            <u-number-box v-model="jobAssignmentForm.quantity" :long-press="false" :positive-integer="false" :size="50" :input-width="190"></u-number-box>
          </u-form-item>
          <u-form-item label="工作单元">
            <u-input disabled v-model="jobAssignmentForm.workunitName" placeholder="选择工作单元"></u-input>
            <u-button @tap="workunitVisible = true" type="success" size="mini">选择工作单元</u-button>
          </u-form-item>
        </u-form>
      </view>
    </u-modal>

    <u-modal
      title="选择工作单元"
      @confirm="handleSubmitWorkunit"
      show-cancel-button
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="workunitVisible"
      width="1800rpx"
    >
      <view class="feedback-card" v-if="workunitVisible">
        <workunitList ref="workunitRef" />
      </view>
    </u-modal>
  </view>
</template>

<script>
import SearchInput from '@/components/ScanInput/index.vue';
import dModelList from './components/dModelList.vue';
import userPersonnel from './components/userPersonnel.vue';
import printTemplate from './components/printTemplate.vue';
import workunitList from './components/workunitList.vue';
import UButton from '../../../uview-ui/components/u-button/u-button.vue';
import { handleError } from 'vue';
export default {
  name: 'ProdReport',
  components: {
    SearchInput,
    dModelList,
    userPersonnel,
    printTemplate,
    UButton,
    workunitList
  },
  data() {
    return {
      workunitVisible: false,
      jobAssignmentVisible: false,
      jobAssignmentForm: {
        quantity: 1,
        workunitName: null
      },
      listTabPro: [
        {
          name: '指令列表'
        },
        {
          name: 'SIZE列表'
        }
      ],
      tableParams: {
        allowProduce: 1,
        workorderCode: '',
        arrangeCode: ''
      },
      allowProduceLocal: [
        {
          text: '是',
          value: 1
        },
        {
          text: '否',
          value: 0
        }
      ],
      stopReasonForm: {
        reason: null,
        desc: null
      },
      screenHeight: 768,
      usePersonData: {},
      title: '生产报工',
      proVisible: false,
      errorVisible: false,
      form: {},
      feedbackForm: {},
      tableData: [],
      knifeTempVisible: false,
      knifeTempSearch: {
        knifeTempCode: '',
        locationCode: ''
      },
      knifeTempInfo: {
        knifeTemplateCode: '',
        knifeTemplateName: '',
        knifeTemplateSpec: '',
        locationCode: '',
        locationName: '',
        locationType: '',
        locationTypeCode: '',
        locationTypeDesc: '',
        locationTypeDescCode: '',
        locationTypeDescName: '',
        locationTypeDescNameCode: '',
        locationTypeDescNameCode2: ''
      },
      stopReasonList: [
        { value: '中午休息吃饭。', text: '休息吃饭' },
        { value: '刀头模具到期更换，更换期间。', text: '刀头模具到期更换' },
        { value: '没料了，正在领料', text: '领料加仓' }
      ],
      exception: [
        {
          value: 'PROD',
          text: '生产异常'
        },
        {
          value: 'QUAL',
          text: '质量异常'
        },
        {
          value: 'DEVI',
          text: '设备异常'
        }
      ],
      stopReason: '',
      stopReasonVisible: false,
      rules: {
        quantity: [
          {
            required: true,
            message: '请输入合格品数量或者不良品数量！',
            trigger: 'blur'
          }
        ]
      },
      typeList: [
        {
          name: '物料扣减'
        },
        {
          name: 'BOM外扣减'
        }
      ],
      materialRecordInfo: {
        taskCode: '',
        materialBatchNumber: '',
        quantity: 0,
        operatorTime: '',
        depletionMethod: 1
      },
      curTaskInfo: {},
      currentType: 0,
      bomFeeData: [],
      bomFeeColumn: [
        {
          type: 'selection',
          width: 35
        },
        {
          name: 'taskCode',
          label: '物料批次',
          align: 'center',
          width: 150
        },
        {
          name: 'status',
          label: 'ERP物料批次',
          align: 'center',
          width: 150
        },
        {
          name: 'materialBatchNumber',
          label: '物料编码',
          width: 150
        },
        {
          name: 'taskCode',
          label: '序列号',
          width: 150
        },
        {
          name: 'quantity',
          label: '数量',
          width: 150
        },
        {
          name: 'itemCode',
          label: '物料描述'
        }
      ],
      tableColumn: [
        {
          type: 'selection',
          width: 60
        },
        {
          name: 'arrangeCode',
          label: '编排单号',
          width: 85,
          cellFun: (row, index) => {
            console.log(row, index);
            this.tableDataDetail = row.proWorkorderList;
            this.showRowDeatilFlag = true;
          }
        },
        {
          name: 'scheduleStartDateStr',
          label: '计划开始时间',
          width: 95
        },
        {
          name: 'scheduleEndDateStr',
          label: '计划结束时间',
          width: 95
        },
        {
          name: 'quantity',
          label: '任务数量',
          width: 70
        },
        {
          name: 'quantityWait',
          label: '可加工数量',
          width: 80
        },
        {
          name: 'status',
          label: '状态',
          filters: {
            PREPARE: '未开工',
            BEGINNING: '已开工',
            PAUSE: '暂停',
            ERROR_STOP: '异常停工',
            FINISH: '完工'
          },
          width: 65
        },
        // {
        //   name: 'date',
        //   label: '批号',
        //   width: 50,
        // },
        {
          name: 'taskCode',
          label: '任务单号',
          width: 100
        },
        // {
        //   name: 'workorderCode',
        //   label: '生产单号',
        //   width: 120
        // },
        // {
        //   name: 'itemCode',
        //   label: '物料编号',
        //   width: 110,
        // },
        // {
        //   name: 'itemName',
        //   label: '物料名称'
        // },
        {
          name: 'processName',
          label: '工序',
          width: 80
        },
        {
          name: 'quantityQualify',
          label: '合格数量',
          width: 70
        },
        {
          name: 'quantityUnqualify',
          label: '不合格数量',
          width: 80
        }
        // {
        //   name: 'clientName',
        //   label: '作业人员',
        //   width: 60,
        //   align: 'center'
        // }
      ],
      dModelData: [],
      tableSelectData: [],
      feedbackForms: [],
      ExceptionForms: {
        abnormalType: null,
        abnormalReason: null
      },
      viewSopPicture: [],
      viewSop: [],
      reasonList: [],
      causeList: [],
      workorderList: [],
      materialUsageRecordList: [],
      materialusagerecordLoading: false,
      issusLineList: [],
      issusLineColumn: [
        {
          name: 'itemCode',
          label: '产品物料编码'
        },
        {
          name: 'itemName',
          label: '产品物料名称'
        },
        {
          name: 'specification',
          label: '规格型号'
        },
        {
          name: 'unitOfMeasure',
          label: '单位'
        },
        {
          name: 'quantityIssued',
          label: '领料数量'
        },
        {
          name: 'batchCode',
          label: '批次号'
        },
        {
          name: 'warehouseName',
          label: '仓库名称'
        },
        {
          name: 'locationName',
          label: '库区名称'
        },
        {
          name: 'areaName',
          label: '库位名称'
        }
      ],
      feedingInspectionVisible: false,
      recoilMaterialVisible: false,
      materialRequestVisible: false,
      materialReturnVisible: false,
      materialReturn: false,
      stockInVisible: false,
      material: false,
      feedingInspectionList: [],
      recoilMaterialList: [],
      materialRequestList: [],
      materialRequestArrays: [],
      materialReturnList: [],
      materialRequestFormData: {
        itemName: null,
        applyNum: null
      },
      materialRequestFormVisible: false,
      materialRequestSelected: {},
      materialReturnFormData: {
        itemName: null,
        applyNum: 1,
        workorderCode: null
      },
      materialReturnProcessItemData: {
        itemName: null,
        itemCode: null,
        applyNum: 1,
        workorderCode: null
      },
      printTemplateData: null,
      printTemplateVisible: false,
      userTempVisible: false,
      materialReturnFormVisible: false,
      materialReturnSelected: {},
      tableDetailColumn: [
        {
          name: 'workorderCode',
          label: '生产工单号',
          width: 140
        },
        {
          name: 'productCode',
          label: '产品编号',
          width: 140
        },
        {
          name: 'productName',
          label: '产品名称',
          width: 140
        },
        {
          name: 'productSpc',
          label: '规格',
          width: 140
        },
        {
          name: 'requestDate',
          label: '需求日期',
          width: 140
        }
      ],
      tableDataDetail: [],
      showRowDeatilFlag: false,
      loading: false
    };
  },
  mounted() {
    //监听工作站切换事件
    uni.$on('switchWorkunit', (station) => {
      this.getTaskList();
    });
  },
  created() {
    //获取屏幕高度
    uni.getSystemInfo({
      success(res) {
        this.screenHeight = res.windowHeight;
      }
    });
    //监听工作站切换事件
    uni.$on('switchWorkunit', (station) => {
      // this.reset();
      this.getTaskList();
    });

    uni.$on('taskStatusChanged', () => {
      this.getTaskList(); //刷新任务状态
    });

    if (this.vuex_workunit != null) {
      this.getTaskList();
    }
    // if (this.vuex_task != null) {
    //   this.shiftTask(this.vuex_task.taskId);
    // }
  },
  destroyed() {
    uni.$off('switchWorkunit');
    uni.$off('taskStatusChanged');
  },
  methods: {
    handleChangeTabPro(index, row) {
      row.currentTabPro = index;
    },
    onPreviewTap(url) {
      uni.previewImage({
        current: url,
        urls: this.viewSop
      });
    },
    // cellClick(row, index, column) {
    //   if (column.name === 'arrangeCode') {
    //     this.tableDataDetail = row.proWorkorderList;
    //     this.showRowDeatilFlag = true;
    //     console.log(e)
    //     e.stopPropagation()
    //   }
    // },
    iconClickArrangeCode() {
      uni.scanCode({
        success: (res) => {
          console.log(res, 'res');
          this.getTaskList({ arrangeCode: res.result });
        },
        fail: () => {
          this.$u.toast('扫码失败，请重新扫描');
        }
      });
    },
    iconClickWorkorderCode(data) {
      uni.scanCode({
        success: (res) => {
          console.log(res, 'res');
          this.getTaskList({ workorderCode: res.result });
        },
        fail: () => {
          this.$u.toast('扫码失败，请重新扫描');
        }
      });
    },
    numclik(...arg) {
      console.log('99999999', arg);
    },
    changeWorkstation() {
      uni.$emit('changeWorkunit');
    },
    // 判断是否显示红色
    isTrClassStyle(row, i) {
      // console.log(row, i, 999)
      var oDate1 = new Date();
      var oDate2 = new Date(row.scheduleEndDate);
      if (oDate1.getTime() > oDate2.getTime()) {
        return true; //第一个大
      } else {
        return false; //第二个大
      }
    },
    commonClick(oper) {
      if (['Refresh', 'MaterialUsageRecord'].indexOf(oper) === -1 && this.tableSelectData.length === 0) {
        this.$u.toast('请选择工作任务！');
        return;
      }
      switch (oper) {
        case 'Refresh':
          this.getTaskList();
          break;
        case 'StartTask':
          let status = false;
          this.tableSelectData.forEach((item) => {
            if (item.status === 'BEGINNING') {
              status = true;
            } else {
              this.$u.api.changeCheckMachineTool({
                taskWorkunitId: item.taskWorkunitId
              });
              this.changeStatus(item.taskId, item.taskWorkunitId, 'BEGINNING', item.workunitId, false);
            }
          });
          if (status) {
            this.$u.toast('该任务已开工，请勿重复开工');
            return;
          }
          break;
        case 'StopTask':
          this.stopCause();
          this.stopReason = '';
          this.stopReasonVisible = true;
          break;
        case 'FinshTask':
          this.tableSelectData.forEach((item) => {
            this.changeStatus(item.taskId, item.taskWorkunitId, 'FINISHED', item.workunitId);
          });
          break;
        case 'Prod':
          this.doFeedback();
          break;
        case 'MaterialUsageRecord':
          this.addMaterialUsageRecord();
          break;
        case 'KnifeTemp':
          this.knifeTempShow();
          break;
        case 'abnormal':
          this.doException();
          break;
        case 'ViewPpicture':
          this.viewiPctureShow();
          break;
        case 'FeedingInspection':
          this.feedingInspectionShow();
          break;
        case 'RecoilMaterial':
          this.recoilMaterialShow();
          break;
        case 'MaterialRequest':
          this.materialRequestShow();
          break;
        case 'MaterialReturn':
          this.materialReturnShow();
          break;
        case 'jobAssignment': // 作业分派
          this.handleJobAssignment();
          break;
        case 'StockIn':
          this.stockInShow();
          break;
        default:
          this.$u.toast('功能正在开发中！');
          break;
      }
    },
    handleJobAssignment() {
      this.jobAssignmentForm = {
        quantity: 1,
        workunitName: null
      };
      this.jobAssignmentVisible = true;
    },
    handleSubmitWorkunit() {
      this.jobAssignmentForm.workunitId = this.$refs.workunitRef.tableSelectData[0].workunitId;
      this.jobAssignmentForm.workunitName = this.$refs.workunitRef.tableSelectData[0].workunitName;
    },
    handleSubmitJobAssignment() {
      let datas = Object.assign({}, this.tableSelectData[0]);
      datas.taskWorkunit = this.jobAssignmentForm;
      delete datas.proWorkorderList;
      this.$u.api.putProtaskSplit(datas).then((res) => {
        // console.log(res, 'res333')
        if (res.code === 200) {
          this.jobAssignmentVisible = false;
          this.getTaskList();
        }
      });
    },
    async knifeTempShow() {
      if (this.tableSelectData.length > 1) {
        return;
      }
      const params = {
        taskWorkunitId: this.tableSelectData[0].taskWorkunitId
        // arrangeCode: this.tableSelectData[0].arrangeCode || '',
        // processId: this.tableSelectData[0].processId,
        // workunitId: this.vuex_workunit.workunitId
      };
      const records = await this.$u.api.dModel.getRecordsByProcessIdAndArrangeCode(params);
      // 如果有数据
      if (records?.data && records.data.length) {
        this.dModelData = records.data;
        this.knifeTempVisible = true;
        return;
      }
      // else {
      //   return this.$u.toast('该刀模版具不属于该工单');
      // }
      this.addDModelRecord(params);
    },
    async upDownGetList() {
      const params = {
        taskWorkunitId: this.tableSelectData[0].taskWorkunitId
        // arrangeCode: this.tableSelectData[0].arrangeCode || '',
        // processId: this.tableSelectData[0].processId
      };
      const records = await this.$u.api.dModel.getRecordsByProcessIdAndArrangeCode(params);
      this.dModelData = records.data;
    },
    // 新增刀模版上下机记录
    async addDModelRecord(params) {
      const { data } = await this.$u.api.dModel.getToolsByProcessIdAndArrangeCode(params);
      if (data?.length) {
        const [selectData] = this.tableSelectData;
        const ps = {
          toolMachinesCode: '',
          arrangeCode: selectData.arrangeCode,
          workunitId: this.vuex_workunit.workunitId,
          workunitCode: this.vuex_workunit.workunitCode,
          workunitName: this.vuex_workunit.workunitName,
          processId: selectData.processId,
          taskId: selectData.taskId,
          taskWorkunitId: selectData.taskWorkunitId,
          workorderId: selectData.workorderId,
          toolRequestUseId: data[0].toolRequestUseId,
          toolMachinesRecordList: data.map((v) => {
            return {
              toolRequestUseItemId: v.toolRequestUseItemId,
              type: 3,
              upDate: '',
              downDate: ''
            };
          })
        };
        // 新增
        const data2 = await this.$u.api.dModel.tmToolMachines(ps);
        if (data2.code == 200) {
          const records = await this.$u.api.dModel.getRecordsByProcessIdAndArrangeCode(params);
          this.dModelData = records.data || [];
          this.knifeTempVisible = true;
        }
      }
    },
    getIssusLinebyWorkorderCodes() {
      this.issusLineList = [];
      this.$u.api.getIssusLinebyWorkorderCodes({ workorderCodes: this.curTaskInfo.workorderCodes?.split(',') }).then((res) => {
        if (res.code === 200) {
          this.issusLineList = res.rows;
        }
      });
    },
    rowClick(row, index) {
      this.$refs.zbtable.toggleRowSelection(row);
      this.curTaskInfo = row;
      this.getMaterialUsageRecordList();
    },
    getCode(row) {
      this.usePersonData = row;
      this.userTempVisible = true;
    },
    toggleAllSelection(checked, arr) {
      // console.log(arr, 'this.tableSelectData');
      this.tableSelectData = arr;
    },
    toggleRowSelection(checked, arr) {
      // console.log(arr, 'this.tableSelectData');
      this.tableSelectData = arr;
    },
    knifeTemp() {
      // this.$u.toast('刀具校验通过！');
    },
    userDetermine() {
      console.log(this.$refs.userPersonnelRef.tableSelectData, 'this.$refs.userPersonnelRef.tableSelectData');
      this.usePersonData.nickName = this.$refs.userPersonnelRef.tableSelectData[0].nickName;
      this.usePersonData.userName = this.$refs.userPersonnelRef.tableSelectData[0]?.userName;
    },
    stopReasonSubmit() {
      this.tableSelectData.forEach((item) => {
        this.changeStop(item.taskId, item.taskWorkunitId, 'PAUSE', item.workunitId);
      });
      this.getTaskList();
    },
    stopReasonChange(e) {
      this.stopReason += e;
    },
    workorderSelect(id, index) {
      console.log(id, '9999');
      const row = this.feedbackForms[index];
      if (!id) {
        row.sizeList = [];
        row.directiveList = [];
        row.workorderSoSizeItemId = '';
        row.printContents = row.arrangeCode;
        row.workorderSoDirectiveId = '';
        row.tableDirectiveData = [];
        row.tableSizeColumn = [];
        row.tableSizeData = [];
        return;
      } else {
        if (row.isLastProcess) {
          this.getWorkorderDirectiveList(id, index);
          this.getWorkorderSizeList(id, index);
        }
      }
      row.workorderId = id;
      const items = row.workorderList.find((item) => item.workorderId === id);
      row.workorderCode = items.workorderCode;
      row.printName = items.workorderCode;
      //row.printContents =row.arrangeCode+row.workorderCode
      row.printContents = row.workorderCode;
      row.sizeList = row.sizeData[id];
      row.directiveList = row.directiveData[id];
      row.packByDirective = items.packByDirective;
      row.packBySize = items.packBySize;
    },

    stopReas(abnormalType) {
      // 查询原因
      this.$u.api.abnormal
        .detail({
          pageNum: 1,
          pageSize: 10,
          abnormalType
        })
        .then((res) => {
          this.reasonList = res.rows.map((item) => {
            return {
              value: item.abnormalReason,
              text: item.abnormalReason
            };
          });
        });
    },
    stopCause() {
      // 查询原因
      this.$u.api.abnormal
        .detail({
          pageNum: 1,
          pageSize: 10,
          abnormalType: 'WORK'
        })
        .then((res) => {
          this.causeList = res.rows.map((item) => {
            return {
              value: item.abnormalReason,
              text: item.abnormalReason
            };
          });
        });
    },
    getWorkorderWithSizeAndDirective(item, index) {
      this.$u.api
        .getWorkorderWithSizeAndDirective({
          pageNum: 1,
          pageSize: 10,
          arrangeCode: item.arrangeCode
        })
        .then((res) => {
          item.workorderList = res.rows;
          //如果只关联一个订单，默认选中
          if (res.rows.length == 1) {
            item.printContents = res.rows[0].workorderCode;
            item.workorderId = res.rows[0].workorderId;
            item.workorderCode = res.rows[0].workorderCode;
            if (item.isLastProcess) {
              this.getWorkorderDirectiveList(res.rows[0].workorderId, index);
              this.getWorkorderSizeList(res.rows[0].workorderId, index);
            }
            if (res.rows[0].sizeList2 != null) {
              item.sizeList = res.rows[0].sizeList2.map((temp2) => {
                return {
                  value: temp2.workorderSoSizeItemId,
                  text: temp2.standardSize
                };
              });
            }
            if (res.rows[0].saleDirectiveList != null) {
              item.directiveList = res.rows[0].saleDirectiveList.map((temp2) => {
                return {
                  value: temp2.workorderSoDirectiveId,
                  text: temp2.clientCmd
                };
              });
            }
            item.packByDirective = res.rows[0].packByDirective;
            item.packBySize = res.rows[0].packBySize;
          }
          item.workorderOption = res.rows.map((temp) => {
            if (temp.saleDirectiveList != null) {
              item.directiveData[temp.workorderId] = temp.saleDirectiveList.map((temp2) => {
                return {
                  value: temp2.workorderSoDirectiveId,
                  text: temp2.clientCmd
                };
              });
            }
            if (temp.sizeList2 != null) {
              item.sizeData[temp.workorderId] = temp.sizeList2.map((temp2) => {
                return {
                  value: temp2.workorderSoSizeItemId,
                  text: temp2.standardSize
                };
              });
            }
            return {
              value: temp.workorderId,
              text: temp.workorderCode
            };
          });
        });
    },

    getTaskList(params) {
      this.form = {};
      const t = this;
      this.tableData = [];
      this.$u.api
        .getTaskList({
          workunitId: t.vuex_workunit.workunitId,
          ...this.tableParams,
          ...params
        })
        .then((res) => {
          if (res.code === 200) {
            // 过滤可加工数量为0的数据
            this.tableData = res.rows.map((item) => {
              return {
                ...item,
                scheduleStartDateStr: item.scheduleStartDate.substring(2, 16),
                scheduleEndDateStr: item.scheduleEndDate.substring(2, 16)
              };
            });
            if (this.tableData.length > 0) {
              this.curTaskInfo = this.tableData[0];
              this.getMaterialUsageRecordList();
            } else {
            }
          }
        });
    },
    typeChange(index) {
      this.currentType = index;
      this.getMaterialUsageRecordList();
    },
    getMaterialUsageRecordList() {
      this.materialusagerecordLoading = true;
      this.$u.api
        .materialusagerecordList({
          workstationId: this.vuex_workstation?.workstationId,
          depletionMethod: this.currentType + 1,
          taskId: this.curTaskInfo.taskId
        })
        .then((res) => {
          this.materialusagerecordLoading = false;
          if (res.code === 200) {
            this.materialUsageRecordList = res.rows;
          }
        });
    },
    addMaterialUsageRecord() {
      if (this.materialRecordInfo.materialBatchNumber !== this.curTaskInfo.itemCode && this.currentType === 0) {
        this.$u.toast('物料不在生产目录中！');
        return;
      }
      if (this.materialRecordInfo.quantity === 0) {
        this.$u.toast('请输入物料数量！');
        return;
      }
      this.materialRecordInfo.operatorTime = new Date();
      this.materialRecordInfo.operatorId = this.vuex_user.userId;
      this.materialRecordInfo.operatorName = this.vuex_user.userName;
      this.materialRecordInfo.taskId = this.curTaskInfo.taskId;
      this.materialRecordInfo.depletionMethod = this.currentType + 1;
      this.materialRecordInfo.workstationId = this.vuex_workstation.workstationId;
      this.$u.api.addMaterialusagerecord(this.materialRecordInfo).then((res) => {
        if (res.code === 200) {
          this.materialRecordInfo.quantity = 0;
          this.materialRecordInfo.materialBatchNumber = '';
          this.$u.toast('上报成功');
          this.getMaterialUsageRecordList();
        }
      });
    },
    shiftTask(tid) {
      this.$u.api
        .getTaskInfo({
          taskId: tid
        })
        .then((res) => {
          if (res.code === 200) {
            this.form = res.data;
            this.$u.vuex('vuex_task', res.data);
            this.form.progress = Math.round((this.form.quantityProduced / this.form.quantity) * 100, 0);
          }
        });
    },
    changeStatus(taskId, taskWorkunitId, status, workunitId, showToast) {
      // this.form.status = status;
      this.$u.api
        .changeStatus({
          taskId: taskId,
          status: status,
          taskWorkunitId: taskWorkunitId,
          workunitId: workunitId,
          attr1: this.stopReason
        })
        .then((res) => {
          if (res.code === 200) {
            let showToastData = showToast === false ? false : true;
            if (showToastData) {
              this.$u.toast('变更成功');
            }
            this.getTaskList();
          }
        });
    },
    //暂停作业
    changeStop(taskId, taskWorkunitId, status, workunitId) {
      // this.form.status = status;
      this.$u.api
        .changeStatus({
          taskId: taskId,
          status: status,
          taskWorkunitId: taskWorkunitId,
          workunitId: workunitId,
          attr1: this.stopReasonForm.reason,
          attr2: this.stopReasonForm.desc
        })
        .then((res) => {
          if (res.code === 200) {
            this.$u.toast('变更成功');
            this.getTaskList();
          }
        });
    },
    // reset() {
    //   this.feedbackForm = {
    //     workstationId: 0,
    //     userName: this.vuex_user.userName,
    //     taskId: this.form.taskId,
    //     feedbackChannel: 'PAD',
    //     quantity: 0,
    //     quantityQualify: 0,
    //     quantityUnqualify: 0
    //   }
    // },
    quantityChanged() {
      this.feedbackForm.quantity = this.feedbackForm.quantityQualify + this.feedbackForm.quantityUnqualify;
    },
    getPrintTemplate(row) {
      this.printTemplateData = row;
      this.printTemplateVisible = true;
    },
    handleSubmitPrintTemplate() {
      this.printTemplateData.printTemplate = this.$refs.printTemplateRef.tableSelectData[0].name;
      this.printTemplateVisible = false;
    },
    doFeedback() {
      // this.reset();
      this.feedbackForms = [];
      this.tableSelectData.forEach((item, index) => {
        let defQualify = item.quantity - item.quantityQualify - item.quantityUnqualify;
        defQualify = defQualify < 0 ? 0 : defQualify;
        defQualify = defQualify > item.quantityWait ? item.quantityWait : defQualify;
        const feedback = {
          ...item,
          workstationId: item.workstationId,
          userName: this.vuex_user.userName,
          taskId: item.taskId,
          taskWorkunitId: item.taskWorkunitId,
          feedbackChannel: 'PAD',
          quantity: item.quantity,
          quantityQualify: Number(defQualify), //默认为排产数量-合格数-不合格数
          quantityUnqualify: 0,
          printName: '',
          lastProcess: item.isLastProcess == 1, //未工序
          nickName: this.vuex_user.nickName,
          workorderId: 0,
          workorderCode: null,
          workorderSoDirectiveId: '',
          workorderSoSizeItemId: '',
          netWeight: 0,
          minPackageNum: 0,
          workorderList: [],
          workorderOption: [],
          directiveList: [],
          sizeList: [],
          directiveData: {},
          sizeData: {},
          printContents: item.arrangeCode,
          whether: '',
          printTemplate: '',
          tableDirectiveColumn: [
            {
              name: 'clientCmd',
              label: '指令号',
              width: 130
            },
            {
              name: 'lossNum',
              label: 'LOSS数',
              width: 130
            },
            {
              name: 'sizeGroup',
              label: '尺码组',
              width: 130
            },
            {
              name: 'quantity',
              label: '数量',
              width: 130
            },
            {
              name: 'quantityQualify',
              label: '合格品数量',
              width: 130
            }
          ],
          tableDirectiveData: [],
          tableSizeColumn: [],
          tableSizeData: [],
          currentTabPro: 0
        };
        this.getWorkorderWithSizeAndDirective(feedback, index);
        this.feedbackForms.push(feedback);
      });
      this.proVisible = true;
    },
    // 获取指令列表
    getWorkorderDirectiveList(id, index) {
      let row = this.feedbackForms[index];
      this.$u.api
        .workOrderSoDirectiveApi({
          workorderId: id
        })
        .then((res) => {
          console.log(res, '88999res');
          if (res.code === 200) {
            row.tableDirectiveData = res.rows;
          }
          //  row.tableDirectiveData = []
          //   row.tableSizeColumn = []
          //   row.tableSizeData = []
        });
    },
    // 获取SIZE列表
    getWorkorderSizeList(id, index) {
      let row = this.feedbackForms[index];
      this.$u.api
        .workOrderSoSizeItemApi({
          workorderId: id
        })
        .then((res) => {
          console.log(res, '88999resSize');
          let columns = [];
          if (res.code === 200) {
            for (const key in res.data.columns) {
              if (res.data.columns.hasOwnProperty.call(res.data.columns, key)) {
                const element = res.data.columns[key];
                let obj = {
                  name: key,
                  label: element
                };
                columns.push(obj);
              }
            }
            row.tableSizeColumn = columns;
            row.tableSizeData = res.data.sizeList;
          }
        });
    },

    doException() {
      this.ExceptionForms = {
        abnormalType: null,
        abnormalReason: null
      };
      const item = this.tableSelectData[0];
      Object.assign(this.ExceptionForms, {
        ...item,
        batchNumber: item.arrangeCode,
        processId: item.processId,
        processCode: item.processCode,
        processName: item.processName,
        workstationId: this.vuex_workunit.workunitId,
        workstationCode: this.vuex_workunit.workunitCode,
        workstationName: this.vuex_workunit.workunitName,
        abnormalType: '',
        abnormalReason: '',
        abnormalTime: ''
      });
      this.errorVisible = true;
    },

    async newlyAddss() {
      const res = await this.$u.api.abnormal.newlyAdd(this.ExceptionForms);
      this.$u.toast('上报成功');
      this.getTaskList();
    },
    cancel() {
      this.proVisible = false;
    },
    handleSubmitfeedback() {
      this.proVisible = true;
      this.feedbackForms.forEach((item) => {
        if (item.quantityQualify === 0 && item.quantityUnqualify === 0) {
          this.$u.toast('请填写合格/不合格产品数量！');
          return;
        }
        if (item.lastProcess) {
          //最后工序
          if (item.packByDirective == 'Y' && !item.workorderSoDirectiveId) {
            this.$u.toast('订单按指令包装，指令码必选！');
            return;
          } else if (item.packBySize == 'Y' && !item.workorderSoSizeItemId) {
            this.$u.toast('订单按SIZE包装，SIZE必选！');
            return;
          }
        }
        console.log(this.vuex_printConnect, 'this.vuex_printConnect');
        if ((item.printTemplate || item.whether == '1') && !this.vuex_printConnect) {
          this.$u.toast('打印机连接失败');
          return;
        }
        //工单
        this.$u.api
          .feedback({
            taskWorkunitId: item.taskWorkunitId,
            taskId: item.taskId,
            taskCode: item.taskCode,
            quantityFeedback: item.quantityQualify + item.quantityUnqualify,
            quantityQualify: item.quantityQualify,
            quantityUnqualify: item.quantityUnqualify,
            userName: item.userName || this.vuex_user.userName,
            feedbackType: item.feedbackType,
            routeId: item.routeId,
            routeCode: item.routeCode,
            processId: item.processId,
            processCode: item.processCode,
            processName: item.processName,
            itemId: item.itemId,
            itemCode: item.itemCode,
            itemName: item.itemName,
            workstationId: item.workstationId,
            workstationCode: item.workstationCode,
            workorderId: item.workorderId,
            workorderCode: item.workorderCode,
            workstationName: item.workstationName,
            startTime: item.scheduleStartDate,
            printTemplate: item.printTemplate,
            workorderSoDirectiveId: item.workorderSoDirectiveId,
            workorderSoSizeItemId: item.workorderSoSizeItemId,
            netWeight: item.netWeight,
            minPackageNum: item.minPackageNum,
            printContents: item.whether == '1' ? item.printContents : null
          })
          .then((res) => {
            if (res.code === 200) {
              this.proVisible = false;
              if (item.printTemplate) {
                let params = {};
                res.data.forEach((datas) => {
                  params = {
                    reportName: 'mysql:' + item.printTemplate,
                    values: {
                      proWorkorder: datas.proWorkorder,
                      size: datas.size,
                      directive: datas.directive
                    }
                  };
                  datas.packagePrintList.forEach((v) => {
                    params.values.packagePrint = v;
                    this.printPdfSocket(params);
                  });
                });
              }
              if (item.whether == '1') {
                this.printPdfSocket({
                  reportName: 'mysql:qrcode-50*50-2',
                  values: {
                    detail: [
                      {
                        barcode: item.printContents,
                        gp: item.printContents
                      }
                    ]
                  }
                });
              }
              if (!res.msg) {
                this.$u.toast('上报成功');
              } else {
                this.$u.toast(res.msg);
              }
              this.getTaskList();
            }
          });
      });
    },
    feedingInspectionShow() {
      this.feedingInspectionVisible = true;
      this.feedingInspectionLoadAndScan();
    },
    feedingInspectionLoadAndScan(bool) {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      this.$u.api.listFeedingInspection({ taskId: taskInfo.taskId }).then((res) => {
        if (res.code === 200) {
          t.feedingInspectionList = res.data;
          if (bool) {
            t.$u.toast('保存成功');
          }
          let timer = setTimeout(() => {
            t.feedingInspectionScan();
          }, 1000);
        }
      });
    },
    feedingInspectionScan() {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      uni.scanCode({
        success: function (res) {
          t.$u.api.validateFeedingInspection({ plnr: res.result, taskId: taskInfo.taskId }).then((res2) => {
            if (res2.code === 200) {
              t.feedingInspectionLoadAndScan(true);
            }
          });
        }
      });
      this.feedingInspectionVisible = true;
    },
    validateFeedingInspection(line) {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      this.$u.api.validateFeedingInspectionById({ lineId: line.lineId }).then((res2) => {
        if (res2.code === 200) {
          t.$u.api.listFeedingInspection({ taskId: taskInfo.taskId }).then((res) => {
            if (res.code === 200) {
              t.feedingInspectionList = res.data;
            }
          });
        }
      });
    },
    recoilMaterialShow() {
      this.recoilMaterialVisible = true;
      this.recoilMaterialLoadAndScan();
    },
    recoilMaterialLoadAndScan(bool) {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      this.$u.api.recoilMaterialList({ taskId: taskInfo.taskId }).then((res) => {
        if (res.code === 200) {
          t.recoilMaterialList = res.data;
          if (bool) {
            t.$u.toast('保存成功');
          }
          let timer = setTimeout(() => {
            t.recoilMaterialScan();
          }, 1000);
        }
      });
    },
    recoilMaterialScan() {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      uni.scanCode({
        success: function (res) {
          t.$u.api.addRecoilMaterial({ taskId: taskInfo.taskId, plnr: res.result }).then((res2) => {
            if (res2.code === 200) {
              t.recoilMaterialLoadAndScan(true);
            }
          });
        }
      });
      this.recoilMaterialVisible = true;
    },
    recoilMaterialDelete(line) {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      this.$u.api.deleteRecoilMaterial({ id: line.recoilMaterialId }).then((res2) => {
        t.$u.api.recoilMaterialList({ taskId: taskInfo.taskId }).then((res) => {
          if (res.code === 200) {
            t.recoilMaterialList = res.data;
          }
        });
      });
    },
    materialRequestShow() {
      this.materialRequestVisible = true;
      const taskInfo = this.tableSelectData[0];
      this.curTaskInfo = this.tableSelectData[0];
      this.curTaskInfo.workorderOption = this.curTaskInfo.proWorkorderList.map((s) => {
        return { value: s.workorderId, text: s.workorderCode };
      });
      this.$u.api.listMaterialRequest({ taskId: taskInfo.taskId }).then((res) => {
        if (res.code === 200) {
          this.materialRequestList = res.data;
          this.materialRequestArrays = this.materialRequestList.concat([]);
        }
      });
    },
    materialRequestFormShow(line) {
      this.materialRequestFormVisible = true;
      this.materialRequestFormData = { itemName: line.itemName, applyNum: 1 };
      this.materialRequestSelected = line;
    },
    materialRequestSetting() {
      this.materialRequestSelected.applyNum = this.materialRequestFormData.applyNum;
      this.materialRequestFormVisible = false;
    },
    materialRequestSave() {
      const rst = [];
      const taskInfo = this.tableSelectData[0];
      const t = this;
      const items = this.curTaskInfo.workorderOption.find((item) => item.text === this.curTaskInfo.workorderCode);
      console.log(this.curTaskInfo.workorderOption, this.curTaskInfo.workorderCode, items);
      this.materialRequestArrays.forEach((s) => {
        if (s.applyNum != null) {
          rst.push({
            itemId: s.itemId,
            taskWorkunitId: this.curTaskInfo.taskWorkunitId,
            workorderCode: items?.text,
            taskId: taskInfo.taskId,
            applyNum: s.applyNum,
            applyType: 1
          });
        }
      });
      this.$u.api.addMaterialRequest(rst).then((res) => {
        t.materialRequestFormVisible = false;
        if (res.code === 200) {
          t.$u.toast('保存成功');
        }
      });
    },
    materialReturnShow() {
      const t = this;
      this.materialReturnVisible = true;
      const taskInfo = this.tableSelectData[0];
      this.curTaskInfo = this.tableSelectData[0];
      this.curTaskInfo.workorderOption = this.curTaskInfo.proWorkorderList.map((s) => {
        return { value: s.workorderCode, text: s.workorderCode };
      });
      this.$u.api.listMaterialReturn({ taskId: taskInfo.taskId, workorderCode: '' }).then((res) => {
        if (res.code === 200) {
          t.materialReturnList = res.data;
        }
      });
    },
    viewiPctureShow() {
      this.materialReturn = true;
      // this.viewSopPicture = this.tableSelectData[0];
      const taskInfo = this.tableSelectData[0];
      this.curTaskInfo = this.tableSelectData[0];
      this.$u.api.viewpicture.viewWorkorder({ taskId: this.curTaskInfo.taskId }).then((res) => {
        if (res.code === 200) {
          this.viewSopPicture = res.data;
        }
      });
    },
    materialReturnWorkorderChange(s) {
      const t = this;
      const taskInfo = this.tableSelectData[0];
      this.$u.api.listMaterialReturn({ taskId: taskInfo.taskId, workorderCode: s }).then((res) => {
        if (res.code === 200) {
          t.materialReturnList = res.data;
        }
      });
    },
    materialReturnWorkorderProcessItem(id) {
      if (!id) {
        this.materialRequestArrays = this.materialRequestList.concat([]);
      } else {
        this.$u.api.getWproworkOrderProcessItem({ workorderId: id, processId: this.curTaskInfo.processId }).then((res) => {
          if (res.code === 200) {
            this.materialRequestArrays = this.materialRequestList.concat(res.rows);
          }
        });
      }
    },

    materialReturnFormShow(line) {
      this.materialReturnFormVisible = true;
      this.materialReturnFormData = {
        itemName: line.itemName,
        applyNum: 1,
        workorderCode: this.materialReturnFormData.workorderCode,
        isQualified: 1
      };
      this.materialReturnSelected = line;
    },
    viewSopsShow(row) {
      this.material = true;
      // this.viewSopPicture = this.tableSelectData[0];
      this.$u.api.viewpicture.viewSop({ workorderId: Number(row.workorderId) }).then((res) => {
        if (res.code === 200) {
          console.log(res.data);
          this.viewSop = res.data;
        }
      });
    },
    materialReturnSetting() {
      this.materialReturnSelected.applyNum = this.materialReturnFormData.applyNum;
      this.materialReturnSelected.isQualified = this.materialReturnFormData.isQualified;
      this.materialReturnFormVisible = false;
    },
    materialReturnSave() {
      const taskInfo = this.tableSelectData[0];
      const rst = this.materialReturnList.map((s) => {
        let data = {
          itemId: s.itemId,
          taskId: taskInfo.taskId,
          backNum: s.applyNum,
          issueLineId: s.lineId,
          taskWorkunitId: this.curTaskInfo.taskWorkunitId,
          workOrderId: s.workorderId,
          batchNo: s.batchCode,
          packNo: s.packNo,
          isQualified: s.isQualified
        };
        if (this.materialReturnFormData.workorderCode) {
          data.workorderCode = this.materialReturnFormData.workorderCode;
        } else {
          data.workorderCode = this.curTaskInfo.workorderOption.flatMap((it) => it.value).join(',');
        }
        return data;
      });
      if (this.materialReturnList.length === 0) {
        return;
      }
      this.$u.api.addMaterialReturn(rst).then((res) => {
        this.materialReturnFormVisible = false;
        if (res.code === 200) {
          t.$u.toast('保存成功');
        }
      });
    },
    stockInShow() {
      this.stockInVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.commonBody {
  width: 100%;
  height: 100%;
  background-color: #fefeff;
  margin: 0 0;
  padding: 0 0;
}

.content {
  margin: 10px;
  display: flex;
}

.content_left {
  width: 40%;
}

.tableForm {
  display: flex;
  margin: 20rpx 0rpx;
}

.task_card {
  width: 90%;
  margin: 5px;
}

.uRow {
  margin-top: 5px;
  margin-bottom: 5px;
}

.content_right {
  width: 60%;
  padding: 10px;
}

.feedback-card {
  margin: 25rpx;
  padding: 18rpx;
  padding-bottom: 70px;
  box-sizing: border-box;
  position: relative;
  background: #ffffff;
  border-radius: 8px;
  cursor: pointer;
  transition: box-shadow 0.2s, border-color 0.2s;
  box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09);
}

::v-deep .u-form-item {
  padding: 0px;
}

.prod-body {
  //display: flex;
  height: 100%;
  //overflow: hidden;

  display: flex;
}

.prod-body-left {
  flex: 1;
  //flex-grow: 1;
  // padding: 10rpx;
  overflow: hidden;

  .prod-body-left-btns {
    height: 80rpx;

    .u-btn {
      width: 250rpx;
      height: 60rpx;
      line-height: 60rpx;
      display: inline-block;
      margin: 10rpx 20rpx;
    }

    .workstation {
      display: inline-block;
    }
  }

  .prod-body-left-task {
    height: calc(100vh - 200rpx);
    min-height: 400rpx;
    border: 1px solid rgb(232, 232, 232);
    /deep/ .item-tr.trbg .item-td {
      background: #fb9461 !important;
      // color:#fff !important;
    }
  }

  .prod-body-left-num {
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 16rpx;
    background-color: #add8e6;
  }

  .prod-body-left-bom {
    height: 500rpx;

    .prod-body-left-bom-type {
      width: 500rpx;
      height: 80rpx;
      padding-top: 10rpx;

      .u-subsection {
        border-radius: 5px 5px 0 0 !important;
      }
    }

    .prod-body-left-bom-table {
      height: 400rpx;
      border: 1px solid rgb(232, 232, 232);
    }
  }
}

.prod-body-right {
  width: 300rpx;
  padding: 10rpx;
  overflow: auto;

  .u-btn {
    height: 100rpx;
    line-height: 100rpx;
    margin: 20rpx 10rpx;
    font-size: 40rpx;
  }
}
.times {
  /deep/ .uni-date-picker__container {
    height: 360rpx;
  }
}
</style>
