<script>
import {getPartValue, removeScanLabel, saveScanLabel, scanLabel} from "../../../api/production/generateReport";
import dayjs from "dayjs";
import {Decimal} from "decimal.js";
import {getPhotoAddressData} from "../../../api/pad";

export default {
  name:"scanForm",
  props:{
    detail:{
      type: [Object],
      required: true
    },
    scanFlag:{
      type: Boolean,
      default:false,
    },
    allNum:{
      type:Number,
      default: 0,
    },
    notifyQty:{
      type:Number,
      default:0,
    },
    isReport:{
      type:Boolean,
      default:false,
    }
  },
  computed:{
    flag:{
      get(){
        return this.scanFlag;
      },
      set(val){
        this.$emit("update:scanFlag",val)
      }
    },
    total:{
      get(){
        return this.scanLabelDetailList.reduce((pre, cur) => {
          return pre + new Decimal(cur.scanQty).toNumber()
        }, 0);
      },
      set(val) {
        // this.scanLabelDetailList = v
      }
    },
    totalNum:{
      get(){
        return this.scanLabelDetailList.length;
      },
      set(val) {
        // this.scanLabelDetailList = v
      }
    },
    totalWeight:{
      get(){
        return this.scanLabelDetailList.reduce((pre, cur) => {
          if (cur.weight){
            return pre + new Decimal(cur.weight).toNumber()
          }
          return pre
        }, 0);
      },
      set(val) {

      }
    }
  },
  data(){
    return{
      model:{
        flag:"",
        label:'',
      },
      partValue:0,
      scanLabelDetailList:[],
      photoDatas:[],
      num:1,
      exportDataStandard: {
        "通知单号": "delNotifyNo",
        "通知单序号号": "delNotifyItemNo",
        "产品编码": "partNo",
        "数量": "scanQty",
        "类型": "scanType",
        "JOB NO.": "seqNo",
        "操作员": "createBy",
        "扫描时间": "createData",
      },
      exportName: "发货扫描"+dayjs().format("YYYYMMDDHHmmss"),
    }
  },
  methods:{
    removeScanLabel(row){
      removeScanLabel(row).then(({data})=>{
        if (data && data.code === 0){
          this.$message.success(data.msg)
          this.scanLabel();
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    getFocus(refName){
      this.$refs[refName].focus()
    },
    openScanDialog(){
      this.getFocus('focusInput')
      // 获取当前part的 标准标签数量
      let params={
        site:this.detail.site,
        partNo:this.detail.partNo
      }
      getPartValue(params).then(({data})=>{
        if (data && data.code === 0){
          this.partValue = data.data;
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    scanLabel(){
      let paramsScan={
        site:this.detail.site,
        delNotifyNo: this.detail.delNotifyNo,
        delNotifyItemNo: this.detail.delNotifyItemNo,
      }
      scanLabel(paramsScan).then(({data})=>{
        if (data && data.code === 0){
          this.scanLabelDetailList = data.rows;
          this.$emit("changeAllNum",this.total)
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
      this.getPhoto();
    },
    scanLabelEnter(){
      if (this.total > this.notifyQty){
        this.$message.warning("扫描累计数量不允许超过要求发货数量")
        return;
      }
      let arr = this.model.label.split(";");
      if (arr.length < 5){//site;partNo;qty;seqNo;printId
        if (!arr[3]){
          this.$message.warning("标签jobNo为空")
          return;
        }
        if (!arr[2] || arr[2] === '0'){
          this.$message.warning("数量不存在或是0")
          return;
        }
        if (!arr[1]){
          this.$message.warning("产品编码为空")
          return;
        }
        if (!arr[0]){
          this.$message.warning("site编码为空")
          return;
        }
        this.$message.warning("标签格式错误")
        return
      }
      if (arr[0] !== this.detail.site || arr[1] !== this.detail.partNo){
        this.$message.warning(`产品不匹配或每袋/每卷数量未维护`)
        return;
      }
      if (this.partValue===0){
        this.$message.warning(`每袋/每卷数量未维护`)
        return;
      }
      // if (this.model.flag !== 'Y' && this.partValue != arr[2]){
      //   this.$message.warning(`标签数量与标准袋装数量不匹配`)
      //   return;
      // }
      if (new Decimal(this.total).add(new Decimal(arr[2])).toNumber()> this.notifyQty){
        this.$message.warning("扫描累计数量不允许超过要求发货数量")
        return;
      }// 保存数据 通知单数量:this.detail.notifyQty
      let params={
        site:this.detail.site,
        delNotifyNo: this.detail.delNotifyNo,
        delNotifyItemNo: this.detail.delNotifyItemNo,
        scanQty:arr[2],
        scanType:parseInt(arr[2]) !== this.partValue?'零散数量':'标准数量',
        seqNo:arr[3],
        printId:arr[4]?arr[4]:'',
        weight:arr[5],
        createBy:this.$store.state.user.name,
        createData:dayjs().format("YYYY-MM-DD")
      }
      saveScanLabel(params).then(({data})=>{
        if (data && data.code === 0){
          this.$message.success(data.msg)
          this.scanLabel();
        }else {
          this.$message.warning(data.msg)
        }
        // 重置标签
        this.model.flag = "";
        this.model.label = '';
      }).catch((error)=>{
        this.$message.warning(error)
        this.model.flag = "";
        this.model.label = '';
      })
    },
    closeScanDialog(){
      this.model = {
        label: '',
        flag: '',
      }
      if (this.isReport === false && this.total < this.notifyQty){
        this.$message.warning("扫描数量未达到通知单数量")
        // this.$alert("扫描数量未达到通知单数量", '提示', {
        //   confirmButtonText: '确定',
        // });
      }
      this.scanLabelDetailList = [];
    },
    getPhoto(){
      let params = {
        site:this.detail.site,
        partNo:this.detail.partNo,
      }
      this.photoDatas = [];
      this.num=1;
      getPhotoAddressData(params).then(({data}) => {
        this.photoDatas = data.rows;
        if(this.photoDatas.length===0){
          setTimeout(() => {
            this.$alert('该物料没有上传图片！', '错误', {
              confirmButtonText: '确定'
            })
          }, 500);
          return false;
        }
      })
    },
    lastPicture(){
      this.$refs.photoCarousel.prev();
    },
    nextPicture(){
      this.$refs.photoCarousel.next();
    },
    changePhoto(index){
      this.num=index+1;
    }
  }

}
</script>

<template>
<div>
  <el-dialog
    title="出货扫描" v-drag
    :visible.sync="flag"
    width="80%"
    @open="scanLabel"
    @close="closeScanDialog" @opened="openScanDialog">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;">
      <div style="width: 60%">
        <el-form :model="model" :inline="true" label-position="top">
          <!--      <el-form-item label=" ">-->
          <!--        <el-select v-model="model.flag" clearable>-->
          <!--          <el-option value="" label="标准袋数"></el-option>-->
          <!--          <el-option value="Y" label="零数袋"></el-option>-->
          <!--        </el-select>-->
          <!--      </el-form-item>-->
          <el-form-item label="标签" style="width: 200px " v-if="!isReport">
            <el-input ref="focusInput" v-model="model.label" @keyup.enter.native="scanLabelEnter"></el-input>
          </el-form-item>
          <el-form-item label="合计">
            <el-input-number disabled :controls="false" style="margin-top: -5px;text-align: right" v-model="total"></el-input-number>
          </el-form-item>
          <el-form-item label="袋数">
            <el-input-number disabled :controls="false" style="margin-top: -5px;text-align: right" v-model="totalNum"></el-input-number>
          </el-form-item>
          <el-form-item label="总重量">
            <el-input-number disabled :controls="false" style="margin-top: -5px;text-align: right" v-model="totalWeight"></el-input-number>
          </el-form-item>
          <el-form-item label=" " v-if="isReport">
            <download-excel
              :fields="exportDataStandard"
              :data="scanLabelDetailList.map(item=>{item.partNo=detail.partNo;return item;})"
              type="xlsx"
              :name="exportName"
              worksheet="导出信息"
              class="el-button el-button--primary el-button--medium">
              导出
            </download-excel>
          </el-form-item>
        </el-form>
        <el-table :data="scanLabelDetailList" stripe border height="500" highlight-current-row>
          <el-table-column label="操作" align="center" v-if="!isReport">
            <template slot-scope="{row,$index}">
              <el-link style="cursor:pointer;" @click="removeScanLabel(row)">删除</el-link>
            </template>
          </el-table-column>
          <el-table-column label="通知单号" min-width="120px" header-align="center" align="center" show-overflow-tooltip prop="delNotifyNo"/>
          <el-table-column label="通知单号序号" min-width="100px" header-align="center" align="left" show-overflow-tooltip prop="delNotifyItemNo"/>
          <el-table-column label="产品编码" min-width="100px" header-align="center" show-overflow-tooltip>
            <template slot-scope="{row,$index}">
              {{detail.partNo}}
            </template>
          </el-table-column>
          <el-table-column label="数量" min-width="60px" header-align="center" align="center" show-overflow-tooltip prop="scanQty"/>
          <el-table-column label="重量" min-width="60px" header-align="center" align="center" show-overflow-tooltip prop="weight"/>
          <el-table-column label="类型" min-width="100px" header-align="center" align="center" show-overflow-tooltip prop="scanType"/>
          <el-table-column label="JOB NO." min-width="100px" header-align="center" align="left" show-overflow-tooltip prop="seqNo"/>
          <el-table-column label="序号" min-width="100px" header-align="center" align="left" show-overflow-tooltip prop="printId"/>
          <el-table-column label="操作员" min-width="100px" header-align="center" align="left" show-overflow-tooltip prop="createBy"/>
          <el-table-column label="扫描时间" min-width="100px" header-align="center" align="center" show-overflow-tooltip prop="createData"/>
        </el-table>
      </div>
      <div class="photo" style="width: 40%;padding-left: 10px">
        <el-form label-position="top" size="medium">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产品编码：">
                <el-input v-model="detail.partNo" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item style="height: 30px;" label=" ">
                <div>
                  <el-button @click="lastPicture()" style="height: 30px;width: 80px" type="primary">
                    上一张
                  </el-button>
                  <el-button @click="nextPicture()" style="height: 30px;width: 80px" type="primary">
                    下一张
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="18">
              <el-form-item :label="`文件名(${photoDatas[this.num-1]?this.num:0}/${this.photoDatas.length})`">
                <el-input :value="photoDatas[this.num-1]?photoDatas[this.num-1].attaFileNameDb:''" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div id="padPhoto" style="text-align: center;width: 100%;vertical-align:middle;margin-top: 5px">
          <el-carousel height="400px" @change="changePhoto" ref="photoCarousel" :autoplay="false" indicator-position="none" :interval="5000" arrow="never">
            <el-carousel-item v-for="(item,index) in this.photoDatas" :key="index">
              <img style="max-width:100%;height: 400px;object-fit: cover;object-position: center center" :src="$store.state.user.padSopUrl+item.attaFileNameDb">
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </div>
    <div style="height: 20px"></div>
  </el-dialog>
</div>
</template>

<style scoped>
.el-input-number /deep/ .el-input__inner{
  text-align: left;
  margin-top: 5px;
  padding-right: 5px !important;
  padding-left: 5px !important;
}

.photo .el-form-item--medium /deep/ .el-form-item__label {
  font-size: 16px;
  line-height: 30px;
  height: 30px;
}

.photo .el-form-item--medium /deep/ .el-form-item__content {
  margin-bottom: 5px;
}

.photo .el-form-item--medium /deep/ .el-form-item__content .el-button {
  width: 80px;
  height: 30px;
}

.photo .el-form-item--medium /deep/ .el-form-item__content .el-input .el-input__inner {
  font-size: 16px;
  line-height: 30px;
  height: 30px !important;
}
</style>
