<script>
import {
  printShipmentBox,
  removeShipmentBox,
  updateShipmentBox,
  updateShipmentBoxStatus
} from '../../../../api/shipment/box'
import {
  getShipmentRollAllData,
  getShipmentRollDataList, printShipmentRoll,
  removeShipmentRollData,
  saveShipmentRollData
} from '../../../../api/shipment/roll'

import {printShipmentInnerLabel} from '../../label/print_shipment_inner_label'
import {printShipmentBoxLabel} from '../../label/print_shipment_box_label'
import {getWareHouseList} from '../../../../api/material/poReceive'
import {getLocationListForSearch} from '../../../../api/base/normalSearch'
import {endShipment} from '../../../../api/shipment'
import dayjs from 'dayjs'

export default {
  name: 'shipmentBox',
  props:{
    height:{
      type:Number,
      default:300
    },
    dataList:{
      type:Array,
      default:()=>[]
    },
    shipment:{
      type:Object,
      default:()=>{}
    }
  },
  data(){
    return {
      open:false,
      endOpen:false,
      form:{},
      endForm:{
        warehouseId:'',
        locationId:'',
        shipmentDate:'',
      },
      rollDataList:[],
      endDataList:[],
      warehouseList:[],
      locationList:[],
      rules:{
        warehouseId:[{required:true,message:'请选择仓库',trigger:'change'}],
        locationId:[{required:true,message:'请选择库位',trigger:'change'}],
        shipmentDate:[{required:true,message:'请选择出库日期',trigger:'change'}],
      },
    }
  },
  methods:{
    handleAddBox(){
      this.$emit('add',)
    },
    handleScanRoll(row){
      this.form = {...row}
      this.$nextTick(()=>{
        this.$refs.inputRollNo.focus()
      })
      this.getDataList();
      this.open = true;
    },
    getDataList(){
      let params = {
        ...this.form
      }
      getShipmentRollDataList(params).then(({data})=>{
        if (data && data.code === 0){
          this.rollDataList = data.rows
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handleUpdateBoxStatus(row,status){
      let params = {
        ...row
      }
      updateShipmentBoxStatus(params).then(({data})=>{
        if (data && data.code === 0){
          this.$message.success(data.msg)
          if (status === 0){
            this.handlePrint(row)
          }
          this.$emit('refresh')
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handleRemoveBox(row){
      this.$confirm('确定要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        removeShipmentBox(row).then(({data})=>{
          if (data && data.code === 0){
            this.$emit('refresh')
            this.$message.success(data.msg)
          }else {
            this.$message.warning(data.msg)
          }
        }).catch((error)=>{
          this.$message.error(error)
        })
      })
    },
    handleRollScan(e){
      let val = e.target.value.trim();
      if (!val){
        this.$message.warning('请输入条码')
        this.form.rollNo = ''
        return
      }
      let scanRow = val.split('|')
      if (scanRow.length < 4){
        this.$message.warning("二维码格式有误!")
        return
      }
      let params = {
        ...this.form,
        id:null,
        rollNo:scanRow[3],
        createBy:this.$store.state.user.name,
      }
      saveShipmentRollData(params).then(({data})=>{
        if (data && data.code === 0){
          this.$emit('refresh')
          this.$message.success(data.msg)
          // 查询 roll
          this.getDataList();
        }else {
          this.$message.warning(data.msg)
        }
        this.form.rollNo = ''
      }).catch((error)=>{
        this.form.rollNo = ''
        this.$message.error(error)
      })

    },
    handleGetRollDataList(row){
      this.form = {
        ...row,
        openDetail:true,
      }
      this.getDataList();
      this.open = true;
    },
    handleRollRemove(row){
      this.$confirm('确定要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        removeShipmentRollData(row).then(({data})=>{
          if (data && data.code === 0){
            this.$emit('refresh')
            this.getDataList();
            this.$message.success(data.msg)
          }else {
            this.$message.warning(data.msg)
          }
        }).catch((error)=>{
          this.$message.error(error)
        })
      })
    },
    handleEndBox(){
      this.endForm = {
        warehouseId:'',
        locationId:'',
        shipmentDate:'',
      }
      this.getRecordData();
      this.getWareHouseList();
    },
    getRecordData(){
      if (this.dataList.length === 0){
        this.$message.warning('未新增箱子')
        return
      }
      let params = {
        ...this.shipment,
      }
      getShipmentRollAllData(params).then(({data})=>{
        if (data && data.code === 0){
          this.endDataList = data.rows
          this.endOpen = true;
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    endShipment(){
      this.$refs.endForm.validate((valid,obj) => {
        if (valid) {
          let params = {
            ...this.endForm,
            site:this.shipment.site,
            shipmentId:this.shipment.shipmentId,
          }
          endShipment(params).then(({data})=>{
            if (data && data.code === 0){
              this.endOpen = false;
              this.$emit('end')
              this.$message.success(data.msg)
            }else {
              this.$message.warning(data.msg)
            }
          }).catch((error)=>{
            this.$message.error(error)
          })
        }else {
          let i = 0;
          Object.keys(obj).forEach(key => {
            if (i === 0){
              this.$message.warning(obj[key][0].message)
              return
            }
            i++;
          })
        }
      })
    },
    getWareHouseList(){
      let params = {
        site:this.$store.state.user.site
      }
      getWareHouseList(params).then(({data})=>{
        if (data && data.code === 0){
          this.warehouseList = data.rows
          if (this.warehouseList.length > 0){
            this.endForm.warehouseId = this.warehouseList[0].wareHouseId
          }
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    getLocationListForSearch(){
      let params={
        site:this.$store.state.user.site,
        warehouseId:this.endForm.warehouseId,
        active:'Y'
      }
      this.locationList = []
      getLocationListForSearch(params).then(({data})=>{
        if (data && data.code === 0){
          this.locationList = data.rows
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    handlePrint(row){
      this.printBoxLabel(row);
    },
    printBoxLabel(row){
      printShipmentBox(row).then(({data})=>{
        if (data && data.code === 0){
          let arr = data.rows.map((item)=>{
            item.printType = 'boxLabel'
            item.productionDate = `${dayjs(item.productionDate).format("YYYYMMDD")}`
            item.shipDate = `${dayjs(item.shipDate).format("YYYY-MM-DD")}`
            item.boxNo = `${dayjs(row.createDate).format("YYMMDDHHmmss")}${(row.boxNo+'').padStart(3,'0')}`
            return item
          })
          // printShipmentBoxLabel(arr);
          this.printRollLabel(row,arr);
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    printRollLabel(row,packList){
      printShipmentRoll(row).then(({data})=>{
        if (data && data.code === 0){
          let arr = [...packList];
          let arrs = data.rows.map(item=>{
            item.printType = 'innerBoxLabel'
            item.productionDate = `${dayjs(item.productionDate).format("YYYYMMDD")}`
            return item
          })
          for (let i = 0; i < arrs.length; i++) {
            arr.push(arrs[i])
          }
          printShipmentBoxLabel(arr);
          // printShipmentInnerLabel(arr);
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    }
  },
  watch:{
    "endForm.warehouseId"(newVal,oldVal){
      if (newVal && newVal !== oldVal){
        this.endForm.locationId = '';
        this.getLocationListForSearch()
      }
    }
  }

}
</script>

<template>
  <div>
    <div style="display: flex;justify-content: space-between;">
      <div><el-button type="primary" @click="handleAddBox">新增箱子</el-button></div>
      <div><el-button type="primary" @click="handleEndBox">最终出库</el-button></div>
    </div>
    <el-table :data="dataList" style="width: 100%" border :height="height">
      <el-table-column prop="boxNoStr" label="箱号" width="200" header-align="center" align="left"></el-table-column>
      <el-table-column prop="partNo" label="物料编码" width="100" header-align="center" align="left"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" header-align="center" align="center"></el-table-column>
      <el-table-column prop="createBy" label="录入人" width="100" header-align="center" align="left"></el-table-column>
      <el-table-column prop="createDate" label="录入时间" width="200" header-align="center" align="center"></el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-link @click="handleScanRoll(scope.row)" v-if="scope.row.status==='未封箱'">扫描</el-link>
          <el-link v-if="scope.row.status==='未封箱'" @click="handleUpdateBoxStatus(scope.row,0)">封箱</el-link>
          <el-link v-if="scope.row.status==='已封箱'" @click="handleUpdateBoxStatus(scope.row,1)">解封箱</el-link>
          <el-link v-if="scope.row.status==='未封箱'" @click="handleRemoveBox(scope.row)">删除</el-link>
          <el-link @click="handleGetRollDataList(scope.row)">查看</el-link>
          <el-link v-if="scope.row.status==='已封箱'" @click="handlePrint(scope.row)">补打</el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="扫描" :visible.sync="open" v-drag :close-on-click-modal="false" append-to-body width="1000px">
      <el-form :model="form" label-width="100px" label-position="top" >
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item label="发货ID">
              <el-input v-model="form.shipmentId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="箱号">
              <el-input v-model="form.boxNoStr" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="装箱数量">
              <el-input-number :controls="false" style="width: 100%" :value="rollDataList.length" disabled></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="请扫描">
              <el-input v-model="form.rollNo" :disabled="form.openDetail" ref="inputRollNo" @keyup.enter.native="handleRollScan" placeholder="请输入扫描的条码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="已扫描列表">
              <el-table :data="rollDataList" border :height="200">
                <el-table-column width="60" label="操作" align="center" v-if="!form.openDetail">
                  <template slot-scope="scope">
                    <el-link @click="handleRollRemove(scope.row)">删除</el-link>
                  </template>
                </el-table-column>
                <el-table-column prop="partNo" width="100" header-align="center" label="物料编码"></el-table-column>
                <el-table-column prop="partDesc" width="200" header-align="center" label="物料名称"></el-table-column>
                <el-table-column prop="rollNo" width="100" header-align="center" label="卷号"></el-table-column>
                <el-table-column prop="rollQty" width="60" header-align="center" align="right" label="数量"></el-table-column>
                <el-table-column prop="batchNo" width="60" header-align="center" label="批号"></el-table-column>
                <el-table-column prop="ref" width="60" header-align="center" align="left" label="WD"></el-table-column>
                <el-table-column prop="manufacturerTime" width="150" header-align="center" align="center" label="生产日期"></el-table-column>
                <el-table-column prop="expirationDate" width="150" header-align="center" align="center" label="失效日期"></el-table-column>
                <el-table-column prop="locationId" width="100" header-align="center" align="center" label="库位"></el-table-column>
                <el-table-column prop="createBy" width="100" header-align="center" label="Created By"></el-table-column>
                <el-table-column prop="createTime" width="150" header-align="center" align="center" label="Created Time"></el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-footer style="height: 20px"></el-footer>
    </el-dialog>

    <el-dialog title="最终出库" :visible.sync="endOpen" v-drag :close-on-click-modal="false" append-to-body width="800px">
      <el-form :model="endForm" :rules="rules" ref="endForm" label-width="100px" label-position="top" >
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item label="仓库" prop="warehouseId" :show-message="false">
              <el-select v-model="endForm.warehouseId" style="width: 100%;">
                <el-option :value="i.wareHouseId" :label="i.wareHouseName" v-for="i in warehouseList" :key="i.menuId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="库位" prop="locationId" :show-message="false">
              <el-select v-model="endForm.locationId" style="width: 100%;">
                <el-option :value="i.locationId" :label="i.locationName" v-for="i in locationList" :key="i.locationId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="出库日期" prop="shipmentDate" :show-message="false">
              <el-date-picker
                style="width: 100%"
                v-model="endForm.shipmentDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="8">
            <el-form-item label=" ">
              <div style="float: right;"><el-button type="primary" @click="endShipment">最终出库</el-button></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="已扫描信息汇总">
              <el-table :data="endDataList" border :height="200">
                <el-table-column prop="partNo" min-width="100" header-align="center" label="物料编码"></el-table-column>
                <el-table-column prop="partDesc" min-width="200" header-align="center" label="物料描述"></el-table-column>
                <el-table-column prop="total" min-width="100" header-align="center" align="right" label="总数量"></el-table-column>
                <el-table-column prop="totalBox" min-width="100" header-align="center" align="right" label="总箱数"></el-table-column>
                <el-table-column prop="totalRoll" min-width="100" header-align="center" align="right" label="总卷数"></el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-footer style="height: 20px"></el-footer>
    </el-dialog>
  </div>
</template>

<style scoped>

/deep/ .el-form-item--medium .el-form-item__content{
  height: auto;
}
</style>
