<template>
  <!-- 盒条件-条件关联 -->
  <div id="topDiv">
    <van-nav-bar
        title="条件关联"
        left-text=""
        left-arrow
        @click-left="$router.go(-1)"
        style="background-color: rgba(0, 105, 83, 1)"
    >
      <template #right>
        {{ $store.state.user.name }}
      </template>
    </van-nav-bar>
  </div>

  <div id="centerDiv">
    <van-cell-group>
      <van-cell :title="$route.meta.type" :value="manualAssociationList.parentCode" style="height: 100px"/>
      <van-cell :title="$route.meta.smokeList" :value="manualAssociationList.code.length">
        {{ manualAssociationList.code.length }}/{{ qrBrand.boxNum != null ? qrBrand.boxNum : 50 }}
      </van-cell>
      <van-cell title="卷烟信息" :value="qrBrand.cgtName"/>
    </van-cell-group>
  </div>
  <van-list class="list" :style="{height:listHeight + 'px',overflow:'auto'}">
    <van-cell v-for="codex in manualAssociationList.code" v-show="manualAssociationList != null">
      <van-row v-if="errorList.indexOf(codex) != -1" class="li" style="color: #FF0000">
        <van-col span="24">{{ codex }}</van-col>

      </van-row>
      <van-row class="li" v-else>
        <van-col span="24">{{ codex }}</van-col>

      </van-row>
    </van-cell>
  </van-list>

  <van-row id="scrapButton">
    <van-button :class="relevanceButton ? 'btn_disabled' : 'btn_enable'" :disabled="relevanceButton"
                @click="relevanceSendButton">完成关联
    </van-button>
  </van-row>
  <van-popup v-model:show="showShiftDetail" round position="bottom">
    <van-picker :columns="shiftDetail" :columns-field-names="{ text: 'shiftDetailName' }"  @cancel="showShiftDetail = false" @confirm="onConfirmShiftDetail" />
  </van-popup>
  <van-popup v-model:show="showClassGroup" round position="bottom">
    <van-picker :columns="classGroup" :columns-field-names="{ text: 'name' }" @cancel="showClassGroup = false" @confirm="onConfirmClassGroup" />
  </van-popup>
  <van-popup v-model:show="show" :close-on-popstate="false"  :close-on-click-overlay="false" :style="{ borderRadius: '10px', width: '90%', height: '30% ' }">
    <div style="position: relative;height: 100%;">
      <van-form @submit="onSubmit">
        <div class="pop">
          <span class="headerSize">班次班组确认</span>
          <div class="border"></div>
          <van-cell-group inset>
            <div class="kuang">
              <van-field v-model="barPieceClassGroupName" is-link readonly label="生产班组" placeholder=""
                         @click="showClassGroup = true" style="width: 100%;" :rules="[{ required: true, message: '请选择生产班组' }]" />
            </div>
            <div class="kuang" style="margin-top: 10px;">
              <van-field v-model="barPieceProductShiftDetailName" is-link readonly label="生产班次" placeholder=""
                         @click="showShiftDetail = true" style="width: 100%;"  :rules="[{ required: true, message: '请选择生产班次' }]"/>
            </div>
          </van-cell-group>
        </div>
        <div class="bottom">
          <van-button class="btn" type="default" native-type="submit">保存</van-button>
          <div></div>
          <van-button class="btn" @click="cancel">取消</van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<script>
import {NavBar, CellGroup, Cell, List, Button, Dialog, Sticky, Col, Row, Notify, Popup, Form, Field, Picker} from "vant";
import {related, relatedBefore} from "@/api/qrcode/relation/qrDiscardCode";
import {getQrcodeInfoByCode, getQrcodeInsByCode} from "@/api/qrcode/relation/qrcodeIns";
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";
import {QrCodeUtil} from "@/api/qrcode/device/brand/brand";
import {getClassGroup, getShiftDetail} from "@/api/qrcode/smoke/exportQrCode";
import {getStringByTwo} from "@/utils/transition";
import {encryptAES} from "@/utils/cryptoJS ";

export default {
  name: "cartonBox",
  components: {
    [NavBar.name]: NavBar,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [List.name]: List,
    [Popup.name]: Popup,
    [Form.name]: Form,
    [Picker.name]: Picker,
    [Field.name]: Field,
    [Button.name]: Button,
    [Dialog.Component.name]: Dialog.Component,
    [Sticky.name]: Sticky,
    [Col.name]: Col,
    [Row.name]: Row,
    [Notify.Component.name]: Notify.Component,
  },
  mounted() {
    const _this = this;
    this.initHeight();
    this.getShiftDetail()
    this.getClassGroup()
    this.getSchedule()
  },
  data() {
    return {
      //弹出框所需数据
      //班次
      showShiftDetail: false,
      shiftDetail: [],

      //班组
      showClassGroup: false,
      classGroup: [],
      show: false,
      listHeight: '',
      isDisabled: true,
      manualAssociationList: {
        parentCode: '',
        code: [],
        errorCode: "",
        type: null,
        barPieceClassGroupName:"",
        barPieceClassGroupCoed:"",
        barPieceProductShiftDetailCode:"",
        barPieceProductShiftDetailName:"",
      },
      //班次班组
      barPieceClassGroupName:"",
      barPieceClassGroupCoed:"",
      barPieceProductShiftDetailName:"",
      barPieceProductShiftDetailCode:"",
      errorList: [],
      packageBoxNum: {
        strip: null, // 条
        piece: null, // 件
      },
      qrBrand: {
        code: null,//二维码数据
        typeCode: null,
        typeName: null,
        cgtName: null,
        cgtCode: null,
        pkgNum: null,// 盒条关联数之比
        boxNum: null,// 条件关联数之比
        qrBrand: null
      },

      forbidden: 0,
      showArr: [],
      dialogPromise: true,
    }
  },
  computed: {
    relevanceButton() {
      if (this.forbidden == 1) {
        return true;
      }
      if (this.manualAssociationList.parentCode != null && this.manualAssociationList.parentCode != '') {
        return this.manualAssociationList.code.length == this.packageBoxNum.piece ? false : true
      }
      return true
    }
  },
  methods: {
    //班次信息
    getShiftDetail(){
      getShiftDetail().then(res=>{
        this.shiftDetail = res.data
      })
    },
    //班组信息
    getClassGroup(){
      getClassGroup().then(res=>{
        this.classGroup = res.data
      })
      this.show = true
    },
    //获取缓存排程
    getSchedule(){
      this.barPieceProductShiftDetailName = localStorage.getItem('barPieceProductShiftDetailName')
      this.barPieceProductShiftDetailCode = localStorage.getItem('barPieceProductShiftDetailCode')
      this.barPieceClassGroupName = localStorage.getItem('barPieceClassGroupName')
      this.barPieceClassGroupCoed = localStorage.getItem('barPieceClassGroupCoed')
    },

    //班次默认回调
    onConfirmShiftDetail(value) {
      // 处理确认事件，将选中的索引值赋给fieldValue，并隐藏下拉框
      this.barPieceProductShiftDetailName = value.shiftDetailName;
      this.barPieceProductShiftDetailCode = value.shiftDetailCode;
      localStorage.setItem('barPieceProductShiftDetailName', value.shiftDetailName);
      localStorage.setItem('barPieceProductShiftDetailCode', value.shiftDetailCode);
      this.showShiftDetail = false
    },
    //班组默认回调
    onConfirmClassGroup(value) {
      this.barPieceClassGroupName = value.name;
      this.barPieceClassGroupCoed = value.code;
      localStorage.setItem('barPieceClassGroupName', value.name);
      localStorage.setItem('barPieceClassGroupCoed', value.code);
      this.showClassGroup = false
    },

    //确认回调
    onSubmit (value) {
      this.show = false
      this.$nativeQRCode.setCallBackFun((res) => {
        // 通过二维码获取卷烟信息信息
        let qrCode = getStringByTwo(res)
        this.getQrBrandByCode(qrCode);
      });
      this.$nativeQRCode.setStatusBarColor("#006953", "white");
      ScanOverlay.show('请扫描二维码')
      // this.getQrBrandByCode("HTTPS://T2DC.CN/99.1000.1/AD32Sf50f2037000169010280752062202410140016460168A00296NUANE5NSCAKMKIMC36D3P216")
      // this.getQrBrandByCode("HTTPS://T2DC.CN/99.1000.1/AC30150750037000169010280752062202404290016460168A01297CCBF1F6636OQI9I9VHV4PA00")
      // setTimeout(()=>{
      //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC20150710025V12GTGRVRWVWMELBCDVY029")
      //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC20150710025V12GTGRVRWVWMELBCDVY030")
        // this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AD22VX2JG0025V12GTGRVRWVWMELBCDVY030")
      // },1000)
    },
    //班次班组取消按钮
    cancel() {
      this.show = false
      this.$router.go(-1)
    },
    // 初始化高度
    initHeight() {
      this.$nextTick(() => {
        // 屏幕宽度
        let windowW = document.documentElement.clientHeight;
        let topDivH = document.getElementById("topDiv").offsetHeight;
        let centerDivH = document.getElementById("centerDiv").offsetHeight;
        let scrapButtonH = document.getElementById("scrapButton").offsetHeight;
        //scrapButton
        this.listHeight = windowW - topDivH - centerDivH - scrapButtonH - 60;
        console.log(windowW)

      });
    },
    //二维码获取卷烟信息卷烟信息获取
    getQrBrandByCode(qrcode) {
      ScanOverlay.hide()
      QrCodeUtil({"qrcode": qrcode}).then(res => {
        if (res.data.typeCode != null && res.data.typeCode != 20) {
          // if (qrcode.length != '105' && qrcode.length != '96' && qrcode.substring(0, 2) != 91) {
          if (qrcode.length != '105' && qrcode.length != '96') {
            Notify({type: 'warning', message: '请扫描正确烟码', duration: 1500});
            return;
          }
        }
        if (!this.qrBrand.cgtCode) {
          this.qrBrand = res.data;
          // 获取盒条比值
          this.packageBoxNum.strip = this.qrBrand.pkgNum;
          // 获取条件比值
          this.packageBoxNum.piece = this.qrBrand.boxNum;
          this.onScanQrCode(res.data);
        } else {
          if (this.qrBrand.cgtCode == res.data.cgtCode) {
            this.onScanQrCode(res.data)
            // return;
          } else {
            if (res.data.typeCode == 30 && this.manualAssociationList.code.length==0){
              this.qrBrand = res.data;
              // 获取盒条比值
              this.packageBoxNum.strip = this.qrBrand.pkgNum;
              // 获取条件比值
              this.packageBoxNum.piece = this.qrBrand.boxNum;
              this.onScanQrCode(res.data)
            }else {
              // 卷烟信息不同
              Notify({type: 'warning', message: '卷烟信息不同', duration: 1500});
            }
          }
        }
        // }
      })
    },

    //扫描二维码
    onScanQrCode(qrCode) {
      if (qrCode.cgtCode == null) {
        Notify({type: 'warning', message: '请扫描正确烟码', duration: 1500});
        return
      }
      if (qrCode.typeCode == '30') {
        let qrcode = qrCode.code
        getQrcodeInsByCode({qrcode}).then(r=>{
          if (r.data.status == 30){
            Notify({type: 'warning', message: '该件烟是报废烟码，无法再次关联', duration: 1500});
            this.isClearBrand()
            return
          }
          if (r.data.status == 40){
            Notify({type: 'warning', message: '该件烟已有关联关系，无法再次关联', duration: 1500});
            this.isClearBrand()
            return
          }
          if (r.data.bTaskId != null){
            Notify({type: 'warning', message: '该烟码已迁移，无法再次关联', duration: 1500});
            this.isClearBrand()
            return
          }
          if (r.data.operUserId == 60){
            Notify({type: 'warning', message: '该烟码已出库，无法再次关联', duration: 1500});
            this.isClearBrand()
            return
          }
          if (r.data.unregistered == 5){
            Notify({type: 'warning', message: '该烟是黑户烟，无法再次关联，请先做解绑操作', duration: 1500});
            this.isClearBrand()
            return
          }
          this.manualAssociationList.parentCode = qrCode.code
        }).catch(()=>{
          this.manualAssociationList.parentCode = qrCode.code
          Notify({type: 'warning', message: '', duration:1});
        })
        // this.manualAssociationList.parentCode = qrCode.code
      } else if (qrCode.typeCode == '20') {

        if (this.manualAssociationList.code.indexOf(qrCode.code) > -1) {
          Dialog.alert({title: "重复扫码"});

        } else if (this.isMoreNum()) {
          let qrcode = qrCode.code
          getQrcodeInsByCode({qrcode}).then(res => {
            if (res.data.unregistered == 5){
              Notify({type: 'warning', message: '该烟是黑户烟，无法再次关联，请先做解绑操作', duration: 1500});
              this.isClearBrand()
              return
            }
            if (res.data.parentCode != null && res.data.parentCode != '') {
              let pCode = res.data.parentCode
              getQrcodeInsByCode({"qrcode": pCode}).then(r => {
                if (r.data.status == 30) {
                  Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且关联的件是报废烟码，无法再次关联', duration: 1500});
                }else if (r.data.operUserId == 60){
                  Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且关联的件已出库，无法再次操作', duration: 1500});
                }else if (r.data.bTaskId != null) {
                  Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且已迁移，无法再次操作', duration: 1500});
                }else if(r.data.status == 40){
                  Notify({type: 'warning', message: '该条烟有条件关联关系，无法再次关联', duration: 1500});
                }else {
                  if (qrCode.pkgNum == null){
                    qrCode.pkgNum = 0
                  }
                  if (res.data.brandCode.startsWith("AD")){
                    if (this.dialogPromise){
                      this.showArr.unshift(qrCode.code)
                      let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                      this.manualAssociationList.code = arr
                    }
                  } else if (this.dialogPromise && res.data.childrenList.length == qrCode.pkgNum){
                    this.showArr.unshift(qrCode.code)
                    let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                    this.manualAssociationList.code = arr
                  }else {
                    this.dialogPromise = false
                    Dialog.confirm({title: "条码关联关系不完整,无法关联",}).then(() => {
                      this.dialogPromise = true
                    });
                  }
                }
              })
            }else if (res.data.brandCode != null && res.data.brandCode.startsWith("AD")){
              if (this.dialogPromise){
                this.showArr.unshift(qrCode.code)
                let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                this.manualAssociationList.code = arr
              }
            } else if (res.code == 200 && res.data.childrenList.length == qrCode.pkgNum) {
              if (this.dialogPromise){
                this.showArr.unshift(qrCode.code)
                let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                this.manualAssociationList.code = arr
              }
            } else {
              this.dialogPromise = false
              Dialog.confirm({title: "盒条关联关系不完整,无法关联",}).then(() => {
                this.dialogPromise = true
              });
            }
          }).catch(() => {
            Notify({type: 'warning', message: '', duration: 1});
            if (this.qrBrand.cgtCode.startsWith("AD")){
              this.showArr.unshift(qrCode.code)
              let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
              this.manualAssociationList.code = arr
              return
            }
            if (qrCode.qrBrand.boxQuantity == 0){
              this.showArr.unshift(qrCode.code)
              let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
              this.manualAssociationList.code = arr
            }else {
              this.dialogPromise = false
              Dialog.confirm({title: "盒条关联关系不完整,无法关联",}).then(() => {
                this.dialogPromise = true
              })
            }
          })
        } else {
          Dialog.alert({title: "超过扫码数量"});
        }
      } else if (qrCode.typeCode == '10') {
        // 件吗或者其他
        Notify({type: 'warning', message: '此为盒码', duration: 1500});
      } else {
        Notify({type: 'warning', message: '请扫描正确烟码', duration: 1500});
      }

    },

    //判断是否超过数量
    isMoreNum() {
      if (this.manualAssociationList.code.length < this.packageBoxNum.piece) return true;
      return false;
    },

    // 完成关联 发送
    relevanceSendButton() {
      this.manualAssociationList.barPieceClassGroupName = this.barPieceClassGroupName
      this.manualAssociationList.barPieceProductShiftDetailName = this.barPieceProductShiftDetailName
      this.manualAssociationList.type = 2
      this.forbidden = 1
      ScanOverlay.show('关联中')
      relatedBefore(this.manualAssociationList).then(res => {
        if (res.code == 200 && res.data != null) {
          this.errorList = res.data
          this.manualAssociationList.errorCode = res.data
          Dialog.confirm({
            message: '二维码中存在关联数据,提交后会对老关联关系进行解绑,是否提交',
          }).then(() => {
            this.forbidden = 0
            ScanOverlay.hide()
            related(this.manualAssociationList).then((res) => {
              if (res.code == 200) {
                this.forbidden = 0
                this.resetAll()
                Notify({type: 'success', message: '关联成功'});
                ScanOverlay.show('请扫描二维码')
              }
            })
          }).catch(() => {
            this.forbidden = 0
            ScanOverlay.hide()
            Notify({type: 'warning', message: '关联取消', duration: 1500});
          });
        } else if (res.code == 200) {
          this.forbidden = 0
          this.resetAll();
          console.log(this.qrBrand,565656)
          Notify({type: 'success', message: '关联成功'});
          ScanOverlay.show('请扫描二维码')
        }
        // else if (res.code == 500){
        //   this.errorList = res.data
        //   ScanOverlay.hide()
        // }
      }).catch(() => {
        ScanOverlay.hide()
        this.forbidden = 0
      })
    },

    //判断是否要清空品规信息内容
    isClearBrand() {
      if (this.manualAssociationList.code.length === 0 && this.manualAssociationList.parentCode === ''){
        this.resetAll()
      }
    },

    // 重置所有数据
    resetAll() {
      this.manualAssociationList = {
        parentCode: '',
        code: [],
        errorCode: "",
        type: null
      };
      this.errorList = []
      this.showArr = []
      this.packageBoxNum = {
        strip: null, // 条
        piece: null, // 件
      }
      this.qrBrand = {
        code: null,//二维码数据
        typeCode: null,
        typeName: null,
        cgtName: null,
        cgtCode: null,
        pkgNum: null,// 盒条关联数之比
        boxNum: null,// 条件关联数之比
        qrBrand: null
      }
    }
  },
}
</script>

<style scoped lang="scss">
//:deep(.van-cell-group) {
//  width: 660px;
//  margin: auto;
//  margin-top: 20px;
//  background: none;
//}
.headerSize {
  font-size: 26px;
  font-family: Source Han Sans CN,sans-serif;
  font-weight: bold;
  color: #000000;
  margin-top: 28px;
}

.border {
  margin-top: 12px;
  width: 100%;
  height: 3px;
  background: #C5C5C5;
}
.kuang {
  height: 60px;
  line-height: 60px;
  margin-top: 15px;
}
.bottom {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  height: 79px;
  border-top: 2px solid #C7C7C7;
  display: flex;
  flex-direction: row;
}
.btn {
  width: 50%;
  height: 100%;
  font-size: 22px;
  font-family: Source Han Sans CN,sans-serif;
  font-weight: 500;
  color: #18A487;
}
.pop {
  display: flex;
  flex-direction: column;
  padding: 0 20px;
}


.list {
  width: 660px !important;
  margin: auto;
  border-radius: 15px;
}


#scrapButton {
  height: 100px;
  width: 100%;
  position: fixed;
  bottom: 0px;
  padding-top: 20px;

  background: #FFFFFF;
}

.btn_disabled {
  width: 100%;
  height: 80px;
  background: #AFD4CC;
  border-radius: 20px;
  color: rgba(230, 230, 230, 1);
}

.btn_enable {
  width: 100%;
  height: 80px;
  background: rgba(33, 143, 120, 0.9);
  border-radius: 20px;
  color: rgba(230, 230, 230, 1);
}
:deep(.van-cell-group) {
  width: 100%;
  margin: auto;
  margin-top: 20px;
  background: none;
}

:deep(.van-cell-group .van-cell:nth-of-type(1)) {
  height: 70px;
  border-radius: 15px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
  line-height: 40px;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.van-cell-group .van-cell:nth-of-type(1) .van-cell__title) {
  flex: .3;
}

:deep(.van-cell-group .van-cell:nth-of-type(1) .van-cell__value) {
  display: block;
  line-height: 30px;
  text-align: left;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
}

:deep(.van-cell-group .van-cell:nth-of-type(2)) {
  height: 104px;
  border-radius: 15px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
  line-height: 104px;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.van-cell-group .van-cell:nth-of-type(2) .van-cell__value) {
  display: block;
  line-height: 20px;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
}

:deep(.van-cell-group .van-cell:nth-of-type(3)) {
  height: 104px;
  border-radius: 15px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
  line-height: 104px;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.van-cell-group .van-cell:nth-of-type(3) .van-cell__value) {
  display: block;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
}

:deep(.li) {
  height: 127px !important;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
  line-height: 40px;
  padding-top: 20px;
  box-sizing: border-box;
}

:deep(.van-cell:after) {
  border-bottom: 2px solid rgba(231, 231, 231, 1)
}

:deep(.van-nav-bar__right) {
  font-size: 32px;
  font-family: Source Han Sans CN,sans-serif;
  font-weight: 400;
  color: #FFFFFF;
}
</style>
