// index.js
var myRequest = require("../../utils/api.js");
var utils = require("../../utils/util.js");
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
})
let timer = null
Page({
  data: {
    value: '',
    show: false,
    autosize: {
      minHeight: 70
    },
    repairSceneId: '',
    repairSceneName: '',
    repairScene: {},
    iswarrantyPeriod: false,
    faultImg: [],
    list: [],

    faultDesc: '',
    address: '',
    cascaderValue: '',
    devicePhonenumber: '',
    deviceId: '',
    contactName: '',
    warrantyPeriod: '',
    contactPhone: '',
    remark: '',
    recorderManager: recorderManager,
    curTime: 0,
    recorder: {
      status: 'ready', // 'ready' | 'recording'
      text: '开始录音',
    },
    isPlay: false,
    secondes: 0,
    startTimestamp: 0,
    isupload: false,
    filePath: '',

  },
  onLoad() {
    let user = wx.getStorageSync('userInfo')
    this.getDefaultDevice(user.devicePhonenumber || user.phonenumber)
    this.setData({
      contactPhone: user.phonenumber

    })

  },
  actionRecoder() {
    if (this.data.recorder.status == 'ready') {
      this._startRecord()

    } else if (this.data.recorder.status == 'recording') {
      this._endRecord()
    } else if (this.data.recorder.status == 'recorded') {
      console.log('删除')
      clearInterval(timer)

      this.setData({
        curTime: 0,
        isPlay: false,
        secondes: 0,
        filePath: '',
        recorder: {
          status: 'ready', // 'ready' | 'recording'
          text: '开始录音',
        },

      })
    }
  },
  //开始录音的时候
  _startRecord() {
    this.data.startTimestamp = Date.now();
    const options = {
      duration: 600000, //指定录音的时长，单位 ms，最大为10分钟（600000），默认为1分钟（60000）
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    this.setData({
      recorder: {
        status: 'recording', // 'ready' | 'recording'
        text: '结束录音',
      },
    })

    //点击录制
    this.data.recorderManager.start(options);

    //开始录音计时
    this.countDown();

    this.data.recorderManager.onStart(() => {
      console.log('点击录制...')
    })

    //错误回调
    this.data.recorderManager.onError((res) => {
      console.log('录音失败', res);
    })
  },
  countDown() {
    timer = setInterval(() => {
      this.data.secondes++;
      console.log('倒计时中')
      this.setData({
        curTime: this.data.secondes
      });
    }, 1000);
  },

  //停止录音
  _endRecord() {
    clearInterval(timer);
    this.data.recorderManager.stop();
    this.data.recorderManager.onStop((res) => {
      console.log('停止录音', res)
      let filePath = res.tempFilePath;
      let duration = res.duration;
      if ((Date.now() - this.data.startTimestamp) / 1000 < 2) {

        wx.showToast({
          title: '录音时间太短!',
          icon: 'none',
          duration: 1500
        })
        this.setData({
          curTime: 0,

          recorder: {
            status: 'ready', // 'ready' | 'recording'
            text: '开始录音',
          },
        })
        return
      } else {
        this.setData({

          recorder: {
            status: 'recorded', // 'ready' | 'recording'
            text: '清除录音',
          },
        })
        this.uploadFile(filePath).then(res => {
          this.setData({
            filePath: res.url
          })
        })

      }

    })
  },

  //播放声音
  playCorder: function () {

    if (!this.data.filePath) {
      wx.showToast({
        title: '请录音后播放!',
        icon: 'none',
        duration: 1500
      })
      return
    }
    if (this.data.isPlay) {
      wx.showToast({
        title: '播放中。。。。',
        icon: 'none',
        duration: 1500
      })
      return
    }

    innerAudioContext.src = this.data.filePath,
      innerAudioContext.play()
    this.countDown()
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
      this.setData({
        curTime: 0,
        secondes: 0,
        isPlay: true,
      })

    })
    innerAudioContext.onEnded(() => {
      clearInterval(timer);
      this.setData({
        isPlay: false,
        // curTime:0
      })
      console.log('结束播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  onChangedevice(e) {
    console.log(e)
    if (e.detail.length == 11) {
      this.getDefaultDevice(e.detail)
    } else {
      this.setData({
        deviceId: '',
        devciceName: "",
        contactName: "",
        address: ""
      })
    }
  },
  getDefaultDevice(devicePhonenumber) {

    myRequest.myRequest('deviceRepairOrder/customer/deviceInfo', {
      phonenumber: devicePhonenumber
    }, 'get').then(res => {
      console.log(res)
      if (res.data) {
        this.setData({
          deviceId: res.data.id,
          iswarrantyPeriod: utils.DataCompare(res.data.warrantyPeriod, new Date()),
          devicePhonenumber,
          warrantyPeriod: res.data.warrantyPeriod.substring(0, 10),
          devciceName: res.data.name,
          contactName: res.data.ownerName,
          address: res.data.provinceName + res.data.cityName + res.data.areaName + res.data.townName + res.data.community
        })
        this.getRepairScene(res.data.deviceVersion)
      } else {
        wx.showToast({
          title: '当前登录手机号无设备绑定信息，请输入',
          icon: 'none'
        })
      }
    })
  },
  getRepairScene(deviceVersion) {
    myRequest.myRequest('deviceRepairOrder/customer/repairScene', {
      deviceVersion,
      sceneName: ''
    }, 'get').then(res => {
      console.log(res)

      this.setData({
        list: res.data
      })

    })
  },
  setDialog() {
    this.setData({
      show: true
    })
  },
  selectItem(e) {
    let {
      item
    } = e.currentTarget.dataset
    console.log(item)
    this.setData({
      show: false,
      repairSceneId: item.sceneId,
      repairSceneName: item.sceneName,
      repairScene: item
    })
  },
  onChange(event) {
    console.log(event)
    // event.detail 的值为当前选中项的索引
    let key = event.target.dataset.key
    this.setData({
      [key]: event.detail
    });
  },
  bindDel(e) {
    console.log(e)
    let faultImg = this.data.faultImg

    let delList = faultImg.splice(e.detail.index, 1)

    myRequest.myRequest('wx/oss/' + delList[0].ossId, {}, 'delete').then(res => {

      this.setData({
        faultImg
      })
    })
  },
  saveDetail() {

    if (!this.data.repairSceneId) {
      wx.showToast({
        title: '请选择维修类型',
        icon: 'none'
      })
      return
    }
    if (this.data.faultImg.length < 3) {
      wx.showToast({
        title: '请上传3张以上图片',
        icon: 'none'
      })
      return
    }
    if (!this.data.devciceName) {
      wx.showToast({
        title: '请输入正确的设备手机号',
        icon: 'none'
      })
      return
    }
    if (this.data.faultDesc == '' || this.data.contactName == '') {
      wx.showToast({
        title: '请输入报修详情',
        icon: 'none'
      })
      return
    }
    let {
      deviceId,
      contactName,
      contactPhone,
      faultDesc,
      devicePhonenumber,
      faultImg,
      repairSceneId,
      filePath
    } = this.data
    let img = faultImg.map(res => {
      return res.url
    })
    let data = {
      deviceId,
      contactName,
      repairSceneId,
      contactPhone,
      faultDesc,
      "faultImg": img,
      "remark": "",
      devicePhonenumber,
      faultVoice: filePath
    }
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    myRequest.myRequest('deviceRepairOrder/customer/create', data, 'post').then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '报修成功，等待维修人员上门维修',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1000);
    })
  },
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    console.log(event, callback)
    let flag = file.every(res => {
      return res.type === 'image' || res.type == "video"
    })
    callback(flag);
  },
  uploadFile(url) {
    return new Promise((resolve, reject) => {
      myRequest.updateImg({
        file: url
      }).then(res => {
        resolve(res)
      })
    })

  },

  afterRead(event) {
    const {
      file
    } = event.detail;
    let that = this;
    let upload = []
    file.forEach(element => {
      upload.push(this.uploadFile(element.url))
    })
     Promise.all(upload).then(res => {

      let faultImg = that.data.faultImg
      faultImg=[...faultImg,...res]
      that.setData({
        faultImg
      });
    })





  },
})