// pages/Material-Management/index.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        initData:{},
        indexNum:0,
        indexNum1:1,
        indexNum2:1,
        AIvideoSurvey: [],
        background:'skyblue',
        videoSurvey: [],
        safetyDeepList:[],
        safetyDeepData:[],
        //服务请求接口表示
        request:{
          //获取完工工号数
          getRebarOrConcreteOrOtherGhFinishNumService:"getRebarOrConcreteOrOtherGhFinishNumService",
          // 混凝土统计使用量
          getFinishConcreteGhInfoByProjectIdWx:"getFinishConcreteGhInfoByProjectIdWx",
          //超耗物料top排行榜
          getReportConcreteExceedMaterielTopService:"getReportConcreteExceedMaterielTopService",
          //超耗原因分析
          getReportConcreteExceedReasonService:"getReportConcreteExceedReasonService",
          //进行中工号物料情况
          getUseSituationRPTDayService:"getUseSituationRPTDayService",
          //混凝土使用情况
          getConcreteMaterialActquantityNumService:"getConcreteMaterialActquantityNumService"  ,
          //进行中工号数
          getRebarOrConcreteOrOtherGhUnderNumService:"getRebarOrConcreteOrOtherGhUnderNumService",
          //获取工号楼层信息
          getConcreteMaterialActQuantityGhInfoService:"getConcreteMaterialActQuantityGhInfoService"
        },
        value2: "本月",
        value1: "本月",
        value3: "本月",
        actions2: [{ name: '本月',id:0 }, { name: '累计', id:1},],
        actions1: [{ name: '本月',id:1 }, { name: '累计', id:2},],
        actions3: [{ name: '本月',id:1 }, { name: '累计', id:0},],
        //完工工号数
        finishGhNumber:0,
        //完工超耗
        finishGhSjl:0,
        finishGhShl:0,
        finishGhJcl:0,
        finishGhJclRate:0,
        //进行中用料情况
        materialZc:0,
        materialCh:0,
        materialLj:0,
        underGhNumber:0,
        loadShow:false,
        topMaterialIsSHowFlag:false,
        topMaterialReasonIsSHowFlag:false,
        ghId:"",

      //混凝土使用情况
      situationList:[]

    },
    //选择项目
    onProjectSelect(e){
      let projectId = e.detail.id;
      let projectName = e.detail.text;
      app.globalData.projectId = projectId;
      app.globalData.projectName = projectName;
      this.setData({
          projectId: projectId,
          projectName: projectName,
      })
      this.onLoad()
    },
    onClick(){
      this.setData({
        show2:true
      })
    },
    onClick1(){
      this.setData({
        show1:true
      })
    },
    onClick2(){
      this.setData({
        show3:true
      })
    },
    // 点击进行超耗tab切换
    onSelect2(e){
      // console.log(e);
        let indexNum =  e.detail.id;
        this.setData({
            indexNum,
            value2: e.detail.name,
        })
        //数据切换
        ///获取混凝土完工工号数
        this.getRebarOrConcreteOrOtherGhFinishNumService(indexNum)
        //获取混凝土完工超耗情况
        this.getProjectChaoHaoStatisticsRPTService(indexNum)
        //获取混凝土超耗top榜单
        this.getReportConcreteExceedMaterielTopService(indexNum)
        //获取混凝土超耗原因分析
        this.getReportConcreteExceedReasonService(indexNum)
    },
  

onSelect1(e){
  let indexNum1 =  e.detail.id;
  console.log(indexNum1);
      this.setData({
        indexNum1,
        value1: e.detail.name,
      })
      this.getUseSituationRPTDayService(indexNum1)
    },
    onSelect3(e){
        let {ghId} = this.data
        let indexNum2 =  e.detail.id;
        this.setData({
          indexNum2,
          value3: e.detail.name,
        })
        if(ghId == 0){
          this.onClickTemperatureTrend(indexNum2)
        }else{
          this.onClickTemperatureTrend(indexNum2,ghId)
        }
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    //获取缓存数据
      wx.getStorage({
        key: 'userinfo',
        success:res=>{
          this.setData({
            loginName:res.data.loginName,
            userName:res.data.userName,
            initData:{text:app.globalData.projectName,id:app.globalData.projectId}
          })  
          this.getProjectCorrespondence(app.globalData.projectId)
        }
      })
    },  
   /**
    * 项目对应关系
    */
  getProjectCorrespondence(projectId) {
    var that = this;
    wx.request({
      url: app.globalData.reqUrl + '/weixin/training/getProjectCorrespondence',
      data: {
        "projectId": projectId,
      },
      method: "get",
      success: function (res) {
        that.setData({
          projectData: res.data
        })
        //数据请求
        //获取混凝土完工工号数
        that.getRebarOrConcreteOrOtherGhFinishNumService(0)
        //获取混凝土完工超耗情况
        that.getProjectChaoHaoStatisticsRPTService(0)
        //获取混凝土超耗top榜单
        that.getReportConcreteExceedMaterielTopService(0)
        //获取混凝土超耗原因分析
        that.getReportConcreteExceedReasonService(0)
        //混凝土使用情况
        that.onClickTemperatureTrend(1)
        //使用情况进行中
        that.getUseSituationRPTDayService(1)
        //获取楼层
        that.getConcreteMaterialActQuantityGhInfoService()
      }
    })
  },

  /**
   * 获取混凝土完工工号数
   */
  getRebarOrConcreteOrOtherGhFinishNumService(type){
    let that = this
    that.setData({
      loadShow:true
    })
    let {clxh} = that.data.projectData
    let startDate = ""
    let endDate = ""
    if(type == 0){
      startDate = that.dateFormat(that.getlastMonth(),"yyyy-MM-dd") + " 00:00:00"
      endDate = that.dateFormat(new Date(),"yyyy-MM-dd") + " 00:00:00"
    }else{
      startDate = "1970-01-01 00:00:00"
      endDate = that.dateFormat(new Date(),"yyyy-MM-dd") + " 00:00:00"
    }
    wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getRebarOrConcreteOrOtherGhFinishNumService',
      method:"GET",
      data:{
        service:that.data.request.getRebarOrConcreteOrOtherGhFinishNumService,
        projectId:clxh,
        startDate,
        endDate,
        materialType:0
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success(res){
        that.setData({
          loadShow:false
        })
        res = res.data
        if(res.code == "000000"){
          that.setData({
            finishGhNumber:res.data[0].finishNum
          })
        }else{
          that.setData({
            finishGhNumber:0
          })
        }
      }
    })
  },
  /**
   * 获取混凝土完工超耗情况
   */
  getProjectChaoHaoStatisticsRPTService(type){
    
    let that = this
    that.setData({
      loadShow:true
    })
    let {clxh} = that.data.projectData
    let startTime = ""
    let endTime = ""
    if(type == 0){
      startTime = that.dateFormat(that.getlastMonth(),"yyyy-MM-dd") + " 00:00:00"
      endTime = that.dateFormat(new Date(),"yyyy-MM-dd") + " 23:59:59"
    }
    wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getProjectChaoHaoStatisticsRPTService',
      method:"GET",
      data:{
        service:that.data.request.getFinishConcreteGhInfoByProjectIdWx,
        projectId:clxh,
        startTime,
        endTime,
        materialType:0
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success(res){
        that.setData({
          loadShow:false
        })
        res = res.data
        if(res.code == "000000"){
          that.setData({
            finishGhSjl:res.data[0].finishGhSjl,
            finishGhShl:res.data[0].finishGhShl,
            finishGhJcl:res.data[0].finishGhJcl,
            finishGhJclRate:res.data[0].finishGhJclRate
          })
        }else{
          that.setData({
            finishGhSjl:0,
            finishGhShl:0,
            finishGhJcl:0,
            finishGhJclRate:0
          })
        }
      }
    })
  },
   /**
   * 获取混凝土超耗top榜单
   */
  getReportConcreteExceedMaterielTopService(type){
    
    let that = this
    that.setData({
      loadShow:true
    })
    let {clxh} = that.data.projectData
    let startTime = ""
    let endTime = ""
    if(type == 0){
      startTime = that.dateFormat(that.getlastMonth(),"yyyy-MM-dd") + " 00:00:00"
      endTime = that.dateFormat(new Date(),"yyyy-MM-dd") + " 23:59:59"
    }
    wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getReportConcreteExceedMaterielTopService',
      method:"GET",
      data:{
        service:that.data.request.getReportConcreteExceedMaterielTopService,
        projectId:clxh,
        startTime,
        endTime,
        materialType:0,
        top:5
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success(res){
        res = res.data
        that.setData({
          loadShow:false
        })
        if(res.code == "000000" && res.data){
          that.setData({
            topMaterialIsSHowFlag:false
          })
          let temp = []
          res.data.forEach((item,index)=>{
              let tempObject = {}
              tempObject.yesMonitor = Number(item.ch).toFixed(1)
              tempObject.name = item.materielName +'('+item.materielModel+')'
              tempObject.total = item.sumCh
              tempObject.unit = "%"
              temp.push(tempObject)
          })
          let excessRateData = temp.sort((prev,next)=> next.prop - prev.prop)
          that.setData({
            safetyDeepData:excessRateData
          })
        }else{
          that.setData({
            safetyDeepData:[]
          })
        }
      }
    })
  },

   /**
   * 获取混凝土超耗原因分析
   */
  getReportConcreteExceedReasonService(type){
    
    let that = this
    that.setData({
      loadShow:true
    })
    let {clxh} = that.data.projectData
    let startTime = ""
    let endTime = ""
    if(type == 0){
      startTime = that.dateFormat(that.getlastMonth(),"yyyy-MM-dd") + " 00:00:00"
      endTime = that.dateFormat(new Date(),"yyyy-MM-dd") + " 23:59:59"
    }
    wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getReportConcreteExceedReasonService',
      method:"GET",
      data:{
        service:that.data.request.getReportConcreteExceedReasonService,
        projectId:clxh,
        startTime,
        endTime,
        materialType:0
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
     
      success(res){
        that.setData({
          loadShow:false
        })
          res = res.data
          if(res.code == "000000" && res.data){
            that.setData({
              topMaterialReasonIsSHowFlag:true
            })
            var temp = {}
            let datas2 = []
            const total = res.data.reduce((prev,cur,index)=>{
              return prev + cur.chActQuantity
            },0)
            for(let i = 0;i < res.data.length;i++){
                if(res.data[i].causeName.indexOf('其他') != -1 ){
                    for(let k in res.data[i]){
                        temp[k] = res.data[i][k]
                    }
                    temp.name = "其它原因"
                    temp.value = Number(temp.chActQuantity).toFixed(1);
                    temp.prop = ((Number(temp.chActQuantity) / total) * 100 ).toFixed(1)
                    res.data.splice(i,1)
                    break;
                }
            }

            for(let i = 0;i < res.data.length;i++){
                if(i < 5){
                    res.data[i].value = Number(res.data[i].chActQuantity).toFixed(1);
                    res.data[i].name = res.data[i].causeName;
                    res.data[i].prop =  ((Number(res.data[i].chActQuantity) / total) * 100 ).toFixed(1)
                    datas2.push(
                      res.data[i]
                    )
                }else{
                    temp.value = Number(Number(temp.value) + Number(Number(res.data[i].chActQuantity).toFixed(1))).toFixed(1)
                }
            }

            datas2 =  datas2.sort((next,prev)=> prev.value - next.value   )
            if(Object.keys(temp).length > 0){
                datas2.push(temp)
            }
            that.setData({
              videoSurvey:datas2
            })
          }else{
            that.setData({
              videoSurvey:[]
            })
          }
      }
    })
  },

  /**
   * 进行中工号数
   */
  getUseSituationRPTDayService(type){
    
    let that = this
    that.setData({
      loadShow:true
    })
    let {clxh} = that.data.projectData
    let startTime = ""
    let endTime = ""
    if(type == 1){
      startTime = that.dateFormat(that.getlastMonth(),"yyyy-MM-dd") + " 00:00:00"
      endTime = that.dateFormat(new Date(),"yyyy-MM-dd") + " 23:59:59"
    }
    wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getUseSituationRPTDayService',
      method:"GET",
      data:{
        service:that.data.request.getUseSituationRPTDayService,
        projectId:clxh,
        startTime,
        endTime,  
        type
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success(res){
      wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getRebarOrConcreteOrOtherGhUnderNumService',
      method:"GET",
      data:{
        service:that.data.request.getRebarOrConcreteOrOtherGhUnderNumService,
        projectId:clxh,
        startDate:startTime,
        endDate:endTime,
        materialType:0
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success(res1){
        that.setData({
          loadShow:false
        })
        //getRebarOrConcreteOrOtherGhUnderNumService
        res = res.data
        res1 = res1.data
        if(res.code == "000000"){
          let {concrete_consume_zc,concrete_consume_ch,concrete_consume_lj} = res.data[0]
          let materialZc =  isNaN(parseFloat(concrete_consume_zc).toFixed(1)) ? 0.0: parseFloat(concrete_consume_zc).toFixed(1);
          //混凝土超耗
          let materialCh =  isNaN(parseFloat(concrete_consume_ch).toFixed(1)) ? 0.0:parseFloat(concrete_consume_ch).toFixed(1);
          //混凝土临建
          let materialLj =  isNaN(parseFloat(concrete_consume_lj).toFixed(1)) ? 0.0:parseFloat(concrete_consume_lj).toFixed(1);
          that.setData({
            materialZc,
            materialCh,
            materialLj,
            underGhNumber:res1.data[0].underNum
          })
        }else{
          that.setData({
            materialZc:0,
            materialCh:0,
            materialLj:0,
            underGhNumber:0
          })
        }
      }
      })
        
      }
    })
  },


    //混凝土使用情况
  onClickTemperatureTrend(type,ghId=''){
      let that = this
      that.setData({
        loadShow:true
      })
      let {clxh} = that.data.projectData
      let startTime = ""
      let endTime = ""
      if(type == 1){
        startTime = that.dateFormat(that.getlastMonth(),"yyyy-MM-dd") + " 00:00:00"
        endTime = that.dateFormat(new Date(),"yyyy-MM-dd") + " 23:59:59"
      }
      wx.request({
        url: app.globalData.reqUrl + '/weixin/material/getConcreteMaterialActquantityNumService',
        method:"GET",
        data:{
          service:that.data.request.getConcreteMaterialActquantityNumService,
          projectId:clxh,
          startTime,
          endTime,
          materialType:0,
          top:3,
          ghId
        },
        header:{
          'content-type': 'application/x-www-form-urlencoded'  
        },
        success(res){
          that.setData({
            loadShow:false
          })
          res = res.data
          if(res.code == "000000"){
            if(res.data){
              let safetyDeepList = []
              const total = res.data.reduce((prev,cur,index)=>{
                return prev + cur.actQuantity
              },0)   
              res.data.forEach(item=>{
                safetyDeepList.push({
                  //name:item.materielName+'/'+item.materielModel,
                  name:item.materielModel,
                  yesMonitor:item.actQuantity.toFixed(1),
                  total:total,
                  unit: 'm³',
                  sjQuantity:item.yhl.toFixed(1)
                })
              })
             that.setData({
                safetyDeepList
             })   
                
            }else{
                that.setData({
                  safetyDeepList:[]
                })
               
            }
  
  
        }
        }
      })  
      
  },

  /**
   * 获取楼号下拉框
   * @param {} e 
   */
  getConcreteMaterialActQuantityGhInfoService(){
    let that = this
    let situationList = [{
      id:0,
      text:"全部"
    }]
    let {clxh} = that.data.projectData
    wx.request({
      url: app.globalData.reqUrl + '/weixin/material/getConcreteMaterialActquantityNumService',
      method:"GET",
      data:{
        service:that.data.request.getConcreteMaterialActQuantityGhInfoService,
        projectId:clxh
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'  
      },
      success(res){
        res = res.data
        if(res.code == "000000" && res.data){
          res.data.forEach(item=>{
            situationList.push({
              id:item.ghId,
              text:item.ghName
            })
          })
        }
        that.setData({
          situationList
        })
      }
  })
  },
  onSelectEducationType(e){
    let id = e.detail.id
    let {indexNum2} = this.data
    this.setData({
      ghId:id
    })
    if(id == 0){
      this.onClickTemperatureTrend(indexNum2)
    }else{
      this.onClickTemperatureTrend(indexNum2,id)
    }
  },





  /**
   * 获取当前时间上一月时间
   */
  getlastMonth() {
    let now = new Date();
    // 当前月的日期
    let nowDate = now.getDate();
    let lastMonth = new Date(now.getTime());
    // 设置上一个月（这里不需要减1）
    lastMonth.setMonth(lastMonth.getMonth());
    // 设置为0，默认为当前月的最后一天
    lastMonth.setDate(0);
    // 上一个月的天数
    let daysOflastMonth = lastMonth.getDate();
    // 设置上一个月的日期，如果当前月的日期大于上个月的总天数，则为最后一天
    lastMonth.setDate(nowDate > daysOflastMonth ? daysOflastMonth : nowDate);
    return lastMonth;
  },

  /**
   * 格式化时间
   */
  dateFormat(date,fmt) {
    let ret;
    const opt = {
        "y+": date.getFullYear().toString(),        // 年
        "M+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "m+": date.getMinutes().toString(),         // 分
        "s+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
  },










    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    /**
   * 返回到更多功能页面
   */
  goGCLB:function(){
    wx.redirectTo({
      url: '../../pages/gengduogongneng/gengduogongneng'
    })
  },
    
  showPopup() {
    this.setData({ show: true });
    
  },
  onClose() {
    this.setData({ show: false });
    this.setData({ show1: false });
    this.setData({ show2: false });
    this.setData({ show3: false });
},
})