<template>
  <view class="commonBody">
    <view class="prod-body">
      <view class="prod-body-left">
        <view>
          <u-form :model="tableParams" labelAlign="right" class="tableForm">
            <u-form-item
              :label="$t('扫码')"
              label-width="50px"
              name="arrangeCode"
            >
              <view class="public-input" style="width: 250px">
                <u-input
                  v-model="tableParams.arrangeCode"
                  @confirm="confirmArrange($event)"
                  :placeholder="$t('请输入生产工单号和工序任务单号')"
                />
              </view>
            </u-form-item>
            <u-form-item
              name="allowProduce"
              label-width="80px"
              :label="$t('当前可加工')"
            >
              <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"
                style="width: 50px"
                >{{ $t('搜索') }}</u-button
              >
            </u-form-item>
          </u-form>
        </view>
        <view class="prod-body-left-task">
          <zb-table
            ref="zbtable"
            :columns="tableColumn"
            :stripe="true"
            rowKey="taskWorkunitId"
            :cellStyle="cellStyle"
            :isTrClassStyle="isTrClassStyle"
            @rowClick="rowClick"
            @toggleRowSelection="toggleRowSelection"
            :border="true"
            :data="tableData"
          ></zb-table>
        </view>
        <view class="prod-body-left-num">{{
          $t('可选订单数：{0}', [tableData.length])
        }}</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="primary" @click="commonClick('Refresh')">{{
          $t('刷新')
        }}</u-button>
        <u-button
          type="success"
          @click="commonClick('StartTask')"
          v-if="!isWaiXie"
          >{{ $t('开始作业') }}</u-button
        >
        <u-button
          type="warning"
          @click="commonClick('StopTask')"
          v-if="!isWaiXie"
          >{{ $t('暂停作业') }}</u-button
        >
        <u-button type="success" @click="commonClick('Prod')">{{
          isWaiXie ? $t('外协收货') : $t('生产报工')
        }}</u-button>
        <u-button
          type="success"
          @click="commonClick('editProd')"
          v-if="!isWaiXie"
          >{{ $t('修改报工') }}</u-button
        >
        <u-button type="primary" @click="commonClick('FinshTask')">{{
          $t('完成作业')
        }}</u-button>
        <u-button
          type="primary"
          @click="commonClick('ViewPpicture')"
          v-if="!isWaiXie"
          >{{ $t('查看图纸') }}</u-button
        >
        <u-button
          type="warning"
          @click="commonClick('abnormal')"
          v-if="!isWaiXie"
          >{{ $t('异常报告') }}</u-button
        >
        <!-- <u-button type="primary" @click="commonClick('StockIn')">完工入库申请</u-button> -->
      </scroll-view>
    </view>

    <u-modal
      :title="isWaiXie ? $t('工序外协收货&报工') : $t('生产报工')"
      :async-close="true"
      @confirm="handleSubmitfeedback"
      show-cancel-button
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      :show-confirm-button="true"
      ref="uModal"
      :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"
          >
            <view>
              <u-form
                label-width="100px"
                :model="feedback"
                :rules="rules"
                labelAlign="right"
              >
                <template v-if="isWaiXie">
                  <u-row>
                    <u-col span="6">
                      <u-form-item :label="$t('生产工单:')" prop="quantity">
                        {{ feedback.workorderCode }}
                      </u-form-item>
                    </u-col>
                    <u-col span="6">
                      <u-form-item :label="$t('工序:')" prop="processName">
                        {{ feedback.processName }}
                      </u-form-item>
                    </u-col>
                  </u-row>
                  <u-row>
                    <u-col span="6">
                      <u-form-item :label="$t('已收货数:')" prop="quantity">
                        {{ feedback.quantityFeedback }}
                      </u-form-item>
                    </u-col>
                    <u-col span="6">
                      <u-form-item :label="$t('未收货数:')" prop="unquantityFeedback">
                        {{ feedback.unquantityFeedback }}
                      </u-form-item>
                    </u-col>
                  </u-row>
                  <u-row>
                    <u-col span="6">
                      <u-form-item :label="$t('产品料号:')" prop="quantity">
                        {{ feedback.productCode }}
                      </u-form-item>
                    </u-col>
                    <u-col span="6">
                      <u-form-item :label="$t('产品名称:')" prop="productName">
                        {{ feedback.productName }}
                      </u-form-item>
                    </u-col>
                  </u-row>
                </template>
                <template v-else>
                  <u-row>
                    <u-col span="6">
                      <u-form-item :label="$t('任务单号:')" prop="quantity">
                        {{ feedback.taskCode }}
                      </u-form-item>
                    </u-col>
                    <u-col span="6">
                      <u-form-item :label="$t('工序:')" prop="processName">
                        {{ feedback.processName }}
                      </u-form-item>
                    </u-col>
                  </u-row>
                  <u-row>
                    <u-col :span="6">
                      <u-form-item :label="$t('已报工数:')" prop="quantity">
                        <span :style="{ padding: '0 5px' }">{{
                          feedback.workorderFeedbackSum
                        }}</span>
                        <!-- {{ computedQuantityV2 }} -->
                      </u-form-item>
                    </u-col>
                    <u-col :span="6">
                      <u-form-item :label="$t('未报工数:')">
                        {{ feedback.workorderUnfeedbackSum }}

                        <!-- {{ computedQuantityV2 }} -->
                      </u-form-item>
                    </u-col>
                  </u-row>

                  <u-row>
                    <u-col :span="6">
                      <u-form-item :label="$t('生产工单:')" prop="workorderId">
                        {{ feedback.arrangeCode }}
                      </u-form-item>
                    </u-col>
                    <u-col
                      :span="6"
                      v-if="
                        feedback.isSerialReport &&
                        Number(feedback.isSerialReport) === 1
                      "
                    >
                      <u-form-item :label="$t('序列号:')" name="qrcode">
                        <view class="public-input" style="width: 100%">
                          <u-input
                            v-model="feedback.qrcode"
                            :focus="isFocus"
                            @blur="onQrcodechange($event)"
                            @confirm="onQrcodechange($event)"
                            :placeholder="$t('请输入序列号')"
                          />
                        </view>
                      </u-form-item>
                    </u-col>
                  </u-row>
                  <u-row
                    v-if="
                      feedback.isSerialReport &&
                      Number(feedback.isSerialReport) === 1
                    "
                  >
                    <u-col :span="6">
                      <u-form-item :label="$t('备注:')" name="qrcode">
                        <uni-easyinput
                          type="text"
                          v-model="feedback.remark"
                          style="width: 200px"
                          :placeholder="$t('请输入备注')"
                        />
                      </u-form-item>
                    </u-col>
                  </u-row>
                </template>
                <u-row>
                  <u-col span="6">
                    <u-form-item
                      :label="$t('合格数量:')"
                      prop="quantityQualify"
                    >
                      <u-number-box
                        :min="0"
                        :max="getFeedbackMax(feedback)"
                        :input-width="190"
                        v-model="feedback.quantityQualify"
                        :long-press="false"
                      ></u-number-box>
                    </u-form-item>
                  </u-col>
                  <u-col span="6">
                    <u-form-item
                      :label="$t('不良品数量:')"
                      prop="quantityUnqualify"
                    >
                      <u-number-box
                        :min="0"
                        :max="getquantityQualifyMax(feedback)"
                        @change="changeUnqualify(feedback)"
                        :input-width="190"
                        v-model="feedback.quantityUnqualify"
                        :long-press="false"
                      ></u-number-box>
                    </u-form-item>
                  </u-col>
                  <u-col span="6">
                    <u-form-item :label="$t('报工时间:')" prop="feedbackTime">
                      <uni-datetime-picker
                        return-type="string"
                        class="times"
                        type="datetime"
                        :clear-icon="false"
                        v-model="feedback.feedbackTime"
                      />
                    </u-form-item>
                  </u-col>
                  <u-col span="6">
                    <u-form-item :label="$t('不合格原因') + ':'" prop="abnormalReason">
                      <u-input v-model="feedback.abnormalReason" disabled></u-input>
                      <u-button
                        @tap="chooseReason(feedback)"
                        :disabled="!feedback.quantityUnqualify || Number(feedback.quantityUnqualify) === 0"
                        type="success"
                        size="mini"
                        >{{ $t('选择原因') }}</u-button
                      >
                    </u-form-item>
                  </u-col>
                  <u-col :span="6">
                    <u-form-item :label="$t('报工人:')" prop="chooseName">
                      <view>
                        <u-tag :text="item.nickName" class="mytag" bg-color="#2972f4" color="#fff" closeable @close="tagClick" v-for="(item, index) in userList" :key="index" />
                      </view>
                      <u-input v-model="feedback.chooseName" :focus="isFocusUser" @confirm="onUserConfirm($event)"></u-input>
                      <u-button
                        @tap="getCode(feedback)"
                        type="success"
                        size="mini"
                        >{{ $t('选择人员') }}</u-button
                      >
                    </u-form-item>
                  </u-col>
                  <u-col span="6" v-if="isWaiXie">
                    <u-form-item :label="$t('是否关单:')" prop="whether">
                      <view class="uni-list-item__extra">
                        <u-radio-group v-model="feedback.closeType">
                          <u-radio :name="1">{{ $t('是') }}</u-radio>
                          <u-radio :name="0">{{ $t('否') }}</u-radio>
                        </u-radio-group>
                      </view>
                    </u-form-item>
                  </u-col>
                </u-row>
              </u-form>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-modal>
    <u-modal
      :title="$t('选择人员')"
      @confirm="chooseUser()"
      show-cancel-button
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      :title-style="{
        'background-color': '#1E3770',
        color: '#FFFFFF',
        'line-height': '37px',
        'padding-top': '0px',
      }"
      v-model="userVisible"
      width="1300rpx"
    >
      <view class="feedback-card">
        <user ref="userRef" v-if="userVisible" />
      </view>
    </u-modal>
    <u-modal
      :title="$t('选择打印模板')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      @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="$t('报工人员')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      @confirm="userDetermine()"
      show-cancel-button
      :title-style="{
        'background-color': '#1E3770',
        color: '#FFFFFF',
        'line-height': '37px',
        'padding-top': '0px',
      }"
      v-model="userTempVisible"
      width="1300rpx"
    >
      <view>
        <userPersonnel
          ref="userPersonnelRef"
          v-if="userTempVisible"
          :data="usePersonData"
        />
      </view>
    </u-modal>
    
    <u-modal
      :title="$t('暂停原因')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      @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="$t('暂停原因')" 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="$t('暂停描述')" 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="$t('异常报告')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      @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="$t('车间异常单编号')" prop="abnormalNumber" label-width="110px">
                <u-input v-model="ExceptionForms.abnormalNumber" disabled></u-input>
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item :label="$t('异常类型')" 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="$t('原因')" 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="$t('编排单号')" 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="$t('工序')" 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="$t('作业单元')" 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="$t('详细数据')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      :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="$t('生产工单')"
      :confirmText="$t('确认')"
      show-cancel-button
      :show-confirm-button="false"
      :cancel-text="$t('返回')"
      :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="$t('未查询到数据')"
          >
            <uni-tr>
              <uni-th width="80px" align="center">{{ $t('图纸名') }}</uni-th>
              <uni-th width="80px" align="center">{{ $t('图纸类型') }}</uni-th>
              <uni-th width="100px" align="center">{{ $t('操作') }}</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in viewSopPicture" :key="index">
              <uni-td align="center">{{ line.fileName }}</uni-td>
              <uni-td align="center">{{ line.fileType }}</uni-td>
              <uni-td align="center">
                <view class="uni-group">
                  <button
                    class="uni-button"
                    size="mini"
                    type="primary"
                    @click="viewSopsShow(line)"
                  >
                    {{ $t('查看') }}
                  </button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>
    <u-modal
      :title="$t('详情')"
      :confirmText="$t('确认')"
      show-cancel-button
      :show-confirm-button="false"
      :cancel-text="$t('返回')"
      :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> -->
          <ProogingSpecificationSheet
            v-if="material"
            :form="ProogingSpecificationSheetForm"
          >
          </ProogingSpecificationSheet>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal
      :title="$t('选择工作单元')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      @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>
    <editFeeding
      ref="editFeeding"
      v-model="editFeedingVisible"
      @chooseReason="chooseReason"
      @close="editFeedingVisible = false"
    />
    <!-- //生产报工报工人员 -->
    <u-modal
      :title="$t('不合格原因')"
      :cancelText="$t('取消')"
      :confirmText="$t('确认')"
      @confirm="abnormalReasonDetermine()"
      show-cancel-button
      :title-style="{
        'background-color': '#1E3770',
        color: '#FFFFFF',
        'line-height': '37px',
        'padding-top': '0px',
      }"
      v-model="abnormalReasonVisible"
      width="1300rpx"
    >
      <view>
        <abnormalReason
          ref="abnormalReasonRef"
          v-if="abnormalReasonVisible"
        />
      </view>
    </u-modal>
  </view>
</template>
<style scoped>
@import '/static/css/amebase.css';
</style>

<script>
import i18n from '../../../lang/index'
import config from '@/common/config.js'

import SearchInput from '@/components/ScanInput/index.vue'
import User from '@/components/User/User.vue'
import abnormalReason from './components/abnormalReason.vue'
import userPersonnel from './components/userPersonnel.vue'
import printTemplate from './components/printTemplate.vue'
import editFeeding from './components/editFeeding.vue'
import workunitList from './components/workunitList.vue'
import ProogingSpecificationSheet from './components/ProogingSpecificationSheet.vue'
import UButton from '../../../uview-ui/components/u-button/u-button.vue'
import cameraAuthMixin from '@/components/AppScan/appScanMixins.js'
import { handleError } from 'vue'
import AppScan from '../../../components/AppScan/AppScan.vue'
import URow from '../../../uview-ui/components/u-row/u-row.vue'
export default {
  name: 'ProdReport',
  dicts: ['pro_pack_type', 'sap_yes_no'],
  mixins: [cameraAuthMixin],
  components: {
    SearchInput,
    abnormalReason,
    editFeeding,
    userPersonnel,
    printTemplate,
    UButton,
    workunitList,
    AppScan,
    User,
    ProogingSpecificationSheet,
    URow,
  },
  data() {
    return {
      getWorkorderDirectiveLoading: false,
      editFeedingVisible: false,
      reasonOBJ: {},
      tableOrderColumn: [
        {
          name: 'quantity',
          label: i18n.t('派工数'),
          width: 170,
        },
        {
          name: 'feedbackQuantity',
          label: i18n.t('已包装数量'),
          width: 150,
        },
        {
          name: 'reportQuantity',
          label: i18n.t('本次报工'),
          width: 100,
          type: 'slot',
          slot: 'reportQuantity',
        },
        {
          name: 'netWeight',
          label: i18n.t('净重'),
          width: 100,
          type: 'slot',
          slot: 'netWeight',
        },
        {
          name: 'grossWeight',
          label: i18n.t('毛重'),
          width: 100,
          type: 'slot',
          slot: 'grossWeight',
        },
        {
          name: 'packageStandard',
          label: i18n.t('装箱规格'),
          width: 120,
          type: 'slot',
          slot: 'packageStandard',
        },
        {
          name: 'peration',
          label: i18n.t('操作'),
          width: 80,
          type: 'slot',
          slot: 'peration',
        },
      ],
      tableDirectiveColumn: [
        {
          name: 'clientCmd',
          label: i18n.t('指令号'),
          width: 120,
        },
        {
          name: 'quantity',
          label: i18n.t('派工数'),
          width: 70,
        },
        {
          name: 'packageNum',
          label: i18n.t('包装数'),
          width: 75,
        },
        {
          name: 'lossNum',
          label: i18n.t('LOSS数'),
          width: 80,
        },
        {
          name: 'feedbackQuantity',
          label: i18n.t('已包装数'),
          width: 80,
        },
        {
          name: 'reportQuantity',
          label: i18n.t('本次报工'),
          width: 80,
          type: 'slot',
          slot: 'reportQuantity',
        },
        {
          name: 'netWeight',
          label: i18n.t('净重'),
          width: 70,
          type: 'slot',
          slot: 'netWeight',
        },
        {
          name: 'grossWeight',
          label: i18n.t('毛重'),
          width: 70,
          type: 'slot',
          slot: 'grossWeight',
        },
        {
          name: 'packageStandard',
          label: i18n.t('装箱规格'),
          width: 130,
          type: 'slot',
          slot: 'packageStandard',
        },
        {
          name: 'peration',
          label: i18n.t('操作'),
          width: 80,
          type: 'slot',
          slot: 'peration',
        },
      ],
      userVisible: false,
      useData: {},
      ProogingSpecificationSheetForm: {},
      knifeTempAppScanVisible: false,
      knifeTempType: null,
      workunitVisible: false,
      jobAssignmentVisible: false,
      jobAssignmentForm: {
        quantity: 1,
        workunitName: null,
      },
      listTabPro: [
        {
          name: i18n.t('报工列表'),
        },
        {
          name: i18n.t('指令列表'),
        },
        {
          name: i18n.t('SIZE列表'),
        },
      ],
      tableParams: {
        allowProduce: 1,
        workorderCode: '',
        arrangeCode: '',
      },
      allowProduceLocal: [
        {
          text: i18n.t('是'),
          value: 1,
        },
        {
          text: i18n.t('否'),
          value: 0,
        },
      ],
      stopReasonForm: {
        reason: null,
        desc: null,
      },
      abnormalReasonVisible: false,
      screenHeight: 768,
      usePersonData: {},
      title: i18n.t('生产报工'),
      proVisible: false,
      errorVisible: false,
      form: {},
      feedbackForm: {},
      tableData: [],
      knifeTempCancelText: i18n.t('确认'),
      knifeTempVisible: false,
      knifeTempSearch: {
        knifeTempCode: '',
        locationCode: '',
      },
      knifeTempInfo: {
        knifeTemplateCode: '',
        knifeTemplateName: '',
        knifeTemplateSpec: '',
        locationCode: '',
        locationName: '',
        locationType: '',
        locationTypeCode: '',
        locationTypeDesc: '',
        locationTypeDescCode: '',
        locationTypeDescName: '',
        locationTypeDescNameCode: '',
        locationTypeDescNameCode2: '',
      },
      stopReasonList: [
        { value: i18n.t('中午休息吃饭。'), text: i18n.t('休息吃饭') },
        {
          value: i18n.t('刀头模具到期更换，更换期间。'),
          text: i18n.t('刀头模具到期更换'),
        },
        { value: i18n.t('没料了，正在领料'), text: i18n.t('领料加仓') },
      ],
      exception: [
        {
          value: 'PROD',
          text: i18n.t('生产异常'),
        },
        {
          value: 'QUAL',
          text: i18n.t('质量异常'),
        },
        {
          value: 'DEVI',
          text: i18n.t('设备异常'),
        },
      ],
      stopReason: '',
      stopReasonVisible: false,
      rules: {
        quantity: [
          {
            required: true,
            message: i18n.t('请输入合格品数量或者不良品数量！'),
            trigger: 'blur',
          },
        ],
      },
      typeList: [
        {
          name: i18n.t('物料扣减'),
        },
        {
          name: i18n.t('BOM外扣减'),
        },
      ],
      curTaskInfo: {
        pickingReason: null,
        returnReason: null,
      },
      bomFeeData: [],
      bomFeeColumn: [
        {
          type: 'selection',
          width: 35,
        },
        {
          name: 'taskCode',
          label: i18n.t('物料批次'),
          align: 'center',
          width: 150,
        },
        {
          name: 'status',
          label: i18n.t('ERP物料批次'),
          align: 'center',
          width: 150,
        },
        {
          name: 'materialBatchNumber',
          label: i18n.t('物料编码'),
          width: 150,
        },
        {
          name: 'taskCode',
          label: i18n.t('序列号'),
          width: 150,
        },
        {
          name: 'quantity',
          label: i18n.t('数量'),
          width: 150,
        },
        {
          name: 'itemCode',
          label: i18n.t('物料描述'),
        },
      ],
      tableColumn: [
        {
          type: 'radio',
          width: 60,
        },
        {
          name: 'arrangeCode',
          label: i18n.t('工单编号'),
          align: 'center',
          width: 180,
        },
        {
          name: 'scheduleStartDateStr',
          label: i18n.t('计划开始时间'),
          align: 'center',
          width: 140,
        },
        {
          name: 'scheduleEndDateStr',
          label: i18n.t('计划结束时间'),
          align: 'center',
          width: 140,
        },
        {
          name: 'workstationName',
          label: i18n.t('工作中心名称'),
          align: 'center',
          width: 140,
        },
        {
          name: 'workunitName',
          label: i18n.t('工作单元名称'),
          align: 'center',
          width: 140,
        },
        {
          name: 'quantity',
          label: i18n.t('任务数量'),
          align: 'center',
          width: 70,
        },
        {
          name: 'quantityWait',
          label: i18n.t('可加工数量'),
          align: 'center',
          width: 80,
        },
        {
          name: 'status',
          label: i18n.t('状态'),
          align: 'center',
          filters: {
            PREPARE: i18n.t('未开工'),
            BEGINNING: i18n.t('已开工'),
            PAUSE: i18n.t('暂停'),
            ERROR_STOP: i18n.t('异常停工'),
            FINISH: i18n.t('完工'),
          },
          width: 65,
        },
        {
          name: 'taskCode',
          label: i18n.t('任务单号'),
          align: 'center',
          width: 100,
        },
        {
          name: 'processName',
          label: i18n.t('工序'),
          align: 'center',
          width: 80,
        },
        {
          name: 'quantityQualify',
          label: i18n.t('合格数量'),
          align: 'center',
          width: 70,
        },
        {
          name: 'quantityUnqualify',
          label: i18n.t('不合格数量'),
          align: 'center',
          width: 70,
        },
      ],
      dModelData: [],
      tableSelectData: [],
      feedbackForms: [],
      feedbackQuantityFu: 0,
      feedbackUnQuantityFu: 0,

      ExceptionForms: {
        abnormalType: null,
        abnormalNumber: null,
        abnormalReason: null,
      },
      viewSopPicture: [],
      viewSop: [],
      causeList: [],
      reasonList: [],
      reasonReturnList: [],
      workorderList: [],
      materialusagerecordLoading: false,
      issusLineList: [],
      issusLineColumn: [
        {
          name: 'itemCode',
          label: i18n.t('产品物料编码'),
        },
        {
          name: 'itemName',
          label: i18n.t('产品物料名称'),
        },
        {
          name: 'specification',
          label: i18n.t('规格型号'),
        },
        {
          name: 'unitOfMeasure',
          label: i18n.t('单位'),
        },
        {
          name: 'quantityIssued',
          label: i18n.t('领料数量'),
        },
        {
          name: 'batchCode',
          label: i18n.t('批次号'),
        },
        {
          name: 'warehouseName',
          label: i18n.t('仓库名称'),
        },
        {
          name: 'locationName',
          label: i18n.t('库区名称'),
        },
        {
          name: 'areaName',
          label: i18n.t('库位名称'),
        },
      ],
      feedingInspectionVisible: false,
      recoilMaterialVisible: false,
      materialRequestVisible: false,
      materialReturnVisible: false,
      materialReturn: false,
      isFocus: false,
      isFocusUser: false,
      stockInVisible: false,
      material: false,
      feedingInspectionList: [],
      recoilMaterialDetailList: [],
      materialRequestList: [],
      materialRequestArrays: [],
      materialRequestArrayList: [],
      materialRequestArrayLists: [],
      materialRequests: [],
      materialReturnList: [],
      materialRequestFormData: {
        itemName: null,
        applyNum: null,
      },
      materialRequestFormVisible: false,
      materialRequestSelected: {},
      materialReturnFormData: {
        itemName: null,
        applyNum: 1,
        workorderCode: null,
        number: 0,
      },
      materialReturnProcessItemData: {
        itemName: null,
        itemCode: null,
        applyNum: 1,
        workorderCode: null,
      },
      applyNo: null,
      printTemplateData: null,
      printTemplateVisible: false,
      userTempVisible: false,
      materialReturnSelected: {},
      recoilMaterialColumn: [
        {
          name: 'sapItemCode',
          label: i18n.t('sap物料号'),
          width: 200,
        },
        {
          name: 'batchNo',
          label: i18n.t('批次号'),
          width: 100,
        },
        {
          name: 'packNo',
          label: i18n.t('卷号'),
          width: 100,
        },
        {
          name: 'quantity',
          label: i18n.t('数量'),
          width: 100,
        },
        {
          name: 'createTime',
          label: i18n.t('创建时间'),
          width: 100,
        },
      ],

      tableDetailColumn: [
        {
          name: 'workorderCode',
          label: i18n.t('生产工单'),
          width: 140,
        },
        {
          name: 'productCode',
          label: i18n.t('产品编号'),
          width: 140,
        },
        {
          name: 'productName',
          label: i18n.t('产品名称'),
          width: 140,
        },
        {
          name: 'quantity',
          label: i18n.t('生产订单数量'),
          width: 140,
        },
        {
          name: 'startSerial',
          label: i18n.t('开始序列码'),
          width: 140,
        },
        {
          name: 'endSerial',
          label: i18n.t('结束序列码'),
          width: 140,
        },
        {
          name: 'productSpc',
          label: i18n.t('规格'),
          width: 140,
        },
        {
          name: 'requestDate',
          label: i18n.t('需求日期'),
          width: 140,
        },
      ],
      tableDataDetail: [],
      recoilMaterialList: [],

      showRowDeatilFlag: false,
      recoilMaterialFlag: false,

      loading: false,
      copyFeedBackForms: [],
      timeTest: {
        isshow: true,
      },
      userList: []
    }
  },
  // watch() {

  // },
  mounted() {
    //监听工作中心切换事件
    // uni.$on('switchWorkunit', (station) => {
    //   this.getTaskList();
    // });
  },
  created() {
    //获取屏幕高度
    uni.getSystemInfo({
      success(res) {
        this.screenHeight = res.windowHeight
      },
    })
    // 获取所有工作单元的任务
    
    uni.$on('getTaskConfig', (station) => {
      this.getTaskList()
    })
    //监听工作中心切换事件
    uni.$on('switchWorkunit', (station) => {
      // this.reset();
      this.getTaskList()
      if (this.isWaiXie) {
        this.tableColumn = [
          {
            type: 'radio',
            width: 60,
          },
          {
            name: 'workorderCode',
            label: i18n.t('工单号'),
            align: 'center',
            width: 120,
          },
          {
            name: 'scheduleStartDateStr',
            label: i18n.t('计划开始时间'),
            align: 'center',
            width: 95,
          },
          {
            name: 'scheduleEndDateStr',
            label: i18n.t('计划结束时间'),
            align: 'center',
            width: 95,
          },
          {
            name: 'productCode',
            label: i18n.t('产品编码'),
            align: 'center',
            width: 140,
          },
          {
            name: 'quantity',
            label: i18n.t('外发数量'),
            align: 'center',
            width: 65,
          },
          {
            name: 'quantityQualify',
            label: i18n.t('已收货数量'),
            align: 'center',
            width: 75,
          },
          {
            name: 'processName',
            label: i18n.t('工序'),
            align: 'center',
            width: 120,
          },
        ]
      } else {
        this.tableColumn = [
        {
          type: 'radio',
          width: 60,
        },
        {
          name: 'arrangeCode',
          label: i18n.t('工单编号'),
          align: 'center',
          width: 180,
        },
        {
          name: 'scheduleStartDateStr',
          label: i18n.t('计划开始时间'),
          align: 'center',
          width: 140,
        },
        {
          name: 'scheduleEndDateStr',
          label: i18n.t('计划结束时间'),
          align: 'center',
          width: 140,
        },
        {
          name: 'workstationName',
          label: i18n.t('工作中心名称'),
          align: 'center',
          width: 140,
        },
        {
          name: 'workunitName',
          label: i18n.t('工作单元名称'),
          align: 'center',
          width: 140,
        },
        {
          name: 'quantity',
          label: i18n.t('任务数量'),
          align: 'center',
          width: 70,
        },
        {
          name: 'quantityWait',
          label: i18n.t('可加工数量'),
          align: 'center',
          width: 80,
        },
        {
          name: 'status',
          label: i18n.t('状态'),
          align: 'center',
          filters: {
            PREPARE: i18n.t('未开工'),
            BEGINNING: i18n.t('已开工'),
            PAUSE: i18n.t('暂停'),
            ERROR_STOP: i18n.t('异常停工'),
            FINISH: i18n.t('完工'),
          },
          width: 65,
        },
        {
          name: 'taskCode',
          label: i18n.t('任务单号'),
          align: 'center',
          width: 100,
        },
        {
          name: 'processName',
          label: i18n.t('工序'),
          align: 'center',
          width: 80,
        },
        {
          name: 'quantityQualify',
          label: i18n.t('合格数量'),
          align: 'center',
          width: 70,
        },
        {
          name: 'quantityUnqualify',
          label: i18n.t('不合格数量'),
          align: 'center',
          width: 70,
        },
      ]
        
      }
    })

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

  },
  destroyed() {
    uni.$off('switchWorkunit')
    uni.$off('getTaskConfig')
    uni.$off('taskStatusChanged')
  },
  computed: {
    isWaiXie() {
      if ((!this.vuex_workunit && this.vuex_workunitList && this.vuex_workunitList[0] && this.vuex_workunitList[0].workunitId === 1) || (this.vuex_workunit && this.vuex_workunit.workunitId === 1))
        return true
      return false
    },
    computedQuantity() {
      return (
        this.feedbackForm.quantityQualify + this.feedbackForm.quantityUnqualify
      )
    },
    computedAttr3() {
      const list = this.feedingInspectionList.filter((v) => v.attr3 == 1)
      return list.length
    },
    computedPercentage() {
      if (
        !this.feedingInspectionList ||
        this.feedingInspectionList.length === 0
      )
        return 100
      if (this.computedAttr3 === this.feedingInspectionList.length) return 100
      let per = (this.computedAttr3 / this.feedingInspectionList.length) * 100
      per = Math.round(per)
      return per
    },
  },
  methods: {
    tagClick(index) {
      this.userList.splice(index, 1)
    },
    changeUnqualify (row) {
      if (!row.quantityUnqualify || Number(row.quantityUnqualify) === 0) {
        row.abnormalReason = ''
        row.abnormalId = ''
        row.abnormalType = ''
        row.abnormalRemark = ''
      }
    },
    async onUserConfirm(item) {
      if (this.userList.find(v => v.userName === item) || this.userList.find(v => v.nickName === item)) {
        return
      }
      const res = await this.$u.api.getMdWorkunitWorkerByUserName({
        workunitId: this.feedbackForms[0].workunitId,
        userName: item
      });
      if (res.code == 200 && res.data) {
        this.userList.push(res.data)
        this.feedbackForms[0].chooseName = ''
        setTimeout(() => {
          this.feedbackForms[0].chooseName = ''
        }, 200)
      } else {
        this.$u.toast(i18n.t('查不到报工人数据'))
      }
      this.isFocusUser = true
      
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 && !this.isWaiXie) {
        return { color: '#3578ff !important' }
      }
      return ''
    },
    handleSubmitConfirmlKnifeTemp() {
      this.knifeTempVisible = true
      this.$refs.appScan.closed()
      this.knifeTempAppScanVisible = false
      this.knifeTempCancelText = i18n.t('确认')
      this.knifeTempType = null
    },
    handleSubmitCancelKnifeTemp() {
      this.knifeTempVisible = true
      if (this.$refs.appScan) {
        this.$refs.appScan.closed()
      }
      this.knifeTempAppScanVisible = false
      this.knifeTempCancelText = i18n.t('取消')
    },
    handleAppScanKnifeTemp(type) {
      this.knifeTempAppScanVisible = true
      this.knifeTempType = type
      this.knifeTempCancelText =
        type === '1' ? '关闭上机扫描' : i18n.t('关闭下机扫描')
      this.getPemissionScan()
    },
    handleUpdateKnifeTemp(code) {
      if (this.knifeTempType === '1') {
        if (this.tableSelectData[0].isExistTool === '1') {
          const [wlbm] = code.split('-')
          const item = this.dModelData.find((v) => v.sapItemCode === wlbm)
          if (item) {
            if (item.typeName === i18n.t('已上机')) {
              this.$u.toast(i18n.t('已上机，重复扫码'))
            } else {
              this.confirmKnifeTemp(code)
            }
          } else {
            this.$u.api.dModel
              .checkIsExsitToolWindow({
                type: this.knifeTempType,
                sn: code,
                taskWorkunitId: this.tableSelectData[0].taskWorkunitId,
              })
              .then((res) => {
                if (res.code === 200) {
                  if (res.data) {
                    uni.showModal({
                      title: i18n.t('系统提示'),
                      content: i18n.t('是否新增刀模版和产品工序的关联?'),
                      success: (res) => {
                        if (res.confirm) {
                          this.confirmKnifeTemp(code)
                        } else {
                          this.$u.toast(i18n.t('刀模版SN不一致'))
                        }
                      },
                    })
                  } else {
                    this.confirmKnifeTemp(code)
                  }
                } else {
                  this.$u.toast(res.msg)
                }
              })
          }
        } else {
          this.confirmKnifeTemp(code)
        }
      } else {
        this.confirmKnifeTemp(code)
      }
    },
    confirmKnifeTemp(code) {
      const params = {
        type: this.knifeTempType,
        sn: code,
        taskWorkunitId: this.tableSelectData[0].taskWorkunitId,
      }
      if (this.knifeTempType === '1') {
        params['isExistTool'] = this.tableSelectData[0].isExistTool
      }
      this.$u.api.dModel.tmToolMachinesScancode(params).then((res) => {
        console.log(res, 'res333')
        if (res.code === 200) {
          this.$u.toast(
            this.knifeTempType === '1' ? '上机成功' : i18n.t('下机成功')
          )
          this.upDownGetList()
        }
      })
    },
    handleChangeTabPro(index, row) {
      row.currentTabPro = index
    },
    onPreviewTap(url) {
      uni.previewImage({
        current: url,
        urls: this.viewSop,
      })
    },
    getfeedbackQuantity(row, index) {
      if (row.isEncase) {
        return i18n.t('打印')
      } else if (row.feedbackQuantity && Number(row.feedbackQuantity) > 0) {
        return i18n.t('补打印')
      } else {
        return i18n.t('打印/报工')
      }
    },
    // cellClick(row, index, column) {
    //   if (column.name === 'arrangeCode') {
    //     this.tableDataDetail = row.proWorkorderList;
    //     this.showRowDeatilFlag = true;
    //     console.log(e)
    //     e.stopPropagation()
    //   }
    // },
    iconPackageStandard(row) {
      uni.scanCode({
        success: (res) => {
          // console.log(res, 'res');
          if (res.result.indexOf('-') > -1) {
            const [packageStandard, boxWeight] = res.result.split('-')
            row.packageStandard = packageStandard
            row.boxWeight = boxWeight
          } else {
            this.$u.toast(i18n.t('扫码失败，请重新扫描'))
          }
        },
        fail: () => {
          this.$u.toast(i18n.t('扫码失败，请重新扫描'))
        },
      })
    },
    onQrcodechange(val) {
      console.log('val', val)
      this.feedbackForms[0]['qrcode'] = val
      if (!val) return
      const datas = Object.assign({}, this.feedbackForms[0])
      this.$u.api
        .validateSerialNo({
          qrcode: datas.qrcode,
          taskId: datas.taskId,
          taskWorkunitId: datas.taskWorkunitId,
        })
        .then((res) => {
          if (res.code === 200) {
            this.feedbackForms[0]['feedbackTime'] = this.parseTime(new Date())
          } else {
            this.feedbackForms[0]['qrcode'] = ''
            this.$u.toast(res.msg || i18n.t('序列号扫描报错'))
          }
        })
    },
    getFeedbackMax(feedback){
      if (feedback.isSerialReport && Number(feedback.isSerialReport) === 1 && !this.isWaiXie) {
        return 1
      } else if (this.isWaiXie || (feedback.surpassState && feedback.ordinal === 1)){ 
        return 9999999999999999999999999999999999999999
      } else {
        return feedback.workorderUnfeedbackSum - feedback.quantityUnqualify
      }
    },
    getquantityQualifyMax(feedback){
      if (feedback.isSerialReport && Number(feedback.isSerialReport) === 1 && !this.isWaiXie) {
        return 1
      } else if (this.isWaiXie || (feedback.surpassState && feedback.ordinal === 1)){ 
        return 9999999999999999999999999999999999999999
      } else {
        return feedback.workorderUnfeedbackSum - feedback.quantityQualify
      }
    },
    changeWorkstation() {
      uni.$emit('changeWorkunit')
    },
    // 判断是否显示红色
    isTrClassStyle(row, i) {
      // console.log(row, i, 999)
      const index = this.tableSelectData.findIndex(
        (v) => v.taskWorkunitId === row.taskWorkunitId
      )
      if (index > -1) {
        return 'selectrow'
      }
      if (row.status === 'PAUSE') {
        return 'yellow' //暂停
      } else if (row.status === 'BEGINNING') {
        return 'green' //已开工
      } else if (row.status === 'ERROR_STOP') {
        return 'red' //异常停工
      } else {
        return '' //第二个大
      }
    },
    // 判断是否显示蓝色
    isSizeClassStyle(row, list) {
      const item = list.find(
        (v) =>
          v.qrcode === row.qrcode && v.distributes && v.distributes.length > 0
      )
      if (item && item.feedbackQuantity > 0 && row.highlight) {
        return 'grablue' //已报工
      } else {
        return '' //第二个大
      }
    },
    commonClick(oper) {
      if (
        ['Refresh', 'editProd'].indexOf(oper) === -1 &&
        this.tableSelectData.length === 0
      ) {
        this.$u.toast(i18n.t('请选择工作任务！'))
        return
      }
      switch (oper) {
        case 'Refresh':
          this.getTaskList()
          break
        case 'StartTask':
          let status = false
          if (this.tableSelectData.length > 1) {
            this.$u.toast(i18n.t('不允许同时操作多条任务'))
            return
          }
          this.tableSelectData.forEach((item) => {
            if (item.status === 'BEGINNING') {
              status = true
            } else {
              this.$u.api
                .changeCheckMachineTool({
                  taskWorkunitId: item.taskWorkunitId,
                })
                .then((res) => {
                  if (res.code === 200) {
                    this.changeStatus(
                      item.taskId,
                      item.taskWorkunitId,
                      'BEGINNING',
                      item.workunitId,
                      false
                    )
                  }
                })
            }
          })
          if (status) {
            this.$u.toast(i18n.t('该任务已开工，请勿重复开工'))
            return
          }
          break
        case 'StopTask':
          this.stopCause()
          this.stopReason = ''
          if (this.tableSelectData.length > 1) {
            this.$u.toast(i18n.t('不允许同时操作多条任务'))
            return
          }
          this.stopReasonVisible = true
          break
        case 'FinshTask':
          if (this.tableSelectData.length > 1) {
            this.$u.toast(i18n.t('不允许同时操作多条任务'))
            return
          }
          this.tableSelectData.forEach((item) => {
            this.changeStatus(
              item.taskId,
              item.taskWorkunitId,
              'FINISHED',
              item.workunitId
            )
          })
          break
        case 'Prod':
          if (this.tableSelectData.length > 1) {
            this.$u.toast(i18n.t('不允许同时操作多条任务'))
            return
          }
          if (this.tableSelectData[0].status === 'PREPARE') {
            this.$u.toast(i18n.t('工序未开工'))
            return
          }

          this.doFeedback()
          break
        case 'editProd':
          this.doEditProd()
          break
        case 'KnifeTemp':
          this.knifeTempShow()
          break
        case 'KnifeTemp2':
          this.changeShow()
          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()
          this.pickingCause()
          break
        case 'StockIn':
          this.stockInShow()
          break
        default:
          this.$u.toast(i18n.t('功能正在开发中！'))
          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
    },
    doEditProd() {
      if (this.tableSelectData.length > 1) {
        this.$u.toast(i18n.t('不允许同时操作多条任务'))
        return
      }
      const datas = Object.assign({}, this.tableSelectData[0])
      this.$refs['editFeeding']
        .getList()
        .then(() => {
          this.editFeedingVisible = true
        })
        .catch(() => {
          this.$u.toast(i18n.t('修改报工出现问题'))
        })
    },
    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) {
        this.$u.toast(i18n.t('不允许同时操作多条任务'))
        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.handleRadio({ target: { value: row.taskWorkunitId } })
      this.curTaskInfo = row
    },
    getCode(row) {
      this.usePersonData = row
      this.userTempVisible = true
    },
    chooseReason(row) {
      if (!row.quantityUnqualify || Number(row.quantityUnqualify) === 0) return
      this.reasonOBJ = row
      this.abnormalReasonVisible = true
    },
    toggleRowSelection(checked, arr) {
      console.log(arr, 'this.tableSelectData')
      this.tableSelectData = arr
    },
    knifeTemp() {
      // this.$u.toast('刀具校验通过！');
    },
    abnormalReasonDetermine (){
      const tableSelectData = JSON.parse(
        JSON.stringify(this.$refs.abnormalReasonRef.tableSelectData)
      )
      this.reasonOBJ.abnormalId = tableSelectData[0].abnormalId
      this.reasonOBJ.abnormalReason = tableSelectData[0].abnormalReason
      this.reasonOBJ.abnormalType = tableSelectData[0].abnormalType
      this.reasonOBJ.abnormalRemark = tableSelectData[0].remark
    },
    userDetermine() {
      const tableSelectData = JSON.parse(
        JSON.stringify(this.$refs.userPersonnelRef.tableSelectData)
      )
      const a = tableSelectData.length - 1
      tableSelectData.forEach((item) => {
        if (this.userList.findIndex(v => v.userName === item.userName) < 0) {
          this.userList.push(item)
        }
      })
    },
    stopReasonSubmit() {
      this.tableSelectData.forEach((item) => {
        this.changeStop(
          item.taskId,
          item.taskWorkunitId,
          'PAUSE',
          item.workunitId
        )
      })
      this.getTaskList()
    },
    stopReasonChange(e) {
      this.stopReason += e
    },

    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,
            }
          })
        })
    },

    pickingCause() {
      // 查询原因
      this.$u.api.abnormal
        .detail({
          pageNum: 1,
          pageSize: 10,
          abnormalType: 'REASON',
        })
        .then((res) => {
          this.reasonList = res.rows.map((item) => {
            return {
              value: item.abnormalReason,
              text: item.abnormalReason,
            }
          })
        })
    },
    pickingCauses() {
      // 查询原因
      this.$u.api.abnormal
        .detail({
          pageNum: 1,
          pageSize: 10,
          abnormalType: 'RETURN_REASON',
        })
        .then((res) => {
          this.reasonReturnList = res.rows.map((item) => {
            return {
              value: item.abnormalReason,
              text: item.abnormalReason,
            }
          })
        })
    },
    confirmArrange(e) {
      this.tableParams.arrangeCode = e
      this.getTaskList(this.tableParams)
    },
    getTaskList(params) {
      this.form = {}
      const t = this
      this.tableData = []
      this.$nextTick(() => {
        if (this.$refs['zbtable']) {
          this.$refs['zbtable'].selectArr = []
        }
      })
      this.tableSelectData = []
      let apires
      if (!this.vuex_workunit) {
        apires = this.$u.api.getAllTaskList({
          ...this.tableParams,
          ...params,
        })
      } else if (this.isWaiXie) {
        apires = this.$u.api.getTaskList({
          outsourced: 1,
          workunitId: t.vuex_workunit.workunitId,
          workorderCode: this.tableParams.arrangeCode,
          allowProduce: this.tableParams.allowProduce,
        })
      } else {
        apires = this.$u.api.getTaskList({
          workunitId: t.vuex_workunit.workunitId,
          ...this.tableParams,
          ...params,
        })
      }
      apires
        .then((res) => {
          if (res.code === 200) {
            let currentIndex = -1
            this.$refs['zbtable'].bodyScrollTop = 0
            // 过滤可加工数量为0的数据
            this.tableData = res.rows.map((item, index) => {
              if (item.location) {
                currentIndex = index
                item['checked'] = true
                this.$nextTick(() => {
                  if (this.$refs['zbtable']) {
                    this.$refs['zbtable'].selectArr = [item]
                  }
                })
                this.tableSelectData.push(item)
              }
              const returnPra = {
                ...item,
                scheduleStartDateStr: item.scheduleStartDate
                  ? item.scheduleStartDate.substring(2, 16)
                  : '',
                scheduleEndDateStr: item.scheduleEndDate
                  ? item.scheduleEndDate.substring(2, 16)
                  : '',
              }
              if (
                this.isWaiXie &&
                item.proWorkorderList &&
                item.proWorkorderList.length > 0
              ) {
                returnPra['workorderCode'] =
                  item.proWorkorderList[0]['workorderCode']
                returnPra['workorderId'] =
                  item.proWorkorderList[0]['workorderId']
                returnPra['productCode'] =
                  item.proWorkorderList[0]['productCode']
                returnPra['productName'] =
                  item.proWorkorderList[0]['productName']
              }
              return returnPra
            })
            if (this.tableData.length > 0) {
              this.curTaskInfo = this.tableData[0]
              if (currentIndex > -1) {
                this.$nextTick(() => {
                  const query = uni.createSelectorQuery().in(this)
                  query.select('#tableBody').boundingClientRect()
                  query.selectAll('#tableBody .item-tr').boundingClientRect()
                  query.exec((res) => {
                    const data1 = res[0]
                    let scrollTop = 0
                    // const currentIndexPlus = currentIndex + 1
                    let sumheight = 0
                    if (res[1] && Array.isArray(res[1]) && res[1].length > 0) {
                      res[1].forEach((item, index) => {
                        if (index < currentIndex) {
                          sumheight += item.height
                        }
                      })
                      // 当查找项高度不在当前窗口，需要滚动到指定高度
                      // 当查找项目在当前窗口，则不滚动
                      // 当查找项目只有一半部分在当前窗口，则滚动到当前项目之前叠加的高度
                      scrollTop =
                        sumheight > data1.height
                          ? sumheight
                          : res[1][currentIndex].height + sumheight >
                            data1.height
                          ? sumheight
                          : 0
                    } else {
                      const height = 80.8
                      scrollTop =
                        height * currentIndex > data1.height
                          ? height * currentIndex
                          : 0
                    }

                    this.$refs['zbtable'].bodyScrollTop = scrollTop
                  })
                })
              }
            }
          }
        })
        .catch((e) => {
          console.log('eee', e)
        })
    },
    // px转rpx
    pxToRpx(px) {
      const screenWidth = uni.getSystemInfoSync().screenWidth
      return (750 * Number.parseInt(px)) / screenWidth
    },
    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(i18n.t('变更成功'))
            }
            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(i18n.t('变更成功'))
            this.getTaskList()
          }
        })
    },

    changeShow() {
      console.log(this.timeTest.isshow)
      this.timeTest.isshow = !this.timeTest.isshow
    },

    getPrintTemplate(row) {
      this.printTemplateData = row
      this.printTemplateVisible = true
    },
    chooseUser() {
      console.log(
        this.$refs.userRef.tableSelectData,
        'this.$refs.userRef.tableSelectData'
      )
      this.useData.checkBy = this.$refs.userRef.tableSelectData[0]?.userName
    },
    handleSubmitPrintTemplate() {
      this.printTemplateData.printTemplate =
        this.$refs.printTemplateRef.tableSelectData[0].name
      this.printTemplateVisible = false
    },
    async doFeedback() {
      // this.reset();
      this.feedbackUnQuantityFu = 0
      this.feedbackQuantityFu = 0
      this.userList = []
      this.feedbackForms = []
      let flagPackage = []
      this.tableSelectData.forEach((item, index) => {
        flagPackage.push(item.isPackage === '1')
        let defQualify =
          item.quantity - item.quantityQualify - item.quantityUnqualify
        defQualify = defQualify < 0 ? 0 : defQualify
        defQualify =
          defQualify > item.quantityWait ? item.quantityWait : defQualify
        const feedback = {
          ...item,
          workorderFeedback: 0,
          qrcode: item.qrcode,
          oldqrcode: item.qrcode,
          workorderUnfeedback: 0,
          workstationId: item.workstationId,
          userName: this.vuex_user.userName,
          taskId: item.taskId,
          taskWorkunitId: item.taskWorkunitId,
          processId: item.processId,
          workorderId:
            item.proWorkorderList.length > 0
              ? item.proWorkorderList[0].workorderId
              : null,
          feedbackChannel: 'PAD',
          quantity: item.quantity,
          //默认为排产数量-合格数-不合格数
          quantityUnqualify: 0,
          reportQualify: item.quantityQualify + item.quantityUnqualify,
          printName: '',
          lastProcess: item.isLastProcess == 1, //未工序
          nickName: '',
          workorderCode:
            item.proWorkorderList.length > 0
              ? item.proWorkorderList[0].workorderCode
              : null,
          netWeight: 0,
          minPackageNum: 0,
          workorderList: [],
          chooseName: '',
          workorderOption: [],
          directiveData: {},
          sizeData: {},
          printContents: item.arrangeCode,
          feedbackTime: this.parseTime(new Date()),
          whether: '',
          closeType: null,
          abnormalId: null,
          abnormalReason: null,
          abnormalType: null,
          abnormalRemark: null,
          printTemplate: '',
          tableSizeData: [],
          remark: '',
          tableSizeColumn: [
            {
              name: 'standardSizeIdx',
              label: i18n.t('序号'),
              width: 40,
            },
            {
              name: 'standardSize',
              label: i18n.t('标准SIZE'),
              width: 100,
            },
            {
              name: 'quantity',
              label: i18n.t('派工数'),
              width: 60,
            },
            {
              name: 'packageNum',
              label: i18n.t('包装数'),
              width: 60,
            },
            {
              name: 'lossNum',
              label: i18n.t('LOSS数'),
              width: 60,
            },
            {
              name: 'feedbackQuantity',
              label: i18n.t('已包装数'),
              width: 80,
            },
            {
              name: 'reportQuantity',
              label: i18n.t('本次报工'),
              width: 90,
              type: 'slot',
              slot: 'reportQuantity',
            },
            {
              name: 'netWeight',
              label: i18n.t('净重'),
              width: 80,
              type: 'slot',
              slot: 'netWeight',
            },
            {
              name: 'grossWeight',
              label: i18n.t('毛重'),
              width: 80,
              type: 'slot',
              slot: 'grossWeight',
            },
            {
              name: 'packageStandard',
              label: i18n.t('装箱规格'),
              width: 120,
              type: 'slot',
              slot: 'packageStandard',
            },
            {
              name: 'peration',
              label: i18n.t('操作'),
              width: 80,
              type: 'slot',
              slot: 'peration',
            },
          ],
          taskType: item.taskType,
          listTabPro: [],
          tableOrderData: [],
          tableDirectiveData: [],
          currentTabPro: 0,
          packNum: 0,
          workorderUnfeedbackSum: item.quantityWait,
          workorderFeedbackSum: item.quantityQualify,
          encasementNum: 0,
          mergePack: 0,
        }
        if (feedback.isSerialReport && Number(feedback.isSerialReport) === 1) {
          feedback.quantityQualify = 1
        } else {
          feedback.quantityQualify = item.quantityWait
        }
        if (this.isWaiXie) {
          feedback.quantityQualify =
            item.quantity - item.quantityQualify - item.quantityUnqualify
          feedback.quantityUnqualify = item.quantityUnqualify
          feedback.quantityFeedback = item.quantityQualify
          feedback.unquantityFeedback = item.quantity - item.quantityQualify
          feedback.closeType = ''
        }
        this.feedbackForms.push(feedback)
      })
      if (Array.from(new Set(flagPackage)).length === 2) {
        this.$u.toast(i18n.t('包装工序禁止多选报工'))
        return
      }
      // 如果选择了包装工序、非包装工序提示：“包装工序禁止多选报工”
      this.proVisible = true
    },

    async doException() {
      if (this.tableSelectData.length > 1) {
        this.$u.toast(i18n.t('不允许同时操作多条任务'))
        return
      }
      let abnormalNumber = ''
      const data = await this.$u.api.abnormal.getAbnormalNumber()
      if (data.code === 200) {
        abnormalNumber = data.data
      }
      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: item.workunitId,
        workstationCode: item.workunitCode,
        workstationName: item.workunitName,
        abnormalType: '',
        abnormalReason: '',
        abnormalTime: '',
        abnormalNumber: abnormalNumber
      })
      this.errorVisible = true
    },

    async newlyAddss() {
      const res = await this.$u.api.abnormal
        .newlyAdd(this.ExceptionForms)
        .then((res) => {
          if (res.code === 200) {
            this.$u.toast(i18n.t('上报成功'))
          } else {
            this.$u.toast(res.msg)
          }
        })

      this.getTaskList()
    },
    cancel() {
      this.proVisible = false
      this.timeTest.isshow = false
      // this.feedbackUnQuantityFu = 0;
      // this.feedbackQuantityFu = 0;
    },
    handleSubmitfeedback() {
      this.feedbackUnQuantityFu = 0
      this.feedbackQuantityFu = 0
      this.timeTest.isshow = false
      this.feedbackForms.forEach((item) => {
        item.userName = this.userList.map(v => v.userName).join('，')
        item.nickName = this.userList.map(v => v.nickName).join('，')
        if (!item.userName) {
          this.$u.toast(i18n.t('报工人不能为空'))
          this.proVisible = true
          this.$refs.uModal.clearLoading()
          return
        }
        if(item.quantityUnqualify && Number(item.quantityUnqualify) > 0 && !item.abnormalReason) {
          this.$u.toast(i18n.t('不合格原因不能为空'))
          this.proVisible = true
          this.$refs.uModal.clearLoading()
          return
        }

        if (
          (item.quantity === 0 || item.quantity === null) &&
          !item.isSerialReport &&
          Number(item.isSerialReport) !== 1
        ) {
          this.$u.toast(i18n.t('请填写合格/不合格产品数量！'))
          return
        }
        // if (item.lastProcess) {
        //   //最后工序
        // }
        // if ((item.printTemplate || item.whether == '1') && !this.vuex_printConnect) {
        //   this.$u.toast('打印机连接失败');
        //   return;
        // }
        let apires
        if (this.isWaiXie) {
          const par = {
            //工单
            taskWorkunitId: item.taskWorkunitId,
            taskId: item.taskId,
            taskCode: item.taskCode,
            quantityFeedback: item.quantityQualify + item.quantityUnqualify,
            quantityQualify: item.quantityQualify,
            quantityUnqualify: item.quantityUnqualify,
            userName: item.userName,
            nickName: item.nickName,
            feedbackType: item.feedbackType,
            routeId: item.routeId,
            routeCode: item.routeCode,
            processId: item.processId,
            processCode: item.processCode,
            processName: item.processName,
            itemId: item.itemId,
            itemCode: item.processCode,
            itemName: item.processName,
            workstationId: item.workstationId,
            workstationCode: item.workstationCode,
            abnormalId: item.abnormalId,
            abnormalReason: item.abnormalReason,
            abnormalType: item.abnormalType,
            abnormalRemark: item.abnormalRemark,
            workorderId: item.workorderId,
            workorderCode: item.workorderCode,
            workstationName: item.workstationName,
            startTime: item.scheduleStartDate,
            printTemplate: item.printTemplate,
            netWeight: item.netWeight,
            feedbackTime: item.feedbackTime,
            minPackageNum: item.minPackageNum,
            closeType: item.closeType,
            printContents: item.whether == '1' ? item.printContents : null,
          }
          apires = this.$u.api.assistFeedback(par)
        } else {
          const par = {
            //工单
            taskWorkunitId: item.taskWorkunitId,
            taskId: item.taskId,
            taskCode: item.taskCode,
            quantityFeedback: item.quantityQualify + item.quantityUnqualify,
            quantityQualify: item.quantityQualify,
            quantityUnqualify: item.quantityUnqualify,
            userName: item.userName,
            feedbackType: item.feedbackType,
            routeId: item.routeId,
            routeCode: item.routeCode,
            processId: item.processId,
            nickName: item.nickName,
            processCode: item.processCode,
            processName: item.processName,
            itemId: item.itemId,
            itemCode: item.itemCode,
            itemName: item.itemName,
            abnormalId: item.abnormalId,
            abnormalReason: item.abnormalReason,
            abnormalType: item.abnormalType,
            abnormalRemark: item.abnormalRemark,
            workstationId: item.workstationId,
            workstationCode: item.workstationCode,
            workorderId: item.workorderId,
            workorderCode: item.workorderCode,
            workstationName: item.workstationName,
            startTime: item.scheduleStartDate,
            printTemplate: item.printTemplate,
            netWeight: item.netWeight,
            feedbackTime: item.feedbackTime,
            minPackageNum: item.minPackageNum,
            printContents: item.whether == '1' ? item.printContents : null,
          }
          if (item.isSerialReport && Number(item.isSerialReport) === 1) {
            par['qrcode'] = item.qrcode
            par['remark'] = item.remark
          }
          apires = this.$u.api.feedback(par)
        }

        apires.then((res) => {
          
          if (res.code === 200) {
            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)
                })
              })
            }
            let workunitName = ''
            if (item.whether == '1') {
              this.$u.api
                .getNextProcess({ taskId: item.taskId })
                .then((workunit) => {
                  workunitName = workunit.data.workunitName
                  console.log(
                    item.arrangeCode,
                    item.workorderCode,
                    item.quantityQualify,
                    workunitName
                  )
                  let aa =
                    i18n.t('编排单号:') +
                    item.arrangeCode +
                    i18n.t('\n工单号:') +
                    item.workorderCode +
                    i18n.t('\n数量:') +
                    item.quantityQualify +
                    i18n.t('\n下一道工序:') +
                    workunitName
                  console.log(aa)

                  this.printPdfSocket({
                    reportName: 'mysql:qrcode-50*50-2',
                    values: {
                      detail: [
                        {
                          barcode: item.printContents,
                          showText:
                            i18n.t('编排单号:') +
                            item.arrangeCode +
                            i18n.t('\n数量:') +
                            item.quantityQualify +
                            i18n.t('\n工单号:') +
                            item.workorderCode +
                            i18n.t('\n下道工序机台:') +
                            workunitName,
                          gp: 1,
                        },
                        {
                          barcode: item.printContents,
                          showText:
                            i18n.t('编排单号:') +
                            item.arrangeCode +
                            i18n.t('\n数量:') +
                            item.quantityQualify +
                            i18n.t('\n工单号:') +
                            item.workorderCode +
                            i18n.t('\n下道工序机台:') +
                            workunitName,
                          gp: 1,
                        },
                      ],
                    },
                  })
                })
            }

            if (!res.msg) {
              this.$u.toast(i18n.t('上报成功'))
            } else {
              this.$u.toast(res.msg)
            }
            console.log('准备刷新')

            this.getTaskList()
          }
          if (item.isSerialReport && Number(item.isSerialReport) === 1) {
            this.feedbackForms[0]['qrcode'] = ''
            this.isFocus = true
            // this.proVisible = true;
            this.$refs.uModal.clearLoading()
          } else {
            this.isFocus = false
            this.proVisible = false
          }
        })
      })
    },
    feedingInspectionShow() {
      if (this.tableSelectData.length > 1) {
        this.$u.toast(i18n.t('不允许同时操作多条任务'))
        return
      }
      this.feedingInspectionVisible = true
      this.getPemissionScan()
      this.feedingInspectionLoadAndScan()
    },
    feedingInspectionLoadAndScan(bool) {
      const taskInfo = this.tableSelectData[0]
      this.$u.api
        .listFeedingInspectionlist({ taskId: taskInfo.taskId })
        .then((res) => {
          if (res.code === 200) {
            this.feedingInspectionList = res.data
            if (bool) {
              this.$u.toast(i18n.t('保存成功'))
            }
          }
        })
    },
    feedingInspectionScan(barNumber) {
      console.log(barNumber, '-----barNumberfeedingInspectionScan')
      const taskInfo = this.tableSelectData[0]
      this.$u.api
        .validateFeedingInspection({ plnr: barNumber, taskId: taskInfo.taskId })
        .then((res) => {
          if (res.code === 200) {
            this.feedingInspectionLoadAndScan(true)
          }
        })
    },
    async getPemissionScan() {
      /* #ifdef APP-PLUS */
      if (!uni.getStorageSync('iosCameraAuth') && this.isIos) {
        uni.setStorageSync('iosCameraAuth', true)
      } else {
        let bol = await this.getCameraAuth()
        if (!bol) {
          this.refusedCameraAuth()
          return
        }
      }
      /* #endif */
    },
    validateFeedingInspection(line) {
      // if(line.attr3 == 1) return
      const t = this
      const taskInfo = this.tableSelectData[0]
      this.$u.api
        .validateFeedingInspectionById({ lineId: line.lineId })
        .then((res2) => {
          if (res2.code === 200) {
            t.$u.api
              .listFeedingInspectionlist({ taskId: taskInfo.taskId })
              .then((res) => {
                if (res.code === 200) {
                  t.feedingInspectionList = res.data
                }
              })
          }
        })
    },
    recoilMaterialShow() {
      if (this.tableSelectData.length > 1) {
        this.$u.toast(i18n.t('不允许同时操作多条任务'))
        return
      }
      this.recoilMaterialVisible = true
      this.getPemissionScan()
      this.recoilMaterialLoadAndScan()
    },
    recoilMaterialLoadAndScan(bool) {
      const t = this
      const taskInfo = this.tableSelectData[0]
      this.$u.api
        .recoilMaterialList({
          taskId: taskInfo.taskId,
          processId: taskInfo.processId,
        })
        .then((res) => {
          if (res.code === 200) {
            t.recoilMaterialDetailList = res.data
            if (bool) {
              t.$u.toast(i18n.t('保存成功'))
            }
          }
        })
    },
    recoilMaterialScan(barNumber) {
      console.log(barNumber, '-----barNumberrecoilMaterialScan')
      const taskInfo = this.tableSelectData[0]
      this.$u.api
        .addRecoilMaterial({ taskId: taskInfo.taskId, plnr: barNumber })
        .then((res) => {
          if (res.code === 200) {
            this.recoilMaterialLoadAndScan(true)
          }
        })
    },
    recoilMaterialDelete(line) {
      const t = this
      const taskInfo = this.tableSelectData[0]
      this.$u.api.deleteRecoilMaterial({ id: line.id }).then((res2) => {
        t.$u.api
          .recoilMaterialList({
            taskId: taskInfo.taskId,
            processId: taskInfo.processId,
          })
          .then((res) => {
            if (res.code === 200) {
              t.recoilMaterialList = res.data
            }
          })
      })
    },

    batchShow(row) {
      this.recoilMaterialList = row.proRecoilMaterialList
      this.$refs.appScan.closed()
      this.recoilMaterialFlag = true
    },

    materialRequestShow() {
      if (this.tableSelectData.length > 1) {
        this.$u.toast(i18n.t('不允许同时操作多条数据'))
        return
      }
      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.map((item) => {
              return {
                ...item,
                workorderCode: this.curTaskInfo.workorderCode,
              }
            })
            this.materialRequestArrays = this.materialRequestList.concat([])
          }
        })
      this.$u.api
        .getMaterialRequest({ taskId: taskInfo.taskId })
        .then((res) => {
          if (res.code === 200) {
            this.materialRequestArrayLists = res.rows
            this.materialRequestArrayList =
              this.materialRequestArrayLists.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() {
      if (!this.curTaskInfo.pickingReason) {
        this.materialRequestVisible = true
        this.$u.toast(i18n.t('原因不能为空！'))
        return
      }
      const rst = []
      const taskInfo = this.tableSelectData[0]
      const t = this
      // const items = this.curTaskInfo.workorderOption.find((item) => item.value === this.curTaskInfo.workorderCode);
      // console.log(this.curTaskInfo.workorderOption, this.curTaskInfo.workorderCode);
      let workorderCode = null
      if (this.curTaskInfo.workorderOption) {
        const finditem = this.curTaskInfo.workorderOption.find(
          (v) => v.value === this.curTaskInfo.workorderCode
        )
        if (finditem) workorderCode = finditem.text
      }
      this.materialRequestArrays.forEach((s) => {
        if (s.applyNum != null) {
          rst.push({
            pickingReason: this.curTaskInfo.pickingReason,
            itemId: s.itemId,
            workunitCode: this.curTaskInfo.workunitCode,
            workunitName: this.curTaskInfo.workunitName,
            taskWorkunitId: this.curTaskInfo.taskWorkunitId,
            workstationId: this.curTaskInfo.workstationId,
            isBackflush: s.isBackflush,
            workorderCode: workorderCode,
            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(i18n.t('保存成功'))
        }
      })
    },
    viewiPctureShow() {
      if (this.tableSelectData.length > 1) {
        this.$u.toast(i18n.t('不允许同时操作多条任务'))
        return
      }
      this.materialReturn = true
      this.curTaskInfo = this.tableSelectData[0]
      this.$u.api.viewpicture
        .listLinkFile({
          taskId: this.curTaskInfo.taskId,
          workunitId: this.curTaskInfo.workunitId,
        })
        .then((res) => {
          if (res.code === 200) {
            this.viewSopPicture = res.data
          }
        })
    },
    materialReturnWorkorderProcessItem(id) {
      if (!id) {
        this.materialRequestArrays = this.materialRequestList.concat([])
        this.materialRequestArrayList = this.materialRequestArrayLists.concat(
          []
        )
      } else {
        const items = this.curTaskInfo.workorderOption.find(
          (item) => item.value === this.curTaskInfo.workorderCode
        )
        console.log(items)
        this.$u.api
          .getWproworkOrderProcessItem({
            workorderId: id,
            processId: this.curTaskInfo.processId,
          })
          .then((res) => {
            if (res.code === 200) {
              const list = res.rows.map((item) => {
                return {
                  ...item,
                  workorderCode: items.text,
                }
              })
              this.materialRequests = this.materialRequestList.concat(list)
              this.materialRequestArrays = this.materialRequests.filter(
                (item, index, self) => {
                  return (
                    self.findIndex((t) => t.itemCode === item.itemCode) ===
                    index
                  )
                }
              )
              console.log(this.materialRequestArrays, 'materialRequestArrays')
            }
          })
        this.materialRequestArrayList = []
        this.$u.api
          .getMaterialRequest({
            workorderId: id,
            taskId: this.curTaskInfo.taskId,
          })
          .then((res) => {
            if (res.code === 200) {
              console.log(res.rows)
              this.materialRequestArrayList = res.rows
            }
          })
      }
    },
    viewSopsShow(row) {
      // this.viewSopPicture = this.tableSelectData[0];
      uni.showLoading({})
      if (
        ['png', 'jpeg', 'jpg'].indexOf(
          row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
        ) > -1
      ) {
        uni.downloadFile({
          url: config.baseUrl + row.filePath,
          header: {
            Authorization: this.vuex_token,
          },
          success: function (res) {
            uni.hideLoading({})
            var filePath = res.tempFilePath
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {},
            })
          },
        })
      } else if (
        ['pdf'].indexOf(
          row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
        ) > -1
      ) {
        uni.downloadFile({
          url: config.baseUrl + row.filePath,
          header: {
            Authorization: this.vuex_token,
          },
          success: function (res) {
            var filePath = res.tempFilePath
            uni.hideLoading({})
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {},
            })
          },
        })
      } else {
        t.$u.toast(i18n.t('不支持查看其它格式的文件'))
      }
    },
    materialReturnSetting() {
      this.materialReturnSelected.applyNum =
        this.materialReturnFormData.applyNum
      this.materialReturnSelected.isQualified =
        this.materialReturnFormData.isQualified
      this.materialReturnFormVisible = false
    },
    async formatDateRandom() {
      await this.$u.api.genCode('MATERIAL_RETURN_CODE').then((item) => {
        console.log(item)
        this.applyNo = item
      })
    },
    async materialReturnSave() {
      if (!this.curTaskInfo.returnReason) {
        this.materialReturnVisible = true
        this.$u.toast(i18n.t('原因不能为空！'))
        return
      }
      await this.formatDateRandom()
      let a = null
      const taskInfo = this.tableSelectData[0]
      const rst = this.materialReturnList.map((s) => {
        let data = {
          itemId: s.itemId,
          taskId: taskInfo.taskId,
          backNum: s.quantityIssued,
          issueLineId: s.lineId,
          taskWorkunitId: this.curTaskInfo.taskWorkunitId,
          workOrderId: s.workorderId,
          batchNo: s.batchCode,
          packNo: s.packNo,
          applyNo: this.applyNo,
          isQualified: s.isQualified,
          returnReason: this.curTaskInfo.returnReason,
        }
        if (this.materialReturnFormData.workorderCode) {
          data.workorderCode = this.materialReturnFormData.workorderCode
        } else {
          // data.workorderCode = this.curTaskInfo.workorderOption.flatMap((it) => it.value).join(',');
          data.workorderCode = s.workorderCode
        }
        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(i18n.t('保存成功'))
        }
      })
      if (this.materialReturnFormData.number >= 1) {
        for (let i = 0; i < this.materialReturnFormData.number; i++) {
          this.printPdfSocket({
            reportName: 'mysql:qrcode-50*50-2',
            values: {
              detail: [
                {
                  barcode: this.applyNo,
                  showText: i18n.t('退料单号:') + this.applyNo,
                  gp: i + 1,
                },
                {
                  barcode: this.applyNo,
                  showText: i18n.t('退料单号:') + this.applyNo,
                  gp: i + 1,
                },
              ],
            },
          })
        }
      }
    },

    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;
  /deep/ .uni-data-checklist .checklist-group .checklist-box {
    margin-right: 15px;
  }
}

.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.yellow .item-td {
      background: #ff9900 !important;
      // color:#fff !important;
    }
    /deep/ .item-tr.green .item-td {
      background: #19be6b !important;
      // color:#fff !important;
    }
    /deep/ .item-tr.red .item-td {
      background: #f56c6c !important;
      // color:#fff !important;
    }
    /deep/ .item-tr.selectrow .item-td {

      background: #00ffff !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;
  }
  /deep/ .uni-scroll-view {
    -ms-overflow-style: none; /* IE 10+ */
    scrollbar-width: none; /* Firefox */
    &::-webkit-scrollbar {
      display: none; /* 对于 Chrome, Safari 和 Opera 隐藏滚动条 */
    }
  }
}

.times {
  /deep/ .uni-date-picker__container {
    height: 360rpx;
  }
}
.list-bar {
  position: relative;
  .sum {
    position: absolute;
    bottom: -30px;
    right: 5px;
    display: flex;
    font-size: 14px;
    .pro-wrapper {
      width: 400rpx;
    }
    view {
      margin-right: 10rpx;
    }
  }
}
.mynotable {
  .tr-green {
    background: #4ea381 !important;
  }
  .uni-table-td {
    color: black;
  }
}
.successBtn {
  display: inline-flex;
  width: auto;
  font-size: 22rpx;
  padding-top: 1px;
  height: 50rpx;
  line-height: 50rpx;
  padding: 0 20rpx;
  color: #ffffff;
  border-color: #19be6b;
  background-color: #19be6b;
  &:hover {
    border-color: #19be6b !important;
    background-color: #19be6b !important;
    color: #ffffff !important;
  }
}
.feedSize {
  /deep/ .grablue {
    background: #ecf5ff !important;
  }
  /deep/ .grablue .even {
    background: #ecf5ff !important;
  }
  /deep/ .grablue .odd {
    background: #ecf5ff !important;
  }
}
.mytag {
  padding: 6px 3px;
}
</style>
<style lang="scss">
.mynotable {
  width: 100% !important;
  /deep/ .uni-table {
    min-width: 100% !important;
  }
}
</style>