<template>
  <view class="commonBody">
    <view class="prod-body">
      <view class="prod-body-left">
        <!--        <view class="prod-body-left-btns">-->
        <!--          <view class="workstation">-->
        <!--            工作站名称：-->
        <!--            {{ this.vuex_workstation == null ? '请选择工作站' : this.vuex_workstation.workstationName }}-->
        <!--            &lt;!&ndash;            <u-icon name="edit-pen-fill" size="46" color="#2979ff"></u-icon>&ndash;&gt;-->
        <!--          </view>-->
        <!--          <u-button type="primary" @click="changeWorkstation">切换工作站</u-button>-->
        <!--          &lt;!&ndash;                  <u-button type="primary" @click="commonClick('')">生产任务</u-button>&ndash;&gt;-->
        <!--          &lt;!&ndash;                  <u-button type="primary" @click="commonClick('KnifeTemp')">刀模上架</u-button>&ndash;&gt;-->
        <!--          &lt;!&ndash;                  <u-button type="primary" @click="commonClick('')">生产投料</u-button>&ndash;&gt;-->
        <!--        </view>-->

        <view class="prod-body-left-task">
          <zb-table :columns="tableColumn" :stripe="true" @rowClick="rowClick"
                    @toggleRowSelection="toggleRowSelection" @toggleAllSelection="toggleAllSelection" :border="true"
                    :data="tableData"></zb-table>
        </view>
        <view class="prod-body-left-num">
          总报工订单数：{{ tableData.length }}
        </view>
        <view class="prod-body-left-bom">
          <!--          <view class="prod-body-left-bom-type">-->
          <!--            <u-subsection :list="typeList" :current="currentType" type="primary" font-size="28"-->
          <!--                          @change="typeChange"></u-subsection>-->
          <!--          </view>-->
          <!--          <view class="prod-body-left-bom-table">-->
          <!--            <u-form>-->
          <!--              <u-row gutter="16">-->
          <!--                <u-col span="3">-->
          <!--                  <u-form-item label="任务单号" label-width="150">-->
          <!--                    {{ curTaskInfo.taskCode }}-->
          <!--                  </u-form-item>-->
          <!--                </u-col>-->
          <!--                <u-col span="4">-->
          <!--                  <u-form-item label="物料条码" label-width="150">-->
          <!--                    <SearchInput v-model="materialRecordInfo.materialBatchNumber" placeholder="请输入物料条码"-->
          <!--                                 hassearchbtn="true"-->
          <!--                                 @inputchange="(val)=>{materialRecordInfo.materialBatchNumber=val}"/>-->
          <!--                  </u-form-item>-->
          <!--                </u-col>-->
          <!--                <u-col span="2">-->
          <!--                  <u-form-item label="数量">-->
          <!--                    <u-number-box :min="0" v-model="materialRecordInfo.quantity"></u-number-box>-->
          <!--                  </u-form-item>-->
          <!--                </u-col>-->
          <!--                <u-col span="1">-->
          <!--                  <u-button type="primary" size="mini" @click="commonClick('MaterialUsageRecord')">添加</u-button>-->
          <!--                </u-col>-->
          <!--                <u-col span="1">-->
          <!--                </u-col>-->
          <!--                <u-col span="5">-->
          <!--                </u-col>-->
          <!--              </u-row>-->
          <!--            </u-form>-->
          <zb-table :columns="issusLineColumn" :stripe="true" :fit="true" :border="true"
                    :data="issusLineList"></zb-table>
          <!--          </view>-->
        </view>
      </view>
      <view class="prod-body-right">
        <view style="text-align: center;line-height: 80rpx;font-size: 28rpx;font-weight: 600;">
          {{ this.vuex_workstation == null ? '请选择工作站' : this.vuex_workstation.workstationName }}
        </view>
        <u-button type="primary" @click="changeWorkstation">切换工作站</u-button>
        <br/>
        <u-button type="warning" @click="commonClick('KnifeTemp')">刀模上架</u-button>
        <u-button type="primary" @click="commonClick('Refresh')">刷新</u-button>
        <u-button type="success" @click="commonClick('StartTask')">开始作业</u-button>
        <u-button type="warning" @click="commonClick('StopTask')">暂停作业</u-button>
        <u-button type="success" @click="commonClick('Prod')">生产报工</u-button>
        <u-button type="primary" @click="commonClick('FinshTask')">完成作业</u-button>
        <!--        <u-button type="error" @click="commonClick('')">报告异常</u-button>-->
        <!--        <u-button type="warning" @click="commonClick('')">检验通知</u-button>-->
        <!--        <u-button type="primary" @click="commonClick('')">属性收集</u-button>-->
        <!--        <u-button type="primary" @click="commonClick('')">反扣冲减</u-button>-->
        <!--        <u-button type="primary" @click="commonClick('')">查看图纸</u-button>-->
        <!--        <u-button type="warning" @click="commonClick('')">完成全部</u-button>-->
      </view>
    </view>

    <u-modal :title="title" @confirm="feedback()" show-cancel-button
             :title-style="{'background-color':'#1E3770','color': '#FFFFFF' ,'line-height': '37px','padding-top': '0px'}"
             v-model="open" width="1800rpx">
      <view class="feedback-card" v-for="feedback in feedbackForms">
        <u-form label-width="100px" :model="feedback" :rules="rules">
          <u-row>
            <u-col span="6">
              <u-form-item label="任务单号" prop="quantity">
                {{ feedback.taskCode }}
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="工序" prop="nickName">
                {{ feedback.processName }}
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="6">
              <u-form-item label="报工总数量" prop="quantity">
                {{ feedback.quantityQualify + feedback.quantityUnqualify }}
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="报工人" prop="nickName">
                <u-input v-model="feedback.nickName"></u-input>
              </u-form-item>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="6">
              <u-form-item label="合格品数量" prop="quantityQualify">
                <u-number-box :min="0" @change="quantityChanged"
                              v-model="feedback.quantityQualify"></u-number-box>
              </u-form-item>
            </u-col>
            <u-col span="6">
              <u-form-item label="不良品数量" prop="quantityUnqualify">
                <u-number-box :min="0" @change="quantityChanged"
                              v-model="feedback.quantityUnqualify"></u-number-box>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
    </u-modal>


    <u-modal title="刀模版上架" @confirm="knifeTemp()" show-cancel-button
             :title-style="{'background-color':'#1E3770','color': '#FFFFFF' ,'line-height': '37px','padding-top': '0px'}"
             v-model="knifeTempVisible" width="1300rpx">
      <u-form label-width="130px" :model="knifeTempSearch" :rules="rules">
        <u-row>
          <u-col span="6">
            <u-form-item label="扫描刃模版条码" prop="quantity">
              <u-input v-model="knifeTempSearch.knifeTempCode"></u-input>
            </u-form-item>
          </u-col>
          <u-col span="6">
            <u-form-item label="扫描库位条码" prop="nickName">
              <u-input v-model="knifeTempSearch.locationCode"></u-input>
            </u-form-item>
          </u-col>
        </u-row>
      </u-form>
      <view>
        扫描结果
        <uni-card>
          <view class="uni-card__content">
            <view class="uni-card__content-title">刀模信息</view>
            <view class="uni-card__content-extra">刀模编号：{{ knifeTempInfo.knifeTemplateCode }}</view>
            <view class="uni-card__content-extra">刀模名称：{{ knifeTempInfo.knifeTemplateName }}</view>
            <view class="uni-card__content-extra">刀模规格：{{ knifeTempInfo.knifeTemplateSpec }}</view>
          </view>
        </uni-card>
      </view>
    </u-modal>


    <u-modal title="暂停原因" @confirm="stopReasonSubmit()" show-cancel-button
             :title-style="{'background-color':'#1E3770','color': '#FFFFFF' ,'line-height': '37px','padding-top': '0px'}"
             v-model="stopReasonVisible" width="1300rpx">
      <u-form label-width="100px" :model="feedback" :rules="rules">
        <u-form-item label="故障类型" prop="quantity">
          <uni-data-select
              :localdata="stopReasonList"
              @change="stopReasonChange"
          ></uni-data-select>
        </u-form-item>
        <u-form-item label="故障原因" prop="nickName">
          <u-input type="textarea" height="150" :border="true" v-model="stopReason"></u-input>
        </u-form-item>
      </u-form>
    </u-modal>
  </view>
</template>

<script>
import SearchInput from "@/components/ScanInput/index.vue";

export default {
  name: "ProdReport",
  components: {SearchInput},
  data() {
    return {
      screenHeight: 768,
      title: '生产报工',
      open: false,
      form: {},
      feedbackForm: {},
      tableData: [],
      knifeTempVisible: false,
      knifeTempSearch: {
        knifeTempCode: '',
        locationCode: ''
      },
      knifeTempInfo: {
        knifeTemplateCode: '',
        knifeTemplateName: '',
        knifeTemplateSpec: '',
        locationCode: '',
        locationName: '',
        locationType: '',
        locationTypeCode: '',
        locationTypeDesc: '',
        locationTypeDescCode: '',
        locationTypeDescName: '',
        locationTypeDescNameCode: '',
        locationTypeDescNameCode2: ''
      },
      stopReasonList: [
        {value: '中午休息吃饭。', text: "休息吃饭"},
        {value: '刀头模具到期更换，更换期间。', text: "刀头模具到期更换"},
        {value: '没料了，正在领料', text: "领料加仓"}
      ],
      stopReason: '',
      stopReasonVisible: false,
      rules: {
        quantity: [{
          required: true,
          message: "请输入合格品数量或者不良品数量！",
          trigger: "blur"
        }]
      },
      typeList: [
        {
          name: '物料扣减'
        },
        {
          name: 'BOM外扣减'
        }
      ],
      materialRecordInfo: {
        taskCode: '',
        materialBatchNumber: '',
        quantity: 0,
        operatorTime: '',
        depletionMethod: 1
      },
      curTaskInfo: {},
      currentType: 0,
      bomFeeData: [],
      bomFeeColumn: [
        {
          type: 'selection',
          width: 35
        },
        {
          name: 'taskCode',
          label: '物料批次',
          align: "center",
          width: 150
        },
        {
          name: 'status',
          label: 'ERP物料批次',
          align: "center",
          width: 150
        },
        {
          name: 'materialBatchNumber',
          label: '物料编码',
          width: 150
        },
        {
          name: 'taskCode',
          label: '序列号',
          width: 150
        },
        {
          name: 'quantity',
          label: '数量',
          width: 150
        },
        {
          name: 'itemCode',
          label: '物料描述',
        }
      ],
      tableColumn: [
        {
          type: 'selection',
          width: 35
        },
        {
          name: 'startTime',
          label: '计划开始时间',
          width: 140,
        },
        {
          name: 'status',
          label: '订单状态',
          filters: {
            'START': '生产中',
            'PAUSE': '暂停',
            'NORMARL': '未开始'
          },
          width: 60,
          align: "center"
        },
        // {
        //   name: 'date',
        //   label: '批号',
        //   width: 50,
        // },
        {
          name: 'taskCode',
          label: '任务单号',
          width: 110,
        },
        {
          name: 'workorderCodes',
          label: '生产单号',
          width: 120,
        },
        {
          name: 'itemCode',
          label: '物料编号',
          width: 110,
        },
        {
          name: 'itemName',
          label: '物料名称'
        },
        {
          name: 'processName',
          label: '工序',
          width: 60,
        },
        {
          name: 'quantity',
          label: '数量',
          width: 60,
          align: "center"
        },
        {
          name: 'quantityQuanlify',
          label: '合格数量',
          width: 60,
          align: "center"
        },
        {
          name: 'quantityUnquanlify',
          label: '不合格数量',
          width: 60,
          align: "center"
        },
        {
          name: 'clientName',
          label: '作业人员',
          width: 60,
          align: "center"
        },
      ],
      tableSelectData: [],
      feedbackForms: [],
      materialUsageRecordList: [],
      issusLineList: [],
      issusLineColumn: [
        {
          name: 'itemCode',
          label: '产品物料编码',
        },
        {
          name: 'itemName',
          label: '产品物料名称',
        },
        {
          name: 'specification',
          label: '规格型号',
        },
        {
          name: 'unitOfMeasure',
          label: '单位',
        },
        {
          name: 'quantityIssued',
          label: '领料数量',
        },
        {
          name: 'batchCode',
          label: '批次号',
        },
        {
          name: 'warehouseName',
          label: '仓库名称',
        },
        {
          name: 'locationName',
          label: '库区名称',
        },
        {
          name: 'areaName',
          label: '库位名称',
        }]
    }
  },
  mounted() {   //监听工作站切换事件
    uni.$on('switchWorkstation', (station) => {
      this.getTaskList();
    })
  },
  created() {
    //获取屏幕高度
    uni.getSystemInfo({
      success(res) {
        this.screenHeight = res.windowHeight;
      }
    })


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

    if (this.vuex_workstation != null) {
      this.getTaskList();
    }
  },
  destroyed() {
    uni.$off('switchWorkstation');
    uni.$off('taskStatusChanged');
  },
  methods: {
    changeWorkstation() {
      uni.$emit('changeWorkstation');
    },
    async commonClick(oper) {
      if (['Refresh', 'MaterialUsageRecord'].indexOf(oper) === -1 && this.tableSelectData.length === 0) {
        this.$u.toast('请选择工作任务！');
        return
      }
      switch (oper) {
        case 'Refresh':
          this.getTaskList();
          break;
        case 'StartTask':
          await Promise.all(this.tableSelectData.map(async item => {
            await this.changeStatus(item.taskId, 'START');
          }));
          this.getTaskList()
          break;
        case 'StopTask':
          this.stopReason = ''
          this.stopReasonVisible = true
          break;
        case 'FinshTask':
          await Promise.all(this.tableSelectData.map(async item => {
            await this.changeStatus(item.taskId, 'FINISHED');
          }));
          this.getTaskList()
          break;
        case 'Prod':
          this.doFeedback()
          break;
        case 'MaterialUsageRecord':
          this.addMaterialUsageRecord()
          break;
        case 'KnifeTemp':
          this.knifeTempShow()
          break;
        default:
          this.$u.toast('功能正在开发中！');
          break
      }
    },
    knifeTempShow() {
      this.knifeTempSearch.knifeTempCode = '';
      this.knifeTempSearch.locationCode = '';
      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.curTaskInfo = row;
      // this.getMaterialUsageRecordList();
      this.getIssusLinebyWorkorderCodes();
    },
    toggleAllSelection(checked, arr) {
      this.tableSelectData = arr
    },
    toggleRowSelection(checked, arr) {
      this.tableSelectData = arr
    },
    knifeTemp() {
      this.$u.toast('刀具校验通过！');
    },
    async stopReasonSubmit() {
      await Promise.all(this.tableSelectData.map(async item => {
        await this.changeStatus(item.taskId, 'PAUSE');
      }));
      this.getTaskList()
    },
    stopReasonChange(e) {
      this.stopReason += e;
    },
    async getTaskList() {
      this.form = {}
      this.tableData = []
      const res = await this.$u.api.getTaskList({
        workstationId: this.vuex_workstation.workstationId,
      })
      if (res.code === 200) {
        this.tableData = res.rows.filter(t => !['PREPARE', 'FINISHED'].includes(t.status));
        this.curTaskInfo = {}
        this.materialUsageRecordList = []
        if (this.tableData.length > 0) {
          this.curTaskInfo = this.tableData[0]
          // this.getMaterialUsageRecordList();
          this.getIssusLinebyWorkorderCodes();
        }
      }
    },
    typeChange(index) {
      this.currentType = index;
      this.getMaterialUsageRecordList()
    },
    getMaterialUsageRecordList() {
      this.materialUsageRecordList = []
      const res = this.$u.api.materialusagerecordList({
        workstationId: this.vuex_workstation.workstationId,
        depletionMethod: this.currentType + 1,
        taskId: this.curTaskInfo.taskId
      })
      if (res.code === 200) {
        this.materialUsageRecordList = res.rows;
      }
    },
    addMaterialUsageRecord() {
      if (this.materialRecordInfo.materialBatchNumber !== this.curTaskInfo.itemCode && this.currentType === 0) {
        this.$u.toast('物料不在生产目录中！');
        return
      }
      if (this.materialRecordInfo.quantity === 0) {
        this.$u.toast('请输入物料数量！');
        return
      }
      this.materialRecordInfo.operatorTime = new Date();
      this.materialRecordInfo.operatorId = this.vuex_user.userId;
      this.materialRecordInfo.operatorName = this.vuex_user.userName;
      this.materialRecordInfo.taskId = this.curTaskInfo.taskId;
      this.materialRecordInfo.depletionMethod = this.currentType + 1;
      this.materialRecordInfo.workstationId = this.vuex_workstation.workstationId;
      const res = this.$u.api.addMaterialusagerecord(this.materialRecordInfo)
      if (res.code === 200) {
        this.materialRecordInfo.quantity = 0;
        this.materialRecordInfo.materialBatchNumber = '';
        this.$u.toast('上报成功');
        this.getIssusLinebyWorkorderCodes();
      }
    },
    async shiftTask(tid) {
      const res = await this.$u.api.getTaskInfo({
        taskId: tid,
      })
      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);
      }
    },
    async changeStatus(taskId, status) {
      const res = await this.$u.api.changeStatus({
        taskId: taskId,
        status: status,
        attr1: this.stopReason
      })
      if (res.code === 200) {
        this.$u.toast('变更成功');
        uni.$emit('taskStatusChanged'); //任务状态变更
      }
    },
    quantityChanged() {
      this.feedbackForm.quantity = this.feedbackForm.quantityQualify + this.feedbackForm.quantityUnqualify;
    },
    doFeedback() {
      this.feedbackForms = []
      this.tableSelectData.forEach((item) => {
        this.feedbackForms.push({
          ...item,
          workstationId: item.workstationId,
          userName: this.vuex_user.userName,
          taskId: item.taskId,
          feedbackChannel: 'PAD',
          quantity: item.quantity,
          quantityQualify: 0,
          quantityUnqualify: 0,
          nickName: this.vuex_user.nickName
        })
      })
      this.open = true;
    },
    cancel() {
      this.open = false;
    },
    async feedback() {
      for (const item of this.feedbackForms) {
        if (['NORMARL', 'PAUSE'].includes(item.status) && item.quantityUnqualify === 0) {
          this.$u.toast('请切换任务状态为开始作业后再进行报工！');
          return;
        }
        if (item.quantityQualify === 0 && item.quantityUnqualify === 0) {
          this.$u.toast('请填写合格/不合格产品数量！');
          return;
        }
      }

      for (const item of this.feedbackForms) {
        const res = await this.$u.api.feedback({
          taskId: item.taskId,
          taskCode: item.taskCode,
          quantityFeedback: item.quantity,
          quantityQualified: item.quantityQualify,
          quantityUnquanlified: item.quantityUnqualify,
          userName: this.vuex_user.userName,
          feedbackType: item.feedbackType,
          routeId: item.routeId,
          routeCode: item.routeCode,
          processId: item.processId,
          processCode: item.processCode,
          processName: item.processName,
          itemId: item.itemId,
          itemCode: item.itemCode,
          itemName: item.itemName,
          workstationId: item.workstationId,
          workstationCode: item.workstationCode,
          workstationName: item.workstationName,
          startTime: item.startTime
        });
        this.getTaskList();

        if (res.code === 200) {
          this.$u.toast('上报成功');
        }
      }
    }
  }
}
</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%;
}

.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;
  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 - 80rpx - 500rpx);
    min-height: 400rpx;
    border: 1px solid rgb(232, 232, 232);
  }

  .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;
  }
}
</style>
