<template>
  <div>
    <div id="sliao" class="sliao" ref="sliao"></div>
    <SliaoSearch ref="sliaoSearch" @search="search" :workers="workers"/>
    <ZyjhSelectComp id="selectComp" ref="selRef"  @initWorkers="initWorkers" @clear="clear"/>
    <TipsComp />
  </div>
</template>

<script>
import Konva from "konva";
import container from "@/views/zyjhzx/sliao/comps/container";
import drawTitle from "@/views/zyjhzx/sliao/comps/title";
import initSearch from "@/views/zyjhzx/components/search";
import {sljh} from "@/views/zyjhzx/sliao/comps/sljh";
import workers from "@/views/zyjhzx/sliao/comps/person";
import SliaoSearch from "@/views/zyjhzx/components/SliaoSearch.vue";
import liliao from "@/views/zyjhzx/sliao/comps/liliao";
import baifang from "@/views/zyjhzx/sliao/comps/baifang";
import {dict, getBzryByBz, getSljhPgd, getYcldw, shangLiao, shangLiaos} from "@/api/zyjh";
import {getBzryList} from "@/api/sjzx/bzzGL";
import TipsComp from "@/views/zyjhzx/components/TipsComp.vue";
import ZyjhSelectComp from "@/views/zyjhzx/components/SelectComp.vue";
import {EventBus} from "@/event-bus";

export default {
  name:'SLiao',
  components: {ZyjhSelectComp, TipsComp, SliaoSearch},
  data(){
    return {
      title:'上  料  作  业  报  工',
      width:0,
      height:0,
      stage:null,
      layer:null,
      slGroup:null,
      sljhGroup:null,
      drawBaiFang:null,
      ycldwGroup:null,
      canSl:false,
      workerGroup:null,
      getCurrentWorker:null,
      currentDw:null,
      currentDwIndex:-1,
      sljhItemList:[],
      tlt:[],
      dw:[],
      workers:[],
      zt:'11',
      msg:null,
      tipsId:null,
      llist:[],
      selectedJh:[],
      plslflag:false,
      plslList:[],
      getSelectShape:null,
      nonSelectShape:null,
    }
  },
  mounted() {
    Array.prototype.r = function(str){
      const [start,end]=str.split(':').map(Number);
      return this.slice(start, end);
    }
    this.$socket.open()
    this.wsSubscribe()
    this.initKonvaStage();
    this.initTlt()
  },
  created(){
    // window.addEventListener('resize', this.initKonvaStage)
  },
  sockets:{
    zyjhzx(data){
      if (this.deviceId!==data.msg.deviceId&&data.msg.actionType!=='开始报工'){
        return
      }
      //工单号尾号长度
      const djhWhLengh=4
      const tmpList=this.list.filter(item=>item.djh===data.msg.orderNumber||item.djh?.slice(-djhWhLengh)===data.msg.orderNumber)
      if (tmpList.length>1){
        this.list=tmpList
        this.drawSljhItem(tmpList)
        this.$message.warning('短号有重复,请使用全工单号重新派工!!!')
        return
      }
      if(!this.currentDw||this.currentDwIndex===-1){
        this.$message.warning('请选择上料垛位')
        return;
      }

      const currentWorker=this.getCurrentWorker()
      if (!currentWorker){
        this.$message.warning('请选择报工人')
      }
      let index=-1
      let errorFlag=true
      for (const item of this.list) {
        index+=1
        if (item.djh===data.msg.orderNumber||item.djh?.slice(-djhWhLengh)===data.msg.orderNumber){
          item.slycldw=this.currentDw.id
          item.slyclcs=this.dw[this.currentDwIndex].list.length+1
          item.slfkry=currentWorker.userCode
          const data={
            ydjh:item,
            ydid:item.id,
            dwId:this.currentDw.id,
            ceng:this.dw[this.currentDwIndex].list.length+1,
            czbh:item.dcCh,
            pl:item.dcPl,
            fd:item.dcFd,
            kw:item.kw,
            zl:item.zl,
            tlth:item.tzbh,
            wph:item.wpxh,
            wpgg:item.wpgg,
            sljhrq:item.sljhrq,
            qgjhrq:item.qgjhrq,
            wlh:item.slwlh,
            lph:item.sllph,
            nbsbm:item.nbsbm,
            bfr:currentWorker.userCode,
            type:'YCL',
            deviceId:this.deviceId
          }
          shangLiao(data).then(res=>{
            this.list.splice(index,1)
            this.drawSljhItem(this.list)
          })
          errorFlag=false
          break
        }
      }
      if (errorFlag){
        setTimeout(()=>{
          EventBus.$emit('error', {
            msg:'识别失败'
          })
        },3000)
      }
    }
  },
  methods:{
    initTlt(){
      dict({bmlb:'QGKW'}).then(res=>{
        this.tlt=res.data
      })
    },
    wsSubscribe(){
      this.sockets.subscribe('slComplete', data => {
        if(this.plslflag){
          this.plslList.push(data)
          return
        }
        if (this.currentDw&&this.currentDw.id===data.dwId) {
          if (this.slGroup){
            this.slGroup.destroyChildren()
          }
          this.dw[this.currentDwIndex].list.push(data)
          this.drawBaiFang(this.dw[this.currentDwIndex].list)
        }else {
          this.dw[data.dwId].list.push(data)
        }
        this.initYcldw();
        // this.getSelectedShape()
      })
      this.sockets.subscribe('pwComplete', data => {
        this.initYcldw()
      })
      this.sockets.subscribe('tips', data => {

      })
    },
    search(queryParam){
      queryParam.dcch=queryParam.dcCh
      this.selectedJh=[]
      getSljhPgd(queryParam).then(res=>{
        this.sljhItemList=res.data
        this.drawSljhItem(this.sljhItemList.r('0:200'))
      })
    },
    initDwInfo(index,dw){
      console.log(this.selectedJh)
      if(!this.getCurrentWorker()){
        this.$message.warning('请选择报工人员')
        return
      }
      if (this.slGroup){
        this.slGroup.destroyChildren()
      }
      this.canSl=true
      this.currentDw=dw
      this.currentDwIndex=index
      if (this.selectedJh.length>0){
        this.plslflag=true
        const jh=[]
        this.selectedJh.forEach((item,index)=>{
          item.slycldw=dw.id
          item.slyclcs=dw.list.length+index+1
          item.slfkry=this.getCurrentWorker()?.userCode
          const data={
            ydjh:item,
            ydid:item.id,
            dwId:dw.id,
            ceng:item.slyclcs,
            czbh:item.dcCh,
            pl:item.dcPl,
            fd:item.dcFd,
            kw:item.kw,
            zl:item.zl,
            tlth:item.tzbh,
            wph:item.wpxh,
            wpgg:item.wpgg,
            sljhrq:item.sljhrq,
            qgjhrq:item.qgjhrq,
            wlh:item.slwlh,
            lph:item.sllph,
            nbsbm:item.nbsbm,
            bfr:this.getCurrentWorker()?.userCode,
            type:'YCL',
          }
          jh.push(data)
        })

        shangLiaos(jh).then(res=>{
          this.selectedJh=[]
          if (!res.success){
            this.drawSljhItem(this.sljhItemList.r('0:200'))
            return;
          }
          if (this.slGroup){
            this.slGroup.destroyChildren()
          }
          for (const data of this.plslList) {
            if (this.currentDw&&this.currentDw.id===data.dwId) {
              this.dw[this.currentDwIndex].list.push(data)
            }else {
              this.dw[data.dwId].list.push(data)
            }
            this.sljhItemList.forEach((sljh,index)=>{
              if(data.czbh===sljh.dcCh&&data.pl===sljh.dcPl&&data.tlth===sljh.tzbh){
                this.$delete(this.sljhItemList, index);
              }
            })
          }
          this.drawSljhItem(this.sljhItemList.r('0:200'))
          this.plslList=[]
          this.plslflag=false
          this.drawBaiFang(this.dw[this.currentDwIndex].list)
          this.initYcldw();
        })
      }else{
        !!dw&&this.drawBaiFang(dw.list)
      }
    },
    initBaiFang(){
      const {slGroup,handler,bgGroup:slBgGroup}= baifang({width:this.width,height:this.height})
      this.slGroup=slGroup
      this.layer.add(slBgGroup)
      this.drawBaiFang=handler
    },
    drawSljhItem(list){
      this.list=list
      if (this.sljhGroup){
        this.sljhGroup.destroyChildren()
        this.sljhGroup.x(0)
        this.sljhGroup.y(0)
      }
      const itemWith=111;
      const itemHeight=108

      for (let i = 0; i < list.length; i++) {
        const item=list[i];
        const x=(i+1)*5+i*itemWith;
        const qyGroup=new Konva.Group({
          x:x,
          y:10,
          width:itemWith,
          height:itemHeight,
        })
        qyGroup.setAttr('index',i)
        qyGroup.setAttr('item',item)

        let selectShape=null
        let selectedShape=null;
        const setSelectShape=function (shape){
          selectShape=shape
        }

        const _that=this
        qyGroup.on('click touchstart',function (){
          if (_that.currentDw){
            _that.currentDw=null
            _that.currentDwIndex=null
            _that.nonSelectShape()
          }

          if (selectedShape){
            selectedShape.hide()
            selectedShape=null
            _that.selectedJh=_that.selectedJh.filter(it=>it.dcCh!==item.dcCh&&it.dcPl!==item.dcPl&&it.tzbh!==item.tzbh)
            return;
          }
          selectedShape=selectShape
          selectedShape.show()
          _that.selectedJh.push(item)
        })

        const selectObj = new Image();
        selectObj.src = require('@/assets/sliao/selected.png');
        selectObj.onload = function () {
          const shape = new Konva.Image({
            x: itemWith-itemWith*0.30,
            y: 4,
            width: itemWith*0.25,
            height:itemWith*0.25,
            image: this,
            visible:false
          });
          qyGroup.add(shape)
          shape.zIndex(0)
          setSelectShape(shape)
        }

        this.sljhGroup.add(qyGroup)

        const imageObj = new Image();
        imageObj.src = require('@/assets/sliao/sljhItemBg.png');
        imageObj.onload = function () {
          const shape = new Konva.Image({
            x: 0,
            y: 0,
            width: 111,
            height:163,
            image: this,
          });
          qyGroup.add(shape)
          shape.zIndex(0)
        }

        const tlth=new Konva.Text({
          x: 0,
          y: 0,
          width: 111,
          height:34,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.djh
        })
        qyGroup.add(tlth)

        const nameGroup=new Konva.Group({
          x: 3,
          y: 33,
          width: 39,
          height:105,
        })

        const nameImageObj1 = new Image();
        nameImageObj1.src = require('@/assets/sliao/nameBg1.png');
        nameImageObj1.onload = function () {
          const shape = new Konva.Image({
            x: 0,
            y: 0,
            width: 39,
            height:125,
            image: this,
          });
          nameGroup.add(shape)
          shape.zIndex(0)
        }
        qyGroup.add(nameGroup)

        const name1=new Konva.Text({
          x: 0,
          y: 0,
          width: 38,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:'船号'
        })
        nameGroup.add(name1)

        const name2=new Konva.Text({
          x: 0,
          y: 21,
          width: 38,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:'批量'
        })
        nameGroup.add(name2)

        const name3=new Konva.Text({
          x: 0,
          y: 42,
          width: 38,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:'材质'
        })
        nameGroup.add(name3)

        const name4=new Konva.Text({
          x: 0,
          y: 63,
          width: 38,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:'规格'
        })
        nameGroup.add(name4)

        const name5=new Konva.Text({
          x: 0,
          y: 84,
          width: 38,
          height:20,
          fontSize:11,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:'炉批号'
        })
        nameGroup.add(name5)

        const name6=new Konva.Text({
          x: 0,
          y: 105,
          width: 38,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:'备注'
        })
        nameGroup.add(name6)

        const infoGroup=new Konva.Group({
          x: 43,
          y: 33,
          width: 65,
          height:105,
        })
        qyGroup.add(infoGroup)

        const info1=new Konva.Text({
          x: 0,
          y: 0,
          width: 65,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.dcCh
        })
        infoGroup.add(info1)

        const info2=new Konva.Text({
          x: 0,
          y: 21,
          width: 65,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.dcPl
        })
        infoGroup.add(info2)

        const info3=new Konva.Text({
          x: 0,
          y: 43,
          width: 65,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.wpxh
        })
        infoGroup.add(info3)

        const info4=new Konva.Text({
          x: 0,
          y: 62,
          width: 65,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.wpgg
        })
        infoGroup.add(info4)

        const info5=new Konva.Text({
          x: 0,
          y: 84,
          width: 65,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.sllph
        })
        infoGroup.add(info5)

        const info6=new Konva.Text({
          x: 0,
          y: 105,
          width: 65,
          height:20,
          fontSize:12,
          fontStyle:'bold',
          fill:'#fff',
          align:'center',
          verticalAlign:'middle',
          text:item.slbz
        })
        infoGroup.add(info6)

        const _layer=this.layer
        const _sljhGroup=this.sljhGroup;
        let touchingFlag=false;
        const that=this
        let timeout=null
        qyGroup.on('mousedown touchstart',function ({evt}){
          const worker=that.getCurrentWorker();
          if (!that.canSl||!worker){
            return
          }

          const {clientX:_x,clientY:_y}=evt
          let x=_x,y=_y
          if (evt.type==='touchstart'){
            x=evt.targetTouches[0].clientX
            y=evt.targetTouches[0].clientY
          }
          touchingFlag=true;
          const _that=this
          timeout=setTimeout(()=>{
            const movingFlag=_sljhGroup.isDragging()
            if (!movingFlag){
              if (touchingFlag){
                _sljhGroup.draggable(false)
                const tmpGroup=_that.clone();
                tmpGroup.x(x-10)
                tmpGroup.y(y-10)
                _layer.add(tmpGroup)
                tmpGroup.draggable(true)
                tmpGroup.dragBoundFunc(function (pos){
                  return{...pos}
                })
                tmpGroup.startDrag()
                _that.visible(false)

                tmpGroup.on('dragend',function (){
                  const {x:thisX,y:thisY}=this.absolutePosition()
                  const {x,y}=that.slGroup.absolutePosition()
                  const maxX=x+that.width*0.4-20
                  const maxY=y+that.height*0.8-20
                  if(thisX>=x&&thisY>=y&&thisX<=maxX&&thisY<=maxY){
                    const item=this.getAttr('item')
                    item.slycldw=that.currentDw.id
                    item.slyclcs=that.dw[that.currentDwIndex].list.length+1
                    item.slfkry=that.getCurrentWorker()?.userCode
                    const data={
                      ydjh:item,
                      ydid:item.id,
                      dwId:that.currentDw.id,
                      ceng:that.dw[that.currentDwIndex].list.length+1,
                      czbh:item.dcCh,
                      pl:item.dcPl,
                      fd:item.dcFd,
                      kw:item.kw,
                      zl:item.zl,
                      tlth:item.tzbh,
                      wph:item.wpxh,
                      wpgg:item.wpgg,
                      sljhrq:item.sljhrq,
                      qgjhrq:item.qgjhrq,
                      wlh:item.slwlh,
                      lph:item.sllph,
                      nbsbm:item.nbsbm,
                      bfr:that.getCurrentWorker()?.userCode,
                      type:'YCL'
                    }

                    shangLiao(data).then(res=>{})

                    this.remove()

                    that.sljhItemList.splice(this.getAttr('index'),1)
                    that.sljhGroup.destroyChildren()
                    that.drawSljhItem(that.sljhItemList.r('0:200'))
                  }else{
                    this.remove()
                    _that.visible(true)
                  }
                  _sljhGroup.draggable(true)
                })
              }
            }
          },500)
        })

        qyGroup.on('mouseup touchend',function (){
          clearTimeout(timeout)
          touchingFlag=false;
          this.draggable(false)
          _sljhGroup.draggable(true)
        })

      }
    },
    initYcldw(){
      getYcldw({type:'ycl'}).then(res=>{
        if(this.ycldwGroup){
          this.ycldwGroup.destroyChildren()
        }
        this.dw=res.data
        const {container,getCurrentDw,getSelectShape,nonSelectShape}= liliao(this.width,this.height,this.dw,this.initDwInfo)
        const group=container()
        this.getSelectShape=getSelectShape
        this.nonSelectShape=nonSelectShape
        this.ycldwGroup=group
        this.layer.add(group)
      })
    },
    initWorkers(bzType){
      if (this.workerGroup){
        this.workerGroup.destroyChildren()
      }else{
        const {container,getCurrentWorker,person}=workers(this.width,this.height,this.workers)
        this.person=person
        const {bgGroup,group}=container()
        this.workerGroup=group
        this.getCurrentWorker=getCurrentWorker
        this.layer.add(bgGroup)
      }
      this.workerGroup.x(0)
      this.workerGroup.y(0)
      getBzryByBz({zyq:this.$route.query.zyq,zt:bzType}).then(res=>{
        this.workers=res.data
        for (let i=0;i<res.data.length;i++){
          const item=res.data[i]
          const worker=this.person(i,item)
          this.workerGroup.add(worker)
        }
      })
    },
    initKonvaStage(){
      this.width=this.$refs.sliao.clientWidth
      this.height=this.$refs.sliao.clientHeight
      const {stage,layer}=container(this.width,this.height,'sliao')
      this.stage=stage
      this.layer=layer


      const title=drawTitle(this.width,this.height,this.title)
      this.layer.add(title)

      const {group}=initSearch()
      this.layer.add(group)

      this.search(this.$refs.sliaoSearch.getQueryParam())

      const {layer:sljhLayer,group:sljhGroup}=sljh(this.width,this.height)
      this.sljhGroup=sljhGroup
      this.stage.add(sljhLayer)

      this.initWorkers(this.$refs.selRef.getData().bzType)

      this.initYcldw()

      this.initBaiFang()
    },
    clear(){
      this.stage.remove()
    }
  }
}

</script>

<style>
#selectComp {
  width:50%;
  height: auto;
  position: absolute;
  top:10px;
  left:20px;
  border: none;
  margin: 0;
}

.vxe-button{
  top: 0px;
  width: 80px;
  height: 22px !important;
}

.vxe-input{
  width: 115px;
}

#searchPl {
  position: absolute;
  top:45px;
  left:15px;
  border: none;
  margin: 0;
}

#searchPl input{
  border: none;
  background: none;
  outline: none;
}

#menu {
  display: none;
  position: absolute;
  width: 100px;
  height: 180px;
  background-color: white;
  box-shadow: 0 0 5px grey;
  border-radius: 3px;
  overflow-y: auto;
}

#menu button {
  width: 100%;
  background-color: white;
  border: none;
  margin: 0;
  font-size: 12px;
  padding: 10px;
}

#menu button:hover {
  background-color: lightgray;
}

#sliao {
  background: #ddd;
  overflow: hidden;
  width: 100%;
  height: 100vh;
  aspect-ratio: 16/9;
}
</style>
