// pages/install/install.js
const {
  usedMaterial,
  getUsedMaterialInfo,
  deleteUsedRocerd,
  getWarehouseList,
  saveWarehouse,
  saveMaterialSN
} = require('../../../api/api')
const { routeLink } = require("../../../utils/route.js");
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mshow: false,
    title: '逆变器物料条码',
    materialCode: '',
    converterList: [],
    oldConverterList: [],
    oldItemList: [],
    batchCode: '',//批量条码
    showDialog: false,
    tabIndex: '0',
    installArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.entryId = options.projectId;
    this.getWarehouseList()
  },

  onShow() {
    // this.getWarehouseList()
  },

  /** 跳转连续扫码 **/
  goScanCode(e) {
    // console.log(66666, e)
    var that = this;
    var materialType = e.currentTarget.dataset.type;  //1逆变器，3组件
    var nbqSpec = e.currentTarget.dataset.spec;  //规格
    var dataNum = e.currentTarget.dataset.num;  //剩余数量
    var zb = e.currentTarget.dataset.zb;  //自备物料
    var model = e.currentTarget.dataset.model;  //型号
    var spec = '';  //规格
    if(materialType == 1){//1逆变器
      spec = nbqSpec
    }else if(materialType == 3){//1逆变器，3组件
      spec = this.data.productList[this.data.tabIndex].zjMap.model
    }
    if (!that.data.warehouseId) {
      wx.showToast({
        title: '请先选择所属仓库',
        icon: 'none'
      })
      return
    }
    this.setData({
      lxSpec: spec,
      lxMaterialType: materialType,
      lxMaterialModel: model
    })
    console.log('剩余数量', dataNum)
    let warehouseId = that.data.warehouseId?that.data.warehouseId: ''
    routeLink("/pages/scanCode/scanCode?entryId="+ this.data.entryId +"&model="+model+"&warehouseId="+ warehouseId +"&spec="+ spec +"&materialType="+ materialType +"&zb="+ zb +"&num="+dataNum);
  },

  /**批量条码处理**/
  getBatchCode(e){
    var that = this    
    if (!that.data.warehouseId) {
      wx.showToast({
        title: '请先选择所属仓库',
        icon: 'none'
      })
      return
    }
    usedMaterial({
      userId: wx.getStorageSync('userId'),
      entryId: that.data.entryId,
      barcode: that.data.batchCode,
      warehouseId: that.data.warehouseId,
      flag: 1,
      spec: that.data.lxSpec,
      materialType: that.data.lxMaterialType,
      materialModel: that.data.lxMaterialModel,
      projectId: that.data.productList[that.data.tabIndex].projectId
    }).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        that.getUsedMaterialInfo()
      } else {       
        let msgStr = res.msg || res.errMsg        
        wx.showModal({
          title: '',
          content: msgStr,
          showCancel: false,
          complete: (res) => {            
            if (res.confirm) {
              that.getUsedMaterialInfo()
            }
          }
        })
        // Dialog.alert({      
        //   message: msgStr, 
        // });
      }
    })
    // console.log('批量条码处理', this.data.batchCode)
  },

  /**
   * 
   * 
   * 单独扫码
   * 
   * @param {*} e 
   */
  scanCode(e) {
    var that = this;
    var materialType = e.currentTarget.dataset.type;  //1逆变器，3组件
    var nbqspec = e.currentTarget.dataset.spec;  //规格
    var materialModel = e.currentTarget.dataset.model;  //型号
    var spec = '';  //规格
    if(materialType == 1){//1逆变器
      spec = nbqspec
    }else if(materialType == 3){//1逆变器，3组件
      spec = this.data.productList[this.data.tabIndex].zjMap.model
    }
    if (!that.data.warehouseId) {
      wx.showToast({
        title: '请先选择所属仓库',
        icon: 'none'
      })
      return
    }
    // 只允许从相机扫码
    wx.showLoading({
      title: "扫码查询中"
    })
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {        
        let result =  res.result.split(',');
        if(result.length>1){
          result = result[0]
        }else{
          if(materialType =='1'){//逆变器
            result = result[0].substring(0,16)
          }else{//组件
            result = result[0]
          }
        }
        console.log('扫码结果', res, result)
        usedMaterial({
          userId: wx.getStorageSync('userId'),
          entryId: that.data.entryId,
          barcode: result.trim(),
          warehouseId: that.data.warehouseId,
          flag: 1,
          spec,
          materialType,
          materialModel
        }).then((res) => {
          wx.hideLoading()
          if (res.code == 200) {
            that.getUsedMaterialInfo()
          } else {
            wx.showModal({
              title: '',
              content: res.msg || res.errMsg,
              showCancel: false,
              complete: (res) => {}
            })
            // wx.showToast({
            //   title: res.msg || res.errMsg,
            //   icon: 'none'
            // })
          }
        })
      },
      fail(res) {
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        })
      }
    })
  },  

  /**
   * 
   * 获取仓库信息
   * 
   */
  getWarehouseList() {
    getWarehouseList({
      userId: wx.getStorageSync('userId')
    }).then((res) => {
      if (res.code == 200) {
        var warehourseList = []
        for (let i = 0; i < res.data.length; i++) {
          const element = res.data[i];
          warehourseList.push(element.columns)
        }
        this.setData({
          warehourseList: warehourseList
        })
      }

      //只有一个仓库时,默认选择这个仓库
      if (this.data.warehourseList.length == 1) {
        saveWarehouse({
          entryId: this.data.entryId,
          warehouseId: this.data.warehourseList[0].id,
        }).then((res) => {
          wx.hideLoading()
          if (res.code == 200) {
            this.setData({
              warehourseName: this.data.warehourseList[0].name,
              warehouseId: this.data.warehourseList[0].id,
            })
          } else {
            this.setData({
              warehourseName: "",
              warehouseId: "",
            })
            wx.showToast({
              title: '选择失败',
              icon: "none"
            })
          }
        })
      }
      this.getUsedMaterialInfo()
    })
  },


  /**
   * 
   *  获取使用物料列表
   * 
   * @param {*} e 
   */
  getUsedMaterialInfo(e) {    
    getUsedMaterialInfo({
      entryId: this.data.entryId,
    }).then((res) => {
      var componentList = []; //组件
      var converterList = []; //逆变器
      var cagesList = []; //并网箱
      var supportList = []; //支架
      if (res.code == 200) {
        res.data.materialEntryList = JSON.parse(res.data.materialEntryList)
        if (res.data.warehouseId) {
          this.data.warehourseList.forEach(element => {
            if (element.id == res.data.warehouseId) {
              this.setData({
                warehourseName: element.name,
                warehouseId: res.data.warehouseId
              })
            }
          });
        }
        this.setData({
          productList: JSON.parse(res.data.projectSettingList)
        })
        // console.log(9999, res.data.materialEntryList, JSON.parse(res.data.projectSettingList))
        if (res.data.materialEntryList.length > 0) {//有安装数据
          res.data.materialEntryList.forEach(element => {
            if (element.type == "组件") {
              componentList.push(element)
            } else if (element.type == "逆变器") {
              converterList.push(element)
            } else if (element.type == "并网箱") {
              cagesList.push(element)
            } else if (element.type == "支架") {
              supportList.push(element)
            }
          });

          var list = [];
          componentList.forEach(element => {
            var pos = list.findIndex((res) => {
              return res.materialId == element.materialId && res.projectId == element.projectId
            })
            if (pos == -1) {
              element.itemList = [JSON.parse(JSON.stringify(element))]
              list.push(element)
            } else {
              list[pos].itemList.push(element)
            }
          });

          var list1 = [];
          converterList.forEach(element => {
            var pos = list1.findIndex((res) => {
              return res.materialId == element.materialId && res.projectId == element.projectId
            })
            if (pos == -1) {
              element.itemList = [JSON.parse(JSON.stringify(element))]
              list1.push(element)
            } else {
              list1[pos].itemList.push(element)
            }
          });
          
          //保留输入的数据          
          let oldItemList = this.data.oldItemList;
          if(list1.length>0 && oldItemList.length>0){
            list1.forEach((item,index)=>{
              item.itemList.forEach((item2,index2)=>{
                oldItemList.forEach((itm, index3)=>{
                  if(item2.id === itm.id && item2.projectId === itm.projectId){
                    item2.sn = itm.sn
                    item2.yzCode = itm.yzCode
                  }
                })
              })              
            })            
          }             
          this.setData({
            componentList: list,
            converterList: list1,
            cagesList: cagesList,
            supportList: supportList,            
            // nbqList: JSON.parse(res.data.nbqMap),
            // zjMap: JSON.parse(res.data.zjMap)
          })
          // console.log(5555, this.data.converterList)
        } else {
          this.setData({
            componentList: [],
            converterList: [],
            cagesList: [],
            supportList: [],            
            // nbqList: JSON.parse(res.data.nbqMap),
            // zjMap: JSON.parse(res.data.zjMap)
          })
        }
        let installArr = []
        this.data.productList.forEach(pItim=>{
          installArr.push({
            projectId: pItim.projectId,
            componentList: [],
            converterList: [],
            cagesList: [],
            supportList: []
          })
        })
        installArr.forEach(pItim=>{
          //组件
          this.data.componentList.forEach(zjItem=>{
            if(zjItem.itemList){
              zjItem.itemList.forEach(item=>{
                if(pItim.projectId == item.projectId){
                  pItim.componentList.push(item)
                }
              })
            }else{
              if(pItim.projectId == zjItem.projectId){
                pItim.componentList.push(zjItem)
              }
            }
          })
          //逆变器
          this.data.converterList.forEach(nbqItem=>{
            if(pItim.projectId == nbqItem.projectId){
              pItim.converterList.push(nbqItem)
            }
            // if(nbqItem.itemList){
            //   nbqItem.itemList.forEach(item=>{
            //     if(pItim.projectId == item.projectId){
            //       pItim.converterList.push(item)
            //     }
            //   })
            // }else{
            //   if(pItim.projectId == nbqItem.projectId){
            //     pItim.converterList.push(nbqItem)
            //   }
            // }
          })
          //并网箱
          this.data.cagesList.forEach(bwxItem=>{
            if(pItim.projectId == bwxItem.projectId){              
              pItim.cagesList.push(bwxItem)
            }
          })
          //支架
          this.data.supportList.forEach(zjItem=>{
            if(pItim.projectId == zjItem.projectId){
              pItim.supportList.push(zjItem)
            }
          })
        })
        this.setData({
          installArr
        })
        
        // console.log(9966999, installArr, this.data.componentList)

      }
    })    
  },


  /**
   * 
   * 删除物料
   * 
   * 
   * @param {*} e 
   */
  deleteUsedRocerd(e) {
    const ids = e.currentTarget.dataset.id
    const oldFlag = e.currentTarget.dataset.oldflag
    const index = e.currentTarget.dataset.index
    const type =  e.currentTarget.dataset.type 
    // console.log(111, index) 
    if (oldFlag == 2) {
      wx.showToast({
        title: '旧物料不可删除',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: '确认删除当前物料？',
      complete: (res) => {
        if (res.cancel) {
          // this.getUsedMaterialInfo()
        }
        if (res.confirm) {
          deleteUsedRocerd({
            ids: ids
          }).then((res) => {
            if (res.code == 200) {
              if(type=='nbq'){
                let oldItemList = this.data.oldItemList;
                if(index>-1){
                  oldItemList.splice(index, 1)
                }
                this.setData({
                  oldItemList
                }) 
              }
              wx.showToast({
                title: '删除成功',
                icon: 'none'
              })
              this.getUsedMaterialInfo()
            } else {
              wx.showToast({
                title: res.errMsg,
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },


  /**
   * 
   * 
   * 添加自用
   * 
   * @param {*} e 
   */
  installOwn(e) {
    if (!this.data.warehouseId) {
      wx.showToast({
        title: '请先选择所属仓库',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/home/pages/installOwn/installOwn?entryId=' + this.data.entryId + "&type=" + e.currentTarget.dataset.type +
        "&warehouseId=" + this.data.warehouseId + '&productId=' + this.data.productList[this.data.tabIndex].projectId,
    })

  },

  /**
   * 
   * 
   * 选择所属仓库
   * 
   * @param {*} e 
   */
  bindWarehourseList(e) {
    const index = e.detail.value
    wx.showLoading({
      title: '保存中',
    })
    saveWarehouse({
      entryId: this.data.entryId,
      warehouseId: this.data.warehourseList[index].id,
    }).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        this.setData({
          warehourseName: this.data.warehourseList[index].name,
          warehouseId: this.data.warehourseList[index].id,
        })
      } else {
        this.setData({
          warehourseName: "",
        })
        wx.showToast({
          title: '选择失败',
          icon: "none"
        })
      }
    })

  },

  /**
   * 
   * 
   * 添加物料
   * 
   * @param {*} e 
   */
  addMaterial(e){
    this.setData({
      mshow: true,
      title: e.currentTarget.dataset.title,
      materialType: e.currentTarget.dataset.type,
      nbqSpec: e.currentTarget.dataset.spec,
    })
  },
  //取消
  onClose() {
    this.setData({
      mshow: false,
      materialCode: ''
    })
  },
  //确认保存物料
  onConfirm(){
    let that = this
    if(this.data.materialCode ==''){
      wx.showToast({
        title: '请输入物料条码',
        icon: 'none'
      })
      return
    }
    if (!that.data.warehouseId) {
      wx.showToast({
        title: '请先选择所属仓库',
        icon: 'none'
      })
      return
    }
    usedMaterial({
      userId: wx.getStorageSync('userId'),
      entryId: that.data.entryId,
      barcode: that.data.materialCode,
      warehouseId: that.data.warehouseId,
      flag: 1,
      spec: that.data.nbqSpec,
      materialType: that.data.materialType
    }).then((res) => {
      wx.hideLoading()
      if (res.code == 200) {
        that.setData({
          mshow: false,
          materialCode: ''
        })
        that.getUsedMaterialInfo()
      } else {
        wx.showToast({
          title: res.msg || res.errMsg,
          icon: 'none'
        })
      }
    })
  },
  //输入SN码/扫码
  snFn(e){
    let that = this
    let way =  e.currentTarget.dataset.way; //录入方式，input：输入，scan：扫码
    let type =  e.currentTarget.dataset.type; //类型，nbqSn：逆变器sn码,sn：通讯棒sn码，
    let cindex = e.currentTarget.dataset.cind; //一级下标
    let index = e.currentTarget.dataset.ind; //二级下标
    if(way =='input'){
      if(type ==='sn'){
        that.setData({
          [`converterList[${cindex}].itemList[${index}].sn`]: e.detail.value.trim()
        })        
      }else if(type==='yzm'){
        that.setData({
          [`converterList[${cindex}].itemList[${index}].yzCode`]: e.detail.value.trim()
        })        
      }else{
        that.setData({
          [`converterList[${cindex}].itemList[${index}].nbqSn`]: e.detail.value.trim()
        })        
      }
      // console.log(98989, this.data.converterList)
    }else if(way =='scan'){
      wx.scanCode({
        onlyFromCamera: true,
        success(res) {
          if(type ==='sn'){
            let result =  res.result.split(',');
            if(result.length>1){
              result = result[0]
            }else{
              result = res.result
            }
            if (!/^[a-zA-Z0-9]+$/.test(result)) {
              wx.showToast({
                title: '条码格式异常，请重新扫码',
                icon: 'none',
                duration: 2000
              })
              return;
            }
            that.setData({
              [`converterList[${cindex}].itemList[${index}].sn`]: result
            })
          }else{
            that.setData({
              [`converterList[${cindex}].itemList[${index}].nbqSn`]: res.result
            })            
          }
        },
        fail(res) {
          wx.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    }
   
    let itemList = []
    this.data.converterList.forEach(item=>{
      item.itemList.forEach(itm=>{
        itemList.push(itm)
      })
    })
    this.setData({
      oldItemList: itemList
    })
    console.log('输入', itemList)
  },
  //保存逆变器
  submit(){
    let that = this
    let list = this.data.converterList
    let itemArr = [];
    try{
      list.forEach(item=>{
        item.itemList.forEach(item2=>{
          itemArr.push({
            entryId: item.entryId,
            materialId: item.materialId,
            barcode: item2.barcode, //物料号
            sn: item2.sn,
            nbqSn: item2.barcode,
            yzCode: item2.yzCode,
            projectId: that.data.productList[that.data.tabIndex].projectId, //产品ID
          })
          if(!item2.barcode || !item2.sn){
            wx.showToast({
              title: '逆变器SN码，通讯棒SN码不能为空',
              icon: 'none'
            })
            throw Error()
          }
          if((item.materialBrand=='固德威'|| item.materialBrand=='爱士惟') && !item2.yzCode){
            wx.showToast({
              title: '请正确填写验证码',
              icon: 'none'
            })
            throw Error()
          }
        })
      })
      // console.log(8989, itemArr)
      // return
      saveMaterialSN({
        userId: wx.getStorageSync('userId'),
        snList: itemArr
      }).then((res) => {
        wx.hideLoading()
        if (res.code == 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
          setTimeout(function () {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.msg || res.errMsg,
            icon: 'none'
          })
        }
      })
    }catch(e) {
      console.log(e)
    }
  },
  //tab切换
  changeTab(e){
    let index = e.currentTarget.dataset.index
    this.setData({
      tabIndex: index
    })
  }
})