const app = getApp(),
  Api = require("../../../../utils/util.js");
  const { API_MONIT_URL,API_BASE_URL,UP_MONIT_IMG } = require('../../../../api/api')
Page({
  data: {
    API_MONIT_URL: API_MONIT_URL,
    API_BASE_URL: API_BASE_URL,
    UP_MONIT_IMG: UP_MONIT_IMG,
    currentTab: 0,
    tab: ['服务反馈', '物料信息', '基本信息'],   
    measuresList: [],
    measures: '',
    stationName: '',
    category: '',
    categoryList: ['电表箱', '支架', '并网箱', '组件','逆变器'],
    applianceBrand: '',
    applianceBarcode: '',
    typeList: ['保内', '保外'],   
    backSay: '',
    mileage: '',
    imgName1: [],
    brandList: [],//设备品牌
    useFitting: [],
    applyFitting: [],
    servTypeList: [],
    serviceTypeName: ''
  },
  // 点击切换工单
  swichNav: function(e) {
    this.setData({
      currentTab: e.currentTarget.dataset.current
    })
  },  
  onLoad: function(options) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    that.setData({
      status: options.status,
      id: options.id,
      imgUrl: app.globalData.imgUrl,
    })
    //基本信息
    Api.req('sf/operationOrder/detail', {
        id: options.id
      }, 'get').then(res => {
        wx.hideLoading()
        if(res.code == 200){
          res.data.bdImgs = res.data.bdImgs.split(',');
          var basic = res.data;
          that.setData({
            basic: basic,
            category: basic.applianceCategory, //设备类型
            applianceBrand: basic.applianceBrand, //设备品牌
            applianceBarcode: basic.applianceBarcode, //设备序列号
            date: basic.putIntoTime.slice(0, 10), //投运时间
            type: basic.warrantyType?that.data.typeList[Number(basic.warrantyType) - 1]:'', //保修类型
            warrantyType: basic.warrantyType, //保修类型
            serviceType: basic.serviceType, //服务类型
            serviceTypeName: basic.serviceTypeName, //服务类型
            measuresId: basic.serviceMeasures, //服务措施ID
            measures: basic.serviceMeasuresName, //服务措施
          })
          that.getList()
        }
      })
      this.getBrandList()
      this.getServiceMeasures()
      this.getServiceType()
  }, 
  //设备品牌
  getBrandList(){
    Api.req('sf/operationOrderCallback/getAllBrand', {
      // orderId: options.id
    }, 'get')
    .then(res => {
      if(res.code == 200){
        this.setData({
          brandList: res.data,
        })
      }
    }) 
  },  
  //服务措施
  getServiceMeasures(){
    Api.req('sf/operationServiceMeasures/list', {
      // orderId: options.id
    }, 'get')
    .then(res => {
      if(res.code == 200){
        this.setData({
          measuresList: res.data.records,
        })
      }
    }) 
  },  
  //服务类型
  getServiceType(){
    Api.req('sf/operationServiceType/list', {}, 'get')
    .then(res => {
      if(res.code == 200){
        this.setData({
          servTypeList: res.data,
        })
      }
    }) 
  },  
  //电站名称
  stationName: function(e) {
    this.setData({
      stationName: e.detail.value
    })
  },
  //设备类型
  category: function(e) {
    this.setData({
      category: this.data.categoryList[e.detail.value],
    })
  },
  //设备品牌
  applianceBrand: function(e) {
    this.setData({
      applianceBrand: this.data.brandList[e.detail.value].name,
      applianceBrandId: this.data.brandList[e.detail.value].id
    })
  },
  //设备S/N
  applianceBarcode: function(e) {
    this.setData({
      applianceBarcode: e.detail.value
    })
  },
  //保修类型
  type: function(e) {
    let index = Number(e.detail.value);
    this.setData({
      type: this.data.typeList[index],
      warrantyType: String(index + 1)
    })
  },
  //服务类型
  servType: function(e) {
    let index = Number(e.detail.value);
    this.setData({
      serviceType: this.data.servTypeList[index].id,
      serviceTypeName: this.data.servTypeList[index].name
    })
  },
  //投运时间
  date: function(e) {
    this.setData({
      date: e.detail.value
    })
  },  
  //服务措施选择
  measures: function(e) {
    this.setData({
      measures: this.data.measuresList[e.detail.value].serviceMeasures,
      measuresId: this.data.measuresList[e.detail.value].id
    })
  },

  //反馈内容
  backSay: function(e) {
    this.setData({
      backSay: e.detail.value
    })
  },

  //销售商
  seller: function(e) {
    this.setData({
      seller: e.detail.value
    })
  },
  //发票号
  bill: function(e) {
    this.setData({
      bill: e.detail.value
    })
  },
  //产品名称
  pro_name: function(e) {
    this.setData({
      pro_name: e.detail.value
    })
  },
  //规格型号
  typeModel: function(e) {
    this.setData({
      typeModel: e.detail.value
    })
  },
  //机身编码
  code: function(e) {
    this.setData({
      code: e.detail.value
    })
  },  
   /**
   * 
   * 上传图片
   * 
   * @param {*} e 
   */
  afteruploadPhotoRead(e) {
    const type = e.currentTarget.dataset.type
    const name = e.currentTarget.dataset.name
    if (Array.isArray(e.detail.file)) { //多张
      var count = 0;
      this.afteruploadPhotoReadS(e, count)
      return
    }
    const {
      file
    } = e.detail;
    const img = file.url;
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    wx.uploadFile({
      url: that.data.UP_MONIT_IMG,
      filePath: file.url,
      header:{
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic c2FiZXIzOnNhYmVyM19zZWNyZXQ=',
        'Blade-Requested-With':'BladeHttpRequest',
        'Tenant-Id': '000000',
        'Blade-Auth':  'bearer ' + wx.getStorageSync('TOKEN'),
      },
      name: 'file',
      complete: function (res) {
        console.log("上传图片", res)
        var imgData = JSON.parse(res.data)
        wx.hideLoading()
        if (res.statusCode == 200) {
          wx.showToast({
            title: '选择成功',
            icon: 'none',
          })
          var item = {
            url: "",
            name: "",
          }
          item.url = img;
          item.name = imgData.data.name;
          that.data[name].push(item)
          that.setData({
            [`${name}`]: that.data[name]
          })
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  /** 上传多张图片递归 **/
  afteruploadPhotoReadS(e, count) {
    let ob = {
      name: '',
      url: '',
    }
    const name = e.currentTarget.dataset.name
    wx.showLoading({
      title: '加载第' + (count + 1) + '张照片中',
      mask: true,
    })
    const element = e.detail.file[count];
    var that = this;
    wx.uploadFile({
      url: that.data.UP_MONIT_IMG,
      filePath: element.url,
      header:{
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic c2FiZXIzOnNhYmVyM19zZWNyZXQ=',
        'Blade-Requested-With':'BladeHttpRequest',
        'Tenant-Id': '000000',
        'Blade-Auth':  'bearer ' + wx.getStorageSync('TOKEN'),
      },
      name: 'file',
      success(res) {
        wx.hideLoading()
        var imgData = JSON.parse(res.data)
        if (res.statusCode == 200) {
          count = count + 1;
          ob.name = imgData.data.name
          ob.url = element.url
          that.data[name].push(ob);
          that.setData({
            [`${name}`]: that.data[name]
          })
          if (count == e.detail.file.length) {
            wx.showToast({
              title: '选择成功',
              icon: 'none'
            })
          } else {
            that.afteruploadPhotoReadS(e, count)
          }
        } else {
          wx.showToast({
            title: '选择失败',
            icon: 'error'
          })
        }
      }
    })
  },
  //上传图片
  uploadImg: function(maxNum, imgName, cb) {
    var that = this,
      maxNum = maxNum;
    wx.chooseImage({
      count: maxNum - that.data.img.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        var imgList = that.data.imgList.concat(tempFilePaths),
          getImg = imgName;
        for (var i = 0; i < imgList.length; i++) {
          wx.showLoading({
            title: '图片上传中...',
            mask: true
          })
          wx.uploadFile({
            url: that.data.url + 'common/weChat/uploadImage',
            filePath: imgList[i],
            name: 'file', //在FILE请求中，图片存储在img字段中
            success: function(res) {
              if (getImg.length < maxNum) {
                getImg.push(res.data)
                var imgs = getImg
                that.setData({
                  imgs
                })
                typeof cb == 'function' && cb(that)
              }
              wx.hideLoading()
            },
            fail: function(res) {
              wx.showToast({
                title: 'error!',
                icon: 'none',
                image: '/img/error.png'
              })
            },
          })
        }

      }
    })
  },
  //删除上传图片
  deleteImg: function(e) {
    const name = e.currentTarget.dataset.name
    const index = e.detail.index //删除图片的下标
    this.data[name].splice(index, 1);
    this.setData({
      [`${name}`]: this.data[name]
    })
  },
//提交
  submit: function(e) {
    var that = this;
    var type = e.currentTarget.dataset.type
    if(type == '1'){//服务完成全必填
      if(this.data.applianceBrand == ''){
        wx.showToast({
          title: '设备品牌不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.applianceBarcode ==''){
        wx.showToast({
          title: '设备S/N不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.type == ''){
        wx.showToast({
          title: '保修类型不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.serviceType == ''){
        wx.showToast({
          title: '服务类型不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.measures == ''){
        wx.showToast({
          title: '服务措施不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.backSay ==''){
        wx.showToast({
          title: '反馈内容不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.imgName1.length==0){
        wx.showToast({
          title: '过程照片不能为空',
          icon: 'none'
        })
        return
      }
    }else{
      if(this.data.backSay ==''){
        wx.showToast({
          title: '反馈内容不能为空',
          icon: 'none'
        })
        return
      }else if(this.data.imgName1.length==0){
        wx.showToast({
          title: '过程照片不能为空',
          icon: 'none'
        })
        return
      }
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    var data = {
      orderId: this.data.id,
      applianceBrand: this.data.applianceBrand, //品牌
      applianceBarcode: this.data.applianceBarcode,//设备S/N
      warrantyType: this.data.warrantyType,//保修类型
      serviceType: this.data.serviceType,//服务类型
      putIntoTime: this.data.date, //投运时间
      serviceMeasures: this.data.measuresId, //服务措施
      feedbackImg: this.data.imgName1.length > 0 ? this.data.imgName1.map(itm=>itm.name).join(",") : "",//过程图片 
      feedbackType: type,//反馈类型：0 过程反馈 1服务完成反馈 2服务无法完成反馈
      feedback: this.data.backSay, //反馈内容
    }
    // console.log("执行",data);
    // return
    Api.req('sf/operationOrderFeedback/save', data, 'post', '','1')
      .then(res => {
        wx.hideLoading()
        if (res.code == '200') {
          wx.showToast({
            title: '操作成功',
          })
          var page = getCurrentPages();
          let prevPage = page[page.length - 2];
          setTimeout(function() {
            prevPage.getNum();
            prevPage.getOrder();
            wx.navigateBack({})
          }, 1000)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            mask: true
          })
        }
      })
  },
  //设备列表
  goDevice(){
    wx.navigateTo({
      url: '../../deviceList/deviceList?id=' + this.data.basic.entryId,
    })
  },
  
  //反馈记录
  backRecord: function(e) {
    wx.navigateTo({
      url: '../backDetail/backDetail?id=' + e.currentTarget.dataset.id + '&type=' + e.currentTarget.dataset.type
    })
  },

  //物料信息
  getDetail(e){
    let type = e.currentTarget.dataset.type
    if(type == '1'){//物料使用详情
      wx.navigateTo({
        url: '../../materialDetail/materialDetail?id=' + e.currentTarget.dataset.id + '&title=已用物料'
      })
    }else{//物料申请详情
      wx.navigateTo({
        url: '../../addMaterial/addMaterial?id=' + e.currentTarget.dataset.id + '&title=详情'
      })
    }
    
  },
  //使用物料
  getUseList(e){
    wx.navigateTo({
      url: '../../materialUse/materialUse?orderId=' + this.data.basic.id
    })
  },
  //申请物料
  goAddApply(e){
    wx.navigateTo({
      url: '../../addMaterial/addMaterial?orderId=' + this.data.basic.id + '&title=新增物料申请'
    })
  },
   //编辑申请物料
  editList(e){
    wx.navigateTo({
      url: '../../addMaterial/addMaterial?id='+ e.currentTarget.dataset.id +'&orderId=' + this.data.basic.id + '&title=编辑'
    })
  },
  //领取
  getReceive(e){
    let that = this
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '是否确认领取该物料？',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
          })   
          Api.req('blade-platformFittingApply/platformFittingApply/empReceiveMate', {
            id: id
          }, 'get').then(res => {
              wx.hideLoading()
              if(res.code == 200){
                wx.showToast({
                  title: '操作成功',
                })
                setTimeout(()=>{
                  that.getList();
                },500)
              }              
            })
        }
      }
    })
  },
  //物料信息列表
  getList: function () {
    var that = this    
    wx.showLoading({
      title: '加载中...',
    })   
    Api.req('blade-operationOrderMaterial/operationOrderMaterial/materialListRelateOrder', {
      orderId: this.data.basic.id
    }, 'get').then(res => {
      wx.hideLoading()
      if(res.code== 200){
        this.setData({
          useFitting: res.data.useFitting, //使用物料
          applyFitting: res.data.applyFitting, //申请物料
        })
      }else{
        wx.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      }
    })
  },
  //删除物料
  delList(e){
    let that = this
    let id = e.currentTarget.dataset.id
    let type = e.currentTarget.dataset.type
    let url = ''
    if(type == '1'){
      url = 'blade-operationOrderMaterial/operationOrderMaterial/deleteUserFitting' //删除使用
    }else{
      url = 'blade-operationOrderMaterial/operationOrderMaterial/deleteApplyFitting' //删除申请
    }
    wx.showModal({
      title: '提示',
      content: '是否确认删除该物料？',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
          })   
          Api.req(url, {
            id: id
          }, 'get').then(res => {
              wx.hideLoading()
              if(res.code == 200){
                wx.showToast({
                  title: '删除成功',
                })
                setTimeout(()=>{
                  that.getList();
                },500)
              }              
            })
        }
      }
    })
  }
})