// pages/repair/repair.js
const app = getApp();
var orgId = 0;
var depId = 0;
var mode = 0;
var filescount = 0;
var files = [];
var uploadFlag = 0; //1=上传出错 0=正常
var filesindex = 0;
var phone = '';
var ysconfig = 0;
//创建录音管理
const recorderManager = wx.getRecorderManager();
//创建播放管理器
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.autoplay = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    taskContent: {
      title: '任务内容',
      showImg: '/images/icons/recording.png',
      playImg: '/images/icons/play.png',
      blImg: '/images/icons/bl.png',
      readingImg: '/images/icons/recording.png',
      luyinzhongImg: '/images/icons/luyinzhong.png',
      stopPlayImg: '/images/icons/zanting.png',
      delimg: '/images/icons/newdel.png',
      taskRadioType: '1',
      radioUrl: '',
      second: 10,
      // mode: 0
    },
    // repairType: {
    //   title: '报修类型'
    // },
    conveyType: {
      list: {},
      title: '运送类型',
      text: ''
    },
    conveyTime: {
      hour: 0,
      min: 0,
      title: '运送时间',
      text: '立即'
    },
    conveyAddr: {
      title: '运送路线',
      startAddr: '',
      startId: 0,
      finishAddr: '',
      finishId: 0
    },
    image: {
      title: '图片'
    },
    video: {
      title: '视频'
    },
    repairTypeImage: '/images/icons/toRight.png',
    imagesAdd: '/images/icons/camera.png',
    form:{
      images: [],
      videos: [],
      voices: []
    },
    images:[],
    videos:[],
    voices:'',
    content:'',
    mode: 3,
    hide: 0,
    conveyTimePicker:{
      multiArray:[],
      objectMultiArray:[],
      multiIndex: [0, 0]
    },
    deptcontent: '',
    showFileSheet: false,
    choosefinish: false,
    choosefinishline: false,
    label:'',
    selectLabel:[],
    depId:0,
    depName:"",
    wyPhone:"",
    conveyTypeId: 0,
    conveyTypeName: '',
    conveyStart: 0,
    conveyStartName: '',
    conveyEnd: 0,
    conveyEndName: '',
    conveyDevice: 0,
    conveyDeviceName: '',
    conveyTypeCate:0,
    priority:0,
    priorityName:'',
    is_back:0,
    name:"",
    phone:"",
    ch:"",
    bName:"",
    bah:"",
    gender:1,
    xqTime:"",
    ywcTime:"",
    sex:[{
       name:'男',value:1,checked:"true"
    },{
        name:'女',value:2
    }]

  },
  radioChange: function (e) {
     this.setData({
         gender:e.detail.value
     })
  },
  wyConfig(){
      app.ajax({
        url: app.globalData.serverUrl + '/org/queryConfig',
        type: 'POST',
        apiname: 'wyConfig',
        data: {

        }
      });
  },
  name(e){
      this.setData({
          name:e.detail.value
      })
  },
  phone(e){
      this.setData({
          phone:e.detail.value
      })
  },
  ch(e){
      this.setData({
          ch:e.detail.value
      })
  },
  bName(e){
      this.setData({
          bName:e.detail.value
      })
  },
  bah(e){
      this.setData({
          bah:e.detail.value
      })
  },

  gotopage: function(e){
      var url = e.currentTarget.dataset.url;
      var type = e.currentTarget.dataset.type;
      var title = e.currentTarget.dataset.title;

      app.gotopage(url, { title: title, type: type });
  },

  onLoad: function(){
    var that = this;
    //初始化时间选中器
    var hours = [];
    var hourdatas = [];
    for(let i = 0;i <= 12; i++){
      let title,val;
      if(i == 0){
        title = '立即';
      }else{
        title = i + '小时';
      }
      hours.push(title);
      hourdatas.push({title:title,val:i});
    }

    var mins = [];
    var mindatas = [];
    for (let i = 0; i < 60; i++) {
      let title, val;
      if (i == 0) {
        title = '立即';
      } else {
        title = i + '分钟';
      }
      mins.push(title);
      mindatas.push({ title: title, val: i });
    }

    var conveyTimePicker = {
      multiArray: [hours, mins],
      objectMultiArray: [hourdatas, mindatas],
      multiIndex: [0, 0]
    }
    this.setData({
      conveyTimePicker: conveyTimePicker
    });


    
    recorderManager.onStart(() => {
      var taskContent = that.data.taskContent;
      taskContent.showImg = taskContent.luyinzhongImg;
      taskContent.taskRadioType = '2';
      that.setData({
        taskContent: taskContent
      })
    })
    recorderManager.onPause(() => {
      
    })

    recorderManager.onStop((res) => {
      var path = res.tempFilePath;
      var task = that.data.taskContent;
      task.taskRadioType = '3';
      task.showImg = task.playImg;
      task.second = Math.ceil(res.duration / 1000);
      that.setData({
        voices: path,
        taskContent: task
      });
      // const { tempFilePath } = res
    })
    recorderManager.onError((res) => {
      wx.showToast({
        title: '录音失败',
        icon: 'none',
        duration: 2000
      });
      var task = that.data.taskContent;
      task.taskRadioType = '1';
      task.showImg = task.readingImg;
      that.setData({
        voices: '',
        taskContent: task
      });
    });

    this.getUserInfo();
  },

    checkboxChange: function(e){
        var data = e.detail.value;
        if(data.length >0){
            this.setData({
                is_back:1
            })
        }else {
            this.setData({
                is_back:0
            })
        }
    },
    callPhone(){
        var that = this;
        if(!that.data.wyPhone){
            wx.showToast({
                title: '未设置物业电话',
                icon: 'none',
                duration: 2000
            });
            return false;
        }
        wx.makePhoneCall({
            phoneNumber: that.data.wyPhone,
        })
    },
  onShow: function(){
    var that = this;
    app.ajaxReadyCallback = res => {
      var apiname = res.data.apiname;
     if (apiname == 'ysconfig'){
        let ysll = res.data.data;
        if(ysll.length > 0){
          ysconfig = parseInt(ysll[0].value)
        }
      }else if(apiname == 'wyConfig'){
          that.setData({
              wyPhone:res.data.data.orgPhone
          })
         ysconfig = res.data.data.orgScanQrcode;
      } else if(apiname == 'orderAdd'){
         wx.showToast({
           title: '提交成功',
           icon: 'success',
           duration: 1500
         });
         setTimeout(function () {
           wx.navigateBack({ delta: 1 });
         }, 1500);
     }else if(apiname == 'userInfo') {         
        that.setData({
            depId:res.data.data.depId,
            depName:res.data.data.depName,
        })
   
    }else {
        // wx.showToast({
        //   title: '提交成功',
        //   icon: 'success',
        //   duration: 1500
        // });
        // setTimeout(function () {
        //   wx.navigateBack({ delta: 1 });
        // }, 1500);
      }
    };
      this.wyConfig();

  },

  onTouchstartRadio: function(event) {
    var radioType = this.data.taskContent.taskRadioType;
    if (radioType == 1) {
      //开始录音
      var options = {
        duration: 15000,
        sampleRate: 44100,
        numberOfChannels: 1,
        encodeBitRate: 192000,
        format: 'mp3',
        frameSize: 50
      }
      recorderManager.start(options);
    }
  },
  
  onTouchendRadio: function(event) {
    var radioType = this.data.taskContent.taskRadioType;
    var that = this;
    if (radioType == 2) {
      recorderManager.stop();
    }
  },
  //播放录音
  playRadio: function(event) {
    var taskContent = this.data.taskContent;
    var radioType = taskContent.taskRadioType;
    if (radioType == 3) {
      var radioUrl = this.data.voices;
      innerAudioContext.src = radioUrl;
      innerAudioContext.play();
      innerAudioContext.onPlay(() => {
        taskContent.taskRadioType = 4;
        taskContent.showImg = taskContent.stopPlayImg;
        this.setData({
          taskContent: taskContent
        })
      });
      innerAudioContext.onError((res) => {
        // console.log(res)
      });
      //监听音频自然播放至结束的事件
      innerAudioContext.onEnded((res) => {
        taskContent.taskRadioType = 3;
        taskContent.showImg = taskContent.playImg;
        this.setData({
          taskContent: taskContent
        })
      });
    } else if (radioType == 4) {
      innerAudioContext.stop();
      //监听音频停止事件
      innerAudioContext.onStop((res) => {
        taskContent.taskRadioType = 3;
        taskContent.showImg = taskContent.playImg;
        this.setData({
          taskContent: taskContent
        })
      });
    }
  },

  choosefile : function(){
    let that = this;
    wx.showActionSheet({
      itemList: ['选择图片','选择视频'],
      success(res) {
        if (res.tapIndex == 0){
          if (that.data.images.length >= 3){
            wx.showToast({
              title: '图片最多只能上传3张',
              icon: 'none',
              duration: 2000
            });
          }else{
            that.chooseImg();
          }
        } else if (res.tapIndex == 1){
          if (that.data.videos.length >= 1) {
            wx.showToast({
              title: '视频最多只能上传1个',
              icon: 'none',
              duration: 2000
            });
          } else {
            that.chooseVideo();
          }
        }
      },
      fail(res) {
        // console.log('fail')
      },
    })
  },

  chooseImg: function(){
    var imgs = this.data.images;
    var that = this;
    var count = 3 - imgs.length;
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var files = res.tempFilePaths;
        imgs = imgs.concat(files);
        that.setData({
          images: imgs
        });
        that.checkfiles();
      }
    })
  },

  checkfiles: function(){
    if (this.data.videos.length >= 1 && this.data.images.length >= 3) {
      this.setData({
        choosefinish: true,
      });
    }else{
      this.setData({
        choosefinish: false,
      });
    }
    if (this.data.videos.length >= 1 || this.data.images.length >= 1){
      this.setData({
        choosefinishline: true
      });
    }else{
      this.setData({
        choosefinishline: false
      });
    }
  },

  chooseVideo: function () {
    var that = this;
    let maxDuration = 15;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      compressed: true,
      maxDuration: maxDuration,
      camera: 'back',
      success(res) {
        if (res.duration > maxDuration){
          wx.showToast({
            title: '视频时长不能超过' + maxDuration +'秒',
            icon: 'none',
            duration: 2000
          });
          return false;
        }
        let videos = [];
        videos.push(res.tempFilePath);
        that.setData({
          videos: videos
        });
        that.checkfiles();
      }
    })
  },

    uploadFiles: function(){
        var that = this;
        if (files.length > 0){
            wx.uploadFile({
                url: app.globalData.uploadServerUrl + 'upload/upfile',
                filePath: files[filesindex].path,
                name: 'uploadFile',
                formData: {
                    // 'ttype': mode,
                    // 'orgId': orgId
                },
                success(res) {
                    var data =JSON.parse(res.data);
                    if (data.code != 0) {
                        wx.hideLoading();
                        wx.showToast({
                            title: '文件上传失败1',
                            icon: 'none',
                            duration: 2000
                        });
                        that.setData({
                            form:{
                                images:[],
                                voices:[],
                                videos:[]
                            }
                        })
                        return false;
                    }else{
                        var form = that.data.form;
                        if (files[filesindex].type == 'image'){
                            form.images.push(data.data.path);
                        } else if (files[filesindex].type == 'video'){
                            form.videos.push(data.data.path);
                        }else{
                            form.voices.push(data.data.path);
                        }
                        filescount--;
                        if(filescount == 0){ //提交表单
                            that.addorder();
                        }else{ //继续上传
                            filesindex++;
                            that.uploadFiles();
                        }
                    }
                },
                fail(res){
                    wx.hideLoading();
                    wx.showToast({
                        title: '文件上传失败',
                        icon: 'none',
                        duration: 2000
                    });
                    that.setData({
                        form: {
                            images: [],
                            voices: [],
                            videos: []
                        }
                    })
                    return false;
                }
            })
        }
    },

  delfile: function(e){
    var type = e.currentTarget.dataset.type;
    var path = e.currentTarget.dataset.path;
    if(type == 'image'){
      var imgs = this.data.images;
      var newsimgs = [];
      for(var i in imgs){
        if (imgs[i] == path){
          continue;
        }
        newsimgs.push(imgs[i]);
      }
      this.setData({
        images: newsimgs
      });
      this.checkfiles();
    }else if(type == 'video'){
      var videos = this.data.videos;
      var newvideos = [];
      for (var i in videos) {
        if (videos[i] == path) {
          continue;
        }
        newvideos.push(videos[i]);
      }
      this.setData({
        videos: newvideos
      });
      this.checkfiles();
    }else{
      var task = this.data.taskContent;
      task.showImg = task.readingImg;
      task.taskRadioType = '1';
      this.setData({
        voices: '',
        taskContent: task
      });
    }
  },

  btnsubmit: function(e){

    //数据初始化
    files = [];
    filescount = 0;
    uploadFlag = 0;
    filesindex = 0;
      if (!this.data.content && !this.data.voices && this.data.videos.length == 0) {
          wx.showToast({
              title: '请填写任务内容',
              icon: 'none',
              duration: 2000
          });
          return false;
      }
      if (ysconfig == 1){ //强制扫码,地点必须选择
          if(this.data.conveyStart <= 0){
              wx.showToast({
                  title: '未选择收件地点',
                  icon: 'none',
                  duration: 2000
              });
              return false;
          }
          if (this.data.conveyEnd <= 0) {
              wx.showToast({
                  title: '未选择送达地点',
                  icon: 'none',
                  duration: 2000
              });
              return false;
          }
      }
      if (this.data.conveyStart > 0 && this.data.conveyEnd > 0 && this.data.conveyStart == this.data.conveyEnd){
          wx.showToast({
              title: '收件地点与送达地点不能相同',
              icon: 'none',
              duration: 2000
          });
          return false;
      }
      if (this.data.conveyTypeId <= 0) {
          wx.showToast({
              title: '请选择运送类型',
              icon: 'none',
              duration: 2000
          });
          return false;
      }
      if (!this.data.xqTime) {
          wx.showToast({
              title: '需求时间不能为空',
              icon: 'none',
              duration: 2000
          });
          return false;
      }
      if (!this.data.ywcTime) {
          wx.showToast({
              title: '完成时间不能为空',
              icon: 'none',
              duration: 2000
          });
          return false;
      }
      if (this.data.depId==0) {
          wx.showToast({
              title: '请选择部门',
              icon: 'none',
              duration: 2000
          });
          return false;
      }
    var formdata = {
      images: this.data.images,
      voices: this.data.voices?[this.data.voices]:[],
      videos: this.data.videos,
    }

    if (formdata.voices.length > 0) {
      for (var i in formdata.voices){
        var file = {
          path: formdata.voices[i],
          type: 'voice'
        }
        files.push(file);
      }
    }

    if (formdata.images.length > 0) {
      for (var i in formdata.images) {
        var file = {
          path: formdata.images[i],
          type: 'image'
        }
        files.push(file);
      }
    }

    if (formdata.videos.length > 0) {
      for (var i in formdata.videos) {
        var file = {
          path: formdata.videos[i],
          type: 'video'
        }
        files.push(file);
      }
    }
    //上传文件
    if(files.length > 0){
      filescount = files.length;
      wx.showLoading({
        title: '提交中',
        mask: true
      });
      this.uploadFiles();
    }else{
      this.addorder();
    }
  },
  onPickerChange3: function (e) {
      this.setData({
          xqTime: e.detail.dateString
      })
  },
  onPickerChange4: function (e) {
      console.log(e);
      this.setData({
          ywcTime: e.detail.dateString
      })
  },
  addorder: function(){
    var that = this;
    var form = that.data.form;
    var formimages = '';
    if (form.images.length > 0) {
      formimages = form.images.join(",");
    }
    var formvoices = '';
    if (form.voices.length > 0) {
      formvoices = form.voices.join(",");
    }
    var formvideos = '';
    if (form.videos.length > 0) {
      formvideos = form.videos.join(",");
    }

    var url = app.globalData.serverUrl + '/orders/add';
    app.ajax({
      url: url,
      apiname:"orderAdd",
      type: 'POST',
      data: {
          depId: that.data.depId,
          content: that.data.content,
          images: formimages,
          voices: formvoices,
          videos: formvideos,
          workTypeMode: 3,
          start: that.data.conveyStart,
          end: that.data.conveyEnd,
          xqTime: that.data.xqTime,
          ywcTime: that.data.ywcTime,
          type: that.data.conveyTypeId,
          name: that.data.name,
          phone: that.data.phone,
          deviceId: that.data.conveyDevice,
          priority: that.data.priority,
          pName: that.data.bName,
          bedNumber: that.data.ch,
          baNumber: that.data.bah,
          gender: that.data.gender,
          back: that.data.is_back,

      }
    });
  },

  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.images, // 需要预览的图片http链接列表  
      success: function (e) {}
    })
  },

  videotap: function (e) {
    var video = e.target.dataset.video;
    app.gotopage('/pages/video/index', { video: video });
    // wx.navigateTo({
    //   url: '/pages/video/index',
    //   success: function (res) {
    //     res.eventChannel.emit('acceptDataFromOpenerPage', { video: video })
    //   }
    // })
  },

  contentChange: function (e) {
    this.setData({
      content: e.detail.value
    })
  },


  hideChange: function(e) {
    var hide = this.data.hide == 1?0:1;
    this.setData({
      hide: hide
    })
  },

  bindMultiPickerChange: function (e) {
    let hour = e.detail.value[0];
    let min = e.detail.value[1];
    let conveyTime = this.data.conveyTime;
    if(hour == 0 && min == 0){
      conveyTime.text = '立即';
    } else if (hour == 0){
      conveyTime.text = min + '分钟后送达';
    }else{
      if (min == 0){
        conveyTime.text = hour + '小时后送达';
      }else{
        conveyTime.text = hour + '小时' + min + '分钟后送达';
      }
    }
    conveyTime.hour = hour;
    conveyTime.min = min;
    this.setData({
      conveyTime: conveyTime
    });
  },
  goSelect(e){
        let that = this;
        let type = e.currentTarget.dataset.type;
        wx.navigateTo({
            url: '/pages/meeting/select/index',
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                acceptDataFromOpenedPage: function(data) {
                    console.log(data)
                    let a = [];
                    if(data.select.length > 2){
                        a.push(data.select[0]);
                        a.push(data.select[1]);
                    }else{
                        data.select.forEach((item) => {
                            a.push(item);
                    });
                    }

                    if(data.type == 1){
                        let strs = [];
                        a.forEach((item) => {
                            strs.push(item.stimetext+'~'+item.etimetext);
                    });
                        let str = strs.join(',');
                        if(data.select.length > 2){
                            str += '...';
                        }
                        that.setData({
                            selectTimes: data.select,
                            timesLabel: str
                        });
                    }else if(data.type == 2){
                        let strs = [];
                        a.forEach((item) => {
                            strs.push(item.realName);
                    });
                        let str = strs.join(',');
                        if(data.select.length > 2){
                            str += '...';
                        }
                        that.setData({
                            selectUser: data.select,
                            userLabel: str
                        });
                    }else if(data.type == 3){
                        let strs = [];
                        a.forEach((item) => {
                            strs.push(item.title);
                    });
                        let str = strs.join(',');
                        if(data.select.length > 2){
                            str += '...';
                        }
                        that.setData({
                            selectDevice: data.select,
                            deviceLabel: str
                        });
                    }else if(data.type == 4){
                        let strs = [];
                        a.forEach((item) => {
                            strs.push(item.name);
                    });
                        let str = strs.join(',');
                        if(data.select.length > 2){
                            str += '...';
                        }
                        that.setData({
                            selectLabel: data.select,
                            label: str
                        });
                    }
                }
            },
            success: function(res) {
                // 通过eventChannel向被打开页面传送数据
                if(type == 1){
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        type: type,
                        list: that.data.info.times,
                        select:that.data.selectTimes
                    });
                } else if (type == 2){
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        type: type,
                        list: [],
                        select:that.data.selectUser
                    });
                } else if (type == 3){
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        type: type,
                        list: that.data.info.devices,
                        select:that.data.selectDevice
                    });
                }else if (type == 4){
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        type: type,
                        list: [],
                        select:that.data.selectLabel
                    });
                }

            }
        })
    },

    getUserInfo(){
        app.ajax({
            url: app.globalData.serverUrl + '/User/info',
            type: 'POST',
            apiname:'userInfo',
            data: {
    
            }
        });
    },

})


