import * as echarts from '../../ec-canvas/echarts';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    details: {
      chainName: '-',
      chainCode: '-',
      packageTypeName: '-',
      productName: '-',
      num: '-',
      startTime: '-',
      transportStatusName: '-',
      userName: '-',
      telephone: '-',
      productId: '',
      status: '',
      chainId: '',
    },
    boundDevice: {},
    ec: {
      lazyLoad: true,
    },
    nav: 0,
    startDate: "", //开始时间
    endDate: "", //结束时间
    isshow: true,
    isShowText: '显示冷链',
    deviceCode: '',
    modalHidden: true,
    modalVal: '', // 解除预警信息
    deptType: '',
    seleteType: [{
      transportStatus: '00',
      transportStatusName: '已入库'
    }, {
      transportStatus: '10',
      transportStatusName: '已出库'
    }, {
      transportStatus: '20',
      transportStatusName: '已结束'
    }],
    region: [],
    allMoer: false,
    chainBoundId: '',
    tableCoin: [{
        name: 'X201',
        img: '../../img/work_icon11.png',
        status: true,
        type: 'lableX201'
      },
      {
        name: 'X202',
        img: '../../img/X202.png',
        status: true,
        type: 'lableX202'
      },
      {
        name: 'X203',
        img: '../../img/work_icon11.png',
        status: true,
        type: 'lableX203'
      },
      {
        name: 'X101',
        img: '../../img/x1.png',
        status: true,
        type: 'lableX101'
      },
      {
        name: 'X102',
        img: '../../img/x102.png',
        status: true,
        type: 'lableX102'
      },
      {
        name: 'X103',
        img: '../../img/x2.png',
        status: true,
        type: 'lableX103'
      },
      {
        name: 'X104',
        img: '../../img/x1.png',
        status: true,
        type: 'lableX104'
      },
      {
        name: 'X105',
        img: '../../img/rfid.png',
        status: true,
        type: 'lableX105'
      },
      {
        name: 'X106',
        img: '../../img/x1.png',
        status: true,
        type: 'lableX106'
      },
      {
        name: 'X107',
        img: '../../img/x2.png',
        status: true,
        type: 'lableX107'
      },
    ],
    showDialog: false, //扫码弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    const that = this;
    //获取用户信息，判断userInfo是否过期
    let userInfo = wx.getStorageSync('userInfo');
    /**
     * status: 用户角色审核状态
     *        0  没有选择任何角色也没做任何认证
     *        10 审核中
     *        20 审核通过
     * ifOverFlow:是否通过验证
     *            N 没有选择角色
     *            Y 已选择角色
     *            非register时，如果是Y说明已经处于认证状态
     *            admin创建企业，personnel选择了企业
     * loginRole:用户权限
     *          admin 管理员
     *          doctor 医生
     *          register 自由注册  可申请为操作员
     *          personnel 操作员  已选择企业未认证
     *          
     */
    const {loginRole,ifOverFlow,status} = userInfo;
    that.setData({
      ispdfBut: loginRole == 'admin' ? true : loginRole == 'personnel' ? true : false,
      options,
      userInfo: wx.getStorageSync('userInfo')
    });
    //获取定位信息
    wx.getLocation({
      altitude: 'altitude',
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          userLatitude: res.latitude,
          userLongitude: res.longitude,
        })
      },
      error() {
        app.showToptip(that, "worning", "获取位置信息失败")
      }
    })
  },
  onShow() {
    var options = this.data.options;
    this.getInfo(options);
    this.getBoundDevice(options);
    var coinStatus = JSON.parse(wx.getStorageSync('labelStatus'));
    var tableCoin = this.data.tableCoin;
    var temp = '';
    tableCoin.map((coinType, index) => {
      Object.keys(coinStatus).forEach(key => {
        if (key == coinType.type) {
          temp = 'tableCoin[' + index + '].status'
          this.setData({
            [temp]: coinStatus[key]
          })
        }
      })
    })
  },
  getInfo(params = {}) {
    var that = this;
    const { deviceType, deviceCode, pid, chainBoundId } = params;
    var seleteType = that.data.seleteType;
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    app.requestP({
      url: "/chain/info",
      method: "post",
      data: {
        chainId: params.id || '',
        parentId: pid || 0,
      }
    }).then(res => {
      var data = res.data.data;
      const {
        chainId
      } = data;
      that.setData({
        details: data,
        // deptType:that.setTransportStatus(data.transportStatus),
        seleteType: that.setSeleteType(data.transportStatus),
        deviceCode,
        chainBoundId,
      })
      that.getHistory({
        chainId,
        searchTag: '0',
        deviceCode,
        chainBoundId,
      });
      that.getTempLine({
        chainId,
        searchTag: '0',
        deviceCode,
        deviceType,
        chainBoundId
      })
    }).catch(err => {
      app.showToptip(that, "error", "数据获取失败，请稍后再试")
      // 隐藏导航栏加载框
      wx.hideNavigationBarLoading();
      // 停止下拉动作
      wx.stopPullDownRefresh();
    })
  },
  setTransportStatus(transportStatus) {
    var seleteType = this.data.seleteType;
    var deptType;
    for (var i = 0; i < seleteType.length; i++) {
      if (seleteType[i].transportStatus == transportStatus) {
        deptType = i;
        break;
      }
    }
    return deptType;
  },
  setSeleteType(transportStatus) {
    var seleteType = this.data.seleteType;
    var type;
    for (var i = 0; i < seleteType.length; i++) {
      if (seleteType[i].transportStatus == transportStatus) {
        seleteType.splice(i, 1);
        break;
      }
    }
    this.setTransportStatus(transportStatus); //暂时不用
    return seleteType;
  },
  setType(e) {
    //数据
    var value = e.detail.value;
    var that = this;
    var chainId = that.data.details.chainId;
    var seleteType = that.data.seleteType;
    that.setData({
      deptType: value + ""
    })
    // app.requestP({
    //   url:'/chain/editTransport',
    //   method:'post',
    //   data:{
    //     addr:'',
    //     chainId,
    //     transportStatus:seleteType[value].transportStatus,
    //   }
    // }).then(res=>{
    //   that.setData({
    //     deptType:value+''
    //   })
    //   app.showToptip(that,'success',res.data.msg)
    // }).catch(err=>{
    //   app.showToptip(that,'error',err.data.msg)
    // })
  },
  setTransportStatus(transportStatus) {
    var seleteType = this.data.seleteType;
    var deptType;
    for (var i = 0; i < seleteType.length; i++) {
      if (seleteType[i].transportStatus == transportStatus) {
        deptType = i;
        break;
      }
    }
    return deptType;
  },
  getBoundDevice(params = {}) {
    var that = this;
    wx.showLoading({
      title: '正在加载...',
      mask: true
    })
    app.requestP({
      url: "/chainBound/boundDevice",
      method: 'post',
      data: {
        chainId: params.id
      }
    }).then(res => {
      const data = res.data.data;
      var bound = [];
      var name = ''
      Object.keys(data).forEach(key => {
        name = ''
        if (data[key].length == 0) {
          delete data[key]
        }else{
          if(key == 'childNum'){
            bound.push({title:'子冷链',info:data[key],isChild:true,code:key})
          }else if(key.indexOf('X') == -1 ){
            if(key == '10'){
              name = '追溯标签'
            }else if(key == '11'){
              name = '全程温控'
            }else if(key == '20'){
              name = '实时追溯'
            }
            bound.push({title:name,info:data[key],isChild:false,code:key})
          }else{
            bound.push({title:key,info:data[key],isChild:false,code:key})
          }
        }
      })
      that.setData({
        boundDevice: bound
      })
    }).catch(err => {
      app.showToptip(that, 'error', err.data.msg)
    })
  },
  goDetails(e) {
    var that = this;
    var type = e.currentTarget.dataset.code;
    var ischild = e.currentTarget.dataset.ischild;
    var info = e.currentTarget.dataset.details.info;
    if(ischild){
      this.goChainCold();
    }
    if(type == 10 || type == 11 || type == 20){
      app.showToptip(this,'error','暂不支持查看！')
      return;
    }
    var json = encodeURIComponent(JSON.stringify({details:info,devicetype:type}));
    wx.navigateTo({
      url: '/pages/query/vvmInfo?details=' + json + '&id=' + that.data.options.id,
    })
  },
  getHistory(params = {}) {
    var that = this;
    //chainId,deviceCode,endTime,searchTag,startTime
    app.requestP({
      url: '/chainLocal/localHistory',
      method: 'post',
      contentType: ' application/json',
      data: {
        ...params,
      }
    }).then(res => {
      that.setData({
        deviceCode: res.data.data.deviceCode || that.data.deviceCode || 'N/A',
      })
      that.setLocus(res.data.data);
    }).catch(err => {
      that.setLocus({
        points: []
      });
      // app.showToptip(that, 'error', err.data.msg)
    })
  },
  goChainCold() {
    var that = this;
    wx.navigateTo({
      url: '/pages/query/childlist/childlist?chainId=' + that.data.details.chainId
    })
  },
  setLocus(data) {
    const that = this;
    const {
      status,
      transportType,
      points
    } = data;
    let locations = points;
    for (let i in locations) { //设置起始marker
      locations[i].id = i - 0
      if (i == 0) {
        locations[i].iconPath = "/img/map_icon1.png";
        locations[i].width = 38;
        locations[i].height = 40;
      }
      if (i == locations.length - 1) {
        locations[i].iconPath = "/img/index_icon_" + transportType + '' + status + '' + ".png";
        locations[i].width = 54;
        locations[i].height = 54;
      }
      locations[i].latitude = locations[i].lat;
      locations[i].longitude = locations[i].lng;
    }
    that.mapCtx = wx.createMapContext('index_map');
    if (locations.length) {
      that.setData({
        latitude: locations[0].lat || that.data.userLatitude,
        longitude: locations[0].lng || that.data.userLongitude,
        markers: [locations[0], locations[locations.length - 1]],
        polyline: [{
          color: '#2D59E6',
          width: 2,
          points: points,
          // arrowLine:true
        }]
      })
      that.mapCtx.includePoints({
        points: points,
        padding: [50, 50, 50, 50]
      })
    } else {
      that.setData({
        latitude: that.data.userLatitude,
        longitude: that.data.userLongitude,
        markers: [{
          iconPath: '/img/index_icon_5000.png',
          width: '54',
          height: '54',
          latitude: that.data.latitude,
          longitude: that.data.longitude
        }],
        polyline: [{
          color: '#2D59E6',
          width: 2,
          points: [],
          // arrowLine:true
        }]
      })
    }
    that.data.locations = locations
  },
  getTempLine(params = {}) {
    const that = this;
    app.requestP({
      url: '/chain/tempLine',
      method: 'post',
      contentType: ' application/json',
      data: {
        ...params
      }
    }).then(res => {
      var data = res.data.data.temps;
      that.setData({
        temperature: data
      })
      if (data.length != 0) {
        that.setTemp(data);
      } else {
        // app.showToptip(that, 'error', '暂无温度数据');
      }
    }).catch(err => {
      // app.showToptip(that, 'error', '暂无温度数据');
    })
  },
  setTemp(data) {
    const that = this;
    that.ecWen = that.selectComponent('#ecDomWen');
    that.ecWen.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      var option = that.getOption();
      option.xAxis.data = data.map(v => v.createTime.replace(" ", "\n"))
      option.series[0].data = data.map(v => v.temp)
      option.dataZoom = [{
          type: "slider",
          start: 0,
          end: (100 / data.length) * 15, //显示五个
        },
        {
          type: "inside",
          start: 0,
          end: (100 / data.length) * 15, //显示五个
        },
      ]
      chart.setOption(option);
      return chart;
    })
  },
  getOption() {
    return {
      tooltip: {
        show: true,
        formatter: '{b}\n{c}℃',
        trigger: "axis",
        position: "top"
      },
      grid: {
        top: '5%',
        left: '0%',
        right: '5%',
        bottom: '18%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        nameTextStyle: {
          color: "#77869E",
          fontSize: 10
        },
        axisLabel: {
          color: "#cccccc",
          fontSize: 8,
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: "#cccccc"
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: true,
        },
        data: ['16:00 \n 2021-06-30', '16:00 \n 2021-06-30', '16:00 \n 2021-06-30', '16:00 \n 2021-06-30', '16:00 \n 2021-06-30', '16:00 \n 2021-06-30', '16:00 \n 2021-06-30']
      },
      yAxis: {
        type: 'value',
        splitNumber: 10,
        max: 40,
        axisLine: {
          lineStyle: {
            color: "#cccccc"
          },
          show: true
        },
      },
      series: [{
        type: 'line',
        showSymbol: false,
        smooth: true,
        lineStyle: {
          width: 1,
          color: "#328EFD", //#D4D4D4
        },
        markLine: {
          lineStyle: {
            color: "#F22424",
          },
          data: [{
            yAxis: 40
          }]
        },
        markPoint: {
          symbolSize: 30,
          //symbol:'diamond',
          label: {
            fontSize: 8,
          },
          data: [{
              type: 'max',
              name: '最大值'
            },
            {
              type: 'min',
              name: '最小值'
            }
          ]
        },
        areaStyle: {
          origin: "start",
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: '#FFFFFF' //
            }, {
              offset: 1,
              color: '#4C96FE' //#D4D4D4
            }],
            global: false
          }
        },
        data: [18, 36, 25, 30, -20, 40, 33]
      }]
    }
  },
  endDateChange(e) {
    this.setData({
      endDate: e.detail.value
    })
  },
  startDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
  },
  submitDate() {
    this.getTemp(1, this.data.options);
  },
  getTemp(type, params = {}) {
    var that = this;
    const {deviceCode,deviceType} = params;
    const chainId = that.data.details.chainId;
    var endDate = that.data.endDate;
    var startDate = that.data.startDate;
    if (type == 1) {
      if (endDate && startDate) {} else {
        app.showToptip(that, "worning", "请选择起止时间")
        return
      }
    }
    wx.showLoading({
      mask: true
    })
    this.getHistory({
      chainId,
      searchTag: 1,
      deviceCode,
      endTime: endDate + ' 23:59:59',
      startTime: startDate + ' 00:00:00'
    });
    this.getTempLine({
      chainId,
      searchTag: 1,
      deviceCode,
      deviceType,
      endTime: endDate + ' 23:59:59',
      startTime: startDate + ' 00:00:00'
    })
  },
  setNav(e) {
    var nav = e.currentTarget.dataset.val;
    const { deviceCode, deviceType, chainBoundId } = this.data.options;
    this.setData({
      nav,
      temperature: []
    });
    if (nav == 0 || nav == 2) {
      const chainId = this.data.details.chainId;
      this.getHistory({
        chainId,
        searchTag: nav,
        deviceCode,
        chainBoundId: chainBoundId || ''
      });
      this.getTempLine({
        chainId,
        searchTag: nav,
        deviceCode,
        deviceType,
        chainBoundId: chainBoundId || ''
      })
    }
  },
  isShow() {
    if (this.data.isshow) {
      this.setData({
        isShowText: '隐藏冷链',
        isshow: false
      })
    } else {
      this.setData({
        isShowText: '显示冷链',
        isshow: true
      })
    }
  },
  isAllMoer() {
    this.setData({
      allMoer: !this.data.allMoer
    })
  },
  cleanWarning(e) { // 解除预警
    const {
      details: {
        chainId
      },
      userInfo: {
        loginRole
      }
    } = this.data;
    var status = e.currentTarget.dataset.status;
    if (status == 10 || status == 20) {
      if (loginRole !== "doctor") {
        wx.navigateTo({
          url: '/pages/query/clearWarning/clearWarning?chainId=' + chainId, //details
        })
      } else {
        app.showToptip(this, 'error', '暂无权限');
      }
    }
  },
  goPdf(e) {
    var chainId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/workbench/scanningType/reportPdf/reportPdf?id=' + chainId+'&orderid='+'',
    })
  },
  regionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  setModalVal(e) {
    this.setData({
      modalVal: e.detail.value
    })
  },
  setmodalHidden(e) {
    var transportStatus = e.currentTarget.dataset.transportstatus;
    if (transportStatus == '00' || transportStatus == '10') {
      this.setData({
        modalHidden: !this.data.modalHidden,
      })
    } else if (transportStatus == '20') {
      app.showToptip(this, 'error', '冷链已结束，请勿修改运输状态')
    }
  },
  //取消按钮点击事件
  modalBindcancel: function () {
    this.setData({
      modalHidden: !this.data.modalHidden,
      region: [],
      modalVal: '',
      iodepId: '',
    })
  },
  modalBindaconfirm() { //二型保存地址
    var that = this;
    var {
      region,
      modalVal,
      iodepId,
      seleteType,
      deptType
    } = that.data;
    var {
      chainId,
      transportStatus
    } = that.data.details;
    var addr = region.join('') + modalVal;
    if (region.join('') && modalVal) {
      app.requestP({
        url: '/chain/editTransport',
        // contentType:' application/json',
        method: 'post',
        data: {
          addr,
          chainId, // 00 已入库 //10 已出库 //20 已结束
          transportStatus: seleteType[deptType].transportStatus,
        }
      }).then(res => {
        that.setData({
          modalHidden: !that.data.modalHidden,
          region: [],
          modalVal: '',
          iodepId: '',
        })
        that.getInfo({
          id: chainId
        });
        app.showToptip(that, 'success', res.data.msg);
      }).catch(err => {
        app.showToptip(that, 'error', err.data.msg);
      })
    } else {
      app.showToptip(that, 'error', '地址和运输状态不能为空');
    }
  },
  goTempDetail() {
    var {
      chainId
    } = this.data.details;
    var nav = this.data.nav;
    wx.navigateTo({
      url: '/pages/query/tempDetails/tempDetails?chainId=' + chainId + '&searchTag=' + nav,
    })
  },
  //查一查弹框控制
  showChaWin() {
    this.setData({
      showChaType: true
    })
  },
  closeChaWin() {
    this.setData({
      showChaType: false,
    })
  },
  chainCode(e) {
    var that = this;
    var chainId = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var code = e.currentTarget.dataset.code;
    that.scanCode().then(result => {
      app.requestP({
        url: '/chainSource/add',
        method: 'post',
        contentType: 'application/json',
        data: {
          chainId,
          [type]: result.code
        }
      }).then(res => {
        app.showToptip(that, 'success', res.data.msg);
        that.getInfo({
          id: chainId,
          pid: 0
        });
      }).catch(err => {
        app.showToptip(that, 'error', err.data.msg);
      })
    })

  },
  scanCode() {
    var that = this;
    return new Promise((resolve, reject) => {
      wx.scanCode({
        scanType: ['barCode', 'qrCode'],
        success: function (res) {
          var {result} = res;
          resolve({
            code: result
          })
        },
        fail: function (err) {
          app.showToptip(that, 'error', '扫码失败');
        }
      })
    })
  },
  copyCode(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.code
    })
  },
  goScanSetting() {
    wx.navigateTo({
      url: '/pages/setting/scanSetting/scanSetting',
    })
  },
  addChain(e) {
    const type = e.currentTarget.dataset.type;
    var details = this.data.details;
    const noAdd = ['lableX101', 'lableX102', 'lableX103', 'lableX105', 'lableX106', 'lableX107','NFC'];
    if (noAdd.indexOf(type) != -1) {
      app.showToptip(this, 'error', '该标签暂不支持在小程序添加，请移动到APP操作！')
      return;
    }
    // 104 一型无源
    switch (type) {
      case 'lableX104':
        wx.navigateTo({
          url: '/pages/nfc/zhuisu2?id='+details.chainId+'&type=X104&addLabel=20',
        })
        break;
      default:
        this.setData({
          showDialog: !this.data.showDialog,
          devicetype:type
        })
        break;
    }
  },
  toggleDialog() { //弹窗关闭
    this.setData({
      showDialog: !this.data.showDialog,
      devicetype:''
    });
  },
  chainBind() {
    var that = this;
    wx.scanCode({
      success: function (res) {
        var { result } = res;
        if (result.indexOf('imei=') != -1) {
          result = result.slice(result.indexOf('imei=') + 5, result.length)
        }
        that.setchainBoundBind(result);
      },
      fail: function (err) {
        app.showToptip(that, 'error', '二维码无效');
      }
    })
  },
  setchainBoundBind(result) {
    var that = this;
    var options = this.data.options;
    const {details,devicetype,latitude,longitude} = that.data;
    app.requestP({
      url: '/chainBound/checkBind',
      method: 'post',
      data: {
        deviceCode: result,
      }
    }).then(res => {
      if (res.data.data == 0) {
        app.requestP({
          url: '/chainBound/bind',
          method: 'post',
          contentType: ' application/json',
          data: {
            chainId: details.chainId,
            deviceCode: result,
            type: devicetype.substr(5),
            lat: latitude,
            lng: longitude
          }
        }).then(response => {
          app.showToptip(that, 'success', '绑定成功！');
          that.getInfo(options);
          that.getBoundDevice(options);
        }).catch(error => {
          app.showToptip(that, 'error', error.data.msg)
        })
      } else {
        app.showToptip(that, 'error', res.data.msg)
      }
    }).catch(err => {
      app.showToptip(that, 'error', err.data.msg)
    })
  },
  inputBind() {
    var that = this
    wx.showModal({
      title: '请输入标签编号',
      editable: true,
      success(res) {
        if (res.confirm) {
          var numreg = /^[0-9]*$/;
          if (res.content) {
            // if (!numreg.test(res.content)) {
            //   app.showToptip(that, "error", "标签编号只能为数字！");
            //   that.inputBind()
            //   return;
            // }
            that.setchainBoundBind(res.content)
          } else {
            app.showToptip(that, "error", '标签编号不能为空！')
            that.inputBind()
          }
        } else {
          //pass
        }
      }
    })
  },
})