<template>
  <div>
    <div>
      <p-card title="盘点执行">
        <a-row>
          <a-col :span="12">
            <div>
              <p-grid-form ref="formTarget" :disable-item="disableItem" :items="formItems"> </p-grid-form>
            </div>
            <a-row :gutter="[16, 16]" style="margin: 20px">
              <a-col :span="12">
                <viewer :images="photo" class="imgPhoto">
                  <template v-for="(src, index) in photo">
                    <!-- <div :class="index > 0 ? 'oneclass' : 'othersclass'"  :key="index" > -->
                    <img :class="index > 0 ? 'oneclass' : 'othersclass'" :src="src" :key="index" />
                    <!-- </div> -->
                  </template>
                </viewer>
                <!-- <img width="50%" height="100px" src="/img/盒子.png" alt="" /> -->
              </a-col>
              <a-col :span="12">
                <p-button :size="size" @click="changeNum(-10)" class="group-btn-b"> -10 </p-button>
                <p-button :size="size" @click="changeNum(-1)" style="margin-left: 15px" class="group-btn-b">
                  -1
                </p-button>
                <p-button :size="size" @click="changeNum(10)" style="margin-left: 15px" class="group-btn-b">
                  +10
                </p-button>
                <p-button :size="size" @click="changeNum(1)" style="margin-left: 15px" class="group-btn-b">
                  +1
                </p-button>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="12">
            <div class="num">{{ detailInfo.doNum }}/{{ detailInfo.totalNum  }}</div>
            <img-list :list="boxList"></img-list>
            <div>
              <img
                width="40%"
                height="80px"
                v-for="(item, i) in locationList"
                :style="item.isPower == 1 ? (i == 0 ? { background: '#f11010' } : { background: '#2de680' }) : {}"
                :key="i"
                alt=""
                class="border-btn-a"
              />
            </div>
          </a-col>
        </a-row>

        <div class="group-btn">
          {{ checkName }}
          <p-checkbox @change="onChange" v-model="checkValue" style="margin-left: 20px"></p-checkbox>
          <p-button type="primary" @click="containerLocationReturn" class="group-btn-a" style="margin-left: 300px">
            货架归还
          </p-button>
          <p-button type="primary" @click="planReceived" class="group-btn-a"> 任务领取 </p-button>
          <p-button type="primary" @click="checkConfirm" class="group-btn-a"> 盘点确认 </p-button>
          <!-- <p-button type="primary" @click="checkStation" class="group-btn-a"> 验证工作站 </p-button> -->
        </div>
        <a slot="extra" href="#">
          <!-- <p-button type="primary"> 重新分配 </p-button>
          <p-button type="primary" style="margin-left: 10px"> 货位修改 </p-button>
          <p-button type="primary" style="margin-left: 10px"> 可用检查 </p-button> -->
        </a>
      </p-card>
    </div>
  </div>
</template>
<script>
import { formItems } from './js/config'
import imgList from '../../components/imagelist'
import { receiveCheckTask, returnGoodsShelf, uploadCheckInfo, checkWorkStationNo, getGoodsInfo, getGoodsOwners, getLots, queryImages,getCheckProcess } from './api'
import { SetStation } from '@/views/util/stationmixin.js'
import { setStationCode, getStationCode,REGEX_letter } from '@/views/util'
import 'viewerjs/dist/viewer.css'
import VueViewer from 'v-viewer'
import Vue from 'vue'
Vue.use(VueViewer)
const options = [
  { value: 'jack', title: 'jack' },
  { value: 'lucy', title: 'lucy' }
]
const imgs = ['/img/盒子.png', '/img/盒子1.png', '/img/盒子2.png']

export default {
  components: {
    'img-list': imgList
  },
  name: 'executionTask',
  mixins: [ SetStation ],
  data() {
    return {
      formItems: formItems(this),
      disableItem: [ 'pieceBarcode', 'itemName', 'manufacturerId', '', 'pieceUom', 'containerNO', 'manufacturerLotNum', 'containerLocation'],
      photo: ['/img/盒子.png', '/img/盒子1.png', '/img/盒子2.png'], //预览图
      checkAll: true,
      size: 'large',
      options,
      checkName: ' 自动领取',
      test: '请上架商品',
      number: '1/3',
      Checkbox: '0',
      checkValue: false,
      timer: null,
      boxList: {},
      locationList: [],
      type: 0, //复盘次数
      stationNo: '',
      isNewAdd: 2, // 1为盘点新增，2为盘点
      wareGoodsId: '',
      setIntervalNum: 0 ,
      detailInfo: {
        doNum: 0,
        totalNum: 0,
      },
      timerId: null
    }
  },
  created() {
    this.getTaskProgress()
    const obj = {
      aa: '1',
      bb: '2',
      cc: '2',
      dd: '2',
      ee: '2',
    }
    Object.keys(obj).reduce((total,currentValue,index) => {
      // console.log(total,'currentValue1111111111111111111111')
      // console.log(currentValue,'reduce')
      // console.log(index,'index')
      
    },[])
    Object.keys(obj).map(item => {
      // console.log(item,'currentValue')

    })
  },
  destroyed(){
        clearInterval(this.timer);
        this.setIntervalNum = 0
  },
  watch: {
    checkValue: {
      handler(val) {
        if(val) {
          const stationNo = this.$refs.formTarget.form.getFieldsValue().stationNo
          if(!stationNo) {
            this.$message.error('请输入站台号')
          }
          this.setTimeTask()
        } else {
          clearInterval(this.timer)
          this.setIntervalNum = 0
        }
      }
    },
    wareGoodsId: {
      handler(val) {
        const wareGoodsId = val
        queryImages({ wareGoodsId }).then(res => {
          if(res.success) {
            if(res.data&&res.data.length> 0) {
              this.photo = res.data
            } else {
              this.photo = imgs
            }
          }
        })
      },
    }
  },
  methods: {
    setTimeTask() {
      this.timer = setInterval(() => {
            this.setIntervalNum++
            this.planReceived('watch')
            // if(this.setIntervalNum > 0) {
            //   this.setIntervalNum++
            // }
      },2000)
    },
    getTaskProgress() {
      // this.timerId = setInterval(() => {
      //   getCheckProcess({}).then(res => {
      //     if(res.success) {
      //       this.detailInfo = {
      //         doNum: res.data.doNum,
      //         totalNum: res.data.totalNum,
      //       }
      //     }
      //   })
      // },2000)
    },
    onChange(e) {
      console.log(`checked = ${e.target.checked}`)
    },
    focusFun(data) {
      if(!data) return
      this.$nextTick(() => {
        if(data == 'completeDate') {
          this.$refs.completeDate.$el.querySelector('input').focus();
        } else {
          this.$refs.formTarget.$refs.list.$refs[data].$el.querySelector('input').focus();
        }

      })


    },
    handleChange(value) {
      console.log(`selected ${value}`)
    },
    checkStation(event) {
      const { stationNo, pieceBarcode, cargoOwnerName, manufacturerLotNum, ownerId } = this.$refs.formTarget.form.getFieldsValue()
      if(event =='stationNo') {
        if(!stationNo) {
          this.$message.error('请输入站台号')
          return
        }
        // if (!REGEX_letter(stationNo)) {
        //   this.$message.error('请输入大写字母！')
        //   return
        // }
        const params = {
          stationNo: stationNo
        }
        checkWorkStationNo(params).then(res => {
          if (res.success) {
            this.stationNo = stationNo
            setStationCode(stationNo)
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      } else if(event =='pieceBarcode') {
        if(!pieceBarcode) {
          this.$message.error('请输入商品条码')
          return
        }
        getGoodsInfo({ pieceBarcode }).then(res => {
          const { itemName, lotNoFactName:manufacturerId, pieceUom} = res.data
          console.log(itemName,'goodsNamegoodsNamegoodsName')
          this.$refs.formTarget.form.setFieldsValue({itemName, manufacturerId, pieceUom})
        })

      } else if(event =='cargoOwnerName') {
        getGoodsOwners({pageSize:15,pageNum:1}).then(res => {
          const ownerId = res.data.list[0].id
          const cargoOwnerName = res.data.list[0].cargoOwnerName
          const itemName = res.data.list[0].itemName
          this.$refs.formTarget.form.setFieldsValue({ownerId, cargoOwnerName, itemName})

        })
      } else if(event =='manufacturerLotNum') {
        getLots({pageSize:15,pageNum:1, pieceBarcode, ownerId}).then(res => {
          console.log(res)
        })
      }


    },
    planReceived(data) {
      console.log(this.$refs.formTarget.form)
      const stationNo = this.$refs.formTarget.form.getFieldsValue().stationNo
      if(!stationNo && data!=='watch') {
        this.$message.error('请输入站台号')
      }
      const params = {
        stationNo: stationNo
      }
      receiveCheckTask(params).then(res => {
        if (res.success) {
          this.type = res.data.result.type
          console.log('执行任务领取')
          if(!res.data.result.bizPropertyId) {
            this.$refs.formTarget.form.enableItem([ 'pieceBarcode', 'cargoOwnerName', 'manufacturerLotNum'])
            this.isNewAdd = 1
          }
          if(res.data.result) {
            this.wareGoodsId = res.data.result?.wareGoodsId
            this.focusFun('firstCount')
            clearInterval(this.timer)
          }
          console.log(this.disableItem)

          this.$refs.formTarget.form.setFieldsValue(res.data.result ? res.data.result : {})
          this.boxList = this.arraySort(res.data.palletLocationList)
          
          this.locationList = res.data.locationList
          // this.$message.success(res.message)
        } else {
          if(data== 'watch' && this.setIntervalNum < 2) {
            this.$message.error(res.message)
          } else if(data != 'watch') {
            this.$message.error(res.message)
          }
        }
      })
    },
    checkConfirm() {
      const {checkTaskNo ,firstCount, stationNo, containerNo, id, bizPropertyId, itemName} = this.$refs.formTarget.form.getFieldsValue()
      const { type, isNewAdd }  = this
      // console.log(firstCount)
      // console.log(bizPropertyId,'goodsIdgoodsId')
      const status = itemName ? ((firstCount === '' || firstCount < 0)? true : false) : false
      if (status) {
        this.$message.error('盘点数量不能小于0')
        return
      }
      const params = {
        checkTaskNo,
        containerNo,
        stationNo,
        type,
        id,
        isNewAdd,
        ...this.$refs.formTarget.form.getFieldsValue()
      }
      // console.log(params,'params');
      // params [type == 1 ? 'firstCount' : 'secondCount'] = firstCount
      uploadCheckInfo(params).then(res => {
        if (res.success) {
          // this.photo = imgs
          this.$message.success(res.message)
          const taskData = res.data?.result
          if(JSON.stringify(taskData) == '{}' || (taskData??'') == '') {
            this.$refs.formTarget.form.resetFields()
            this.$refs.formTarget.form.setFieldsValue({stationNo: getStationCode()})
            this.boxList = {}
            this.locationList = []
            this.photo = imgs
            this.wareGoodsId = ''
            this.setTimeTask()
          } else {
            // this.checkValue = false
            this.boxList = this.arraySort(res.data.palletLocationList)
            res.data.result.firstCount = ''
            this.$refs.formTarget.form.setFieldsValue(res.data.result)
            this.type = res.data.result.type
            this.focusFun('firstCount')
            this.wareGoodsId = res.data.result?.wareGoodsId
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    containerLocationReturn() {
      const containerNo = this.$refs.formTarget.form.getFieldsValue().containerNo
      const stationNo = this.$refs.formTarget.form.getFieldsValue().stationNo
      const params = {
        containerNo,
        stationNo
      }
      returnGoodsShelf(params).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.boxList = {}
          this.locationList = []
          this.$refs.formTarget.form.resetFields()
          this.$refs.formTarget.form.setFieldsValue({stationNo: getStationCode()})
        } else {
          this.$message.error(res.message)
          
        }
      })
    },
    changeNum(num) {
      let Nownum = this.$refs.formTarget.form.getFieldsValue().firstCount
      this.$refs.formTarget.form.setFieldsValue({ firstCount: Number(Nownum) + Number(num) })
    },
    onChange(e) {
      console.log(e)
      console.log(this.checkValue)
      if (e.target.checked) {
        this.Checkbox = '1'
      } else {
        this.Checkbox = '0'
      }
    },
    //获取箱子顺序
    arraySort(list) {
      console.log(list)
      let data = {
        1: [],
        2: [],
        3: [],
        4: [],
      }
      if (!list) {
        return
      }
      list.forEach((i) => {
        data[i.layer].push(i)
      })
      console.log(data)
      // this.boxList = data
      return data
    },
    //  arraySort(list) {
    //   //方法1
    //   // const Oddarr = []
    //   // const evenArr = []
    //   // const arr = []
    //   // list.reverse()
    //   // list.map((t,i) => {
    //   //   if((i+1)%2 == 0) {
    //   //     evenArr.push(t)
    //   //   } else {
    //   //     Oddarr.push(t)
    //   //   }
    //   // })
    //   // for (let i = 0; i < Oddarr.length; i++) { 
    //   //   arr.push(evenArr[i])
    //   //   arr.push(Oddarr[i])
    //   // }
    //   // console.log(arr,'OddarrOddarrOddarr')
    //   // return arr



    //   //方法2
    //   let arr = list
    //   let a = null
    //   let b = null
    //   let len = arr.length
    //   let n = Math.floor(len/2)
    //   for (let i = 0; i < n; i++) {
    //     if(i%2 ==0) {
    //       a = arr[i]
    //       arr[i] = arr[len-(i+1)-1]
    //       arr[len-(i+1)-1] = a
    //     } else {
    //       b = arr[i]
    //       arr[i] = arr[len-i]
    //       arr[len-i] = b
    //     }
    //   }
    //   return arr

    //   //方法2
    //   // let arr = [1,2,3,4,5,6,7,8]
    //   // let len = arr.length
    //   // let n = len/2
    //   // let m =  Math.floor(n/2)
    //   // let a;
    //   // let b;
    //   // for (let i = 0; i < m; i++) {
    //   //   a = arr[i]
    //   //   b = arr[i + 1]
    //   //   arr[i] = arr [len - 2 - (i*2)]
    //   //   arr[i + 1] = arr [len - 1 - (i*2)]
    //   //   arr [len - 2 - (i*2)] = a
    //   //   arr [len - 1 - (i*2)] = b
    //   // }
    //   // console.log(arr)

    // }
  }
}
</script>
<style lang="less">
.group-btn {
  // float: right;
  //  border: 1px solid #409eff;
  margin: 15px;
  font-weight: bold;
  font-size: 15px;
  .group-btn-a {
    margin-left: 40px;
    height: 50px;
    width: 150px;
  }
}
.oneclass {
  display: none;
}
.othersclass {
  // background: url('./components/img/盒子6.jpg');
  background-repeat:no-repeat;
  height: 100%;
  background-size: contain;
}
.imgPhoto {
  height: 138px;
  overflow: hidden;
  text-align: center;
}
.ant-input.ant-input-disabled {
  color: #108ee9;
}
.border-btn-a {
  height: 50px;
  width: 200px;
  margin-top: 10px;
  margin-left: 80px;
  background-color: #e4e7ed;
}
.group-btn-b {
  width: 50px;
}
.select-a {
  .select-b {
    margin-top: 15px;
    width: 180px;
  }
}
.testName {
  font-weight: bold;
  font-size: 30px;
  color: red;
}
.num {
  font-weight: bold;
  font-size: 35px;
}
</style>
