import $ from './../../utils/Tool'
import router from './../../utils/router'
import {gethouseKeeper,getSpaceAdjustList,submitFeedback} from '../../requests/api';
let timer=null;
Page({
  data: {
    debunkList:[
      {
        label:'1',
        name:"多次调节无效果"
      },
      {
        label:'2',
        name:"噪音大"
      },
      {
        label:'3',
        name:"吹风感强"
      },
      {
        label:'4',
        name:"有异味"
      },
      {
        label:'5',
        name:"空调设备故障"
      }
    ],
    debunkValue:0,
    fileList:[],
    showUpload:true,
    photoType:'', // 0照片 1视频
    houseKeeper:null,
    spaceId:null,
    spaceName:'',
    formSearch:false,
    imgbaseUrl:$.store.get('imgbaseUrl')
  },
  goBack(){
    router.pop()
  },
  goHome(){
    $.store.set('goHome',true);
    router.toHome()
  },
  chooseSpace(){
    router.push('search')
  },
  makePhoneCall(e){
    let phone = e.currentTarget.dataset.phone;
    console.log(e)
    wx.makePhoneCall({
      phoneNumber: phone,
      success:function(){
        console.log('拨打成功')
      },
      fail:function(){
        console.log('拨打失败')
      }
    })
  },
  debunkChange(event){
    if(event.detail!==this.data.debunkValue){
      this.setData({
        debunkValue: event.detail,
      });
    }else{
      this.setData({
        debunkValue: 0,
      });
    }
  },
  inputChange(e){
    let {value} = e.detail;
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(()=>{
        if(value==null){
          //这里表示  如果搜索框中没有数据的话，做的一些处理
        }else{
          this.setData({suggest:value},()=>{
            console.log(this.data.suggest)
          })
        }
    },300)

    console.log(e);
    // event.detail = {value, cursor, keyCode}
  },
  uploadVadio(){
    const that = this;
    wx.chooseMedia({
      count: 1,
      maxDuration: 15,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {

          let tempFilePaths = res.tempFiles[0].tempFilePath;

          if(tempFilePaths.split('.').pop()==="mp4"){
            that.setData({photoType:'1'})
          }else{
            that.setData({photoType:'0'})
          }
          let fileList = that.data.fileList.concat(tempFilePaths);
          if (fileList.length==1){
              that.setData({
                  showUpload:false
              })
          }
          that.setData({
            fileList,
          })
      }
  })
  },
  uploadFile(){
    let fileName = new Date().getTime();
    let fileType = this.data.photoType=='0'?'.png':'.mp4';
    this.setData({fileName:`${fileName}${fileType}`})
    return new Promise((resolve,reject)=>{
      wx.uploadFile({
        url: `https://duoduoenv.sagacloud.cn/server/common/upload?name=${fileName}${fileType}`,
        filePath: this.data.fileList[0],
        name: 'file',
        success: (resp) => {
          console.log(resp);
          resolve(resp)
        },
        fail:(res)=>{
          reject(res)
        }
      })
    })

  },
  clearImg(){
    this.setData({fileList:[],showUpload:true,photoType:null})
  },
  getKeeper(){
    let data={
      // "criteria": {
          // "projectId": $.store.get('projectId'),
          "tenantId":$.store.get('tenantId')
      // }
    }
    gethouseKeeper(data).then(res=>{
        let {data} = res;
        this.setData({houseKeeper:data})
    })
  },
  getFirstSpace(){
    const data = {
      "criteria": {
        "userId": $.store.get('userId'),
        "projectId": $.store.get('projectId'),
        "tenantId":  $.store.get('tenantId')
      }
    }
    getSpaceAdjustList(data).then((res)=>{
      if(res.count){
        let item = res.content[0];
        this.setData({
          spaceId:item.id,
          spaceName:item.localName
        })
      }
    })
  },
  async submitFeed(){
    if(!this.data.spaceId){
      wx.hideLoading();
      wx.showToast({
        title: '未选择空间',
        duration: 1500
      })
      return
    }
    if(!this.data.debunkValue&&!this.data.suggest&&!this.data.photoType){
      wx.hideLoading();
      wx.showToast({
        title: '请填写内容！',
        icon:'none',
        duration: 1500
      })
      return
    }
    let projectId = $.store.get('projectId') ||$.storage.get('projectId');
    let userId = $.store.get('userId') || $.storage.get('userId');
    let data={
      "projectId":projectId,
      "spaceId":this.data.spaceId,
      "userId":userId,
      "phone":$.store.get('phone'),//反馈人手机号
      "type":0,//反馈来源 0 小程序 1 app 2 pc
      "suggest":this.data.suggest,//反馈建议
    }
    this.data.debunkValue&&(data.item=this.data.debunkValue);
    console.log(this.data.photoType,"this.data.photoType")
    if(this.data.photoType!==''){
      let res  = await this.uploadFile();
      data.photoList=[{"type":this.data.photoType,"photo":this.data.fileName}]
    }
    submitFeedback(data).then(res=>{
      if(res.result=="success"){
        wx.hideLoading();
        setTimeout(function () {
          wx.showToast({
            title:"提交成功",
            duration: 2000
          })
        }, 300)
        this.setData({fileList:[],debunkValue:0,suggest:'',showUpload:true,photoType:''})
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    !this.formSearch&&this.getFirstSpace();
    this.getKeeper();
  },

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

  },

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

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

  },
})