// pages/room/add.js
const api = require('../../config/api.js');
const util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sceneList: [],
    hostList: [],

    currentUser: {},
    dateMinute: '',
    assistantList: [],
    detail: {
      name: '',
      scene: "", //直播label
      brandId: '', //直播场景ID
      anchorUserId: '', //主持人ID
      assistantUserId: '', //助理用户iD
      assistant: "", // 助理label
      effectiveStartTime: '',
      effectiveEndTime: '',
    },
    fetcherData: {
      type: 32,
      address: "",
      page: 1,
      size: 20,
      name: "",
    }
  },

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

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    this.getAssistantsList();
    this.getSceneList();

    let user = await wx.getStorageSync('userinfoDetail')

    this.setData({
      currentUser: user,
      "detail.anchorUserId": user.userId
    })
    // debugger
  },

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

  },

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

  },

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

  },

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

  },

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

  },

  async getAssistantsList() {
    let {userId} = wx.getStorageSync('userinfoDetail')
    try {
      const res = await util.request(api.getAssistants, this.data.fetcherData, 'POST', 'application/json')
      if (res.code === 200) {

        if (Array.isArray(res.data)) {
          Array.from(res.data).forEach(assistant => {
            assistant.name = assistant.nickname
            assistant.id = assistant.userId
          })
        this.setData({
            assistantList: res.data.filter(ele => ele.userId !== userId)
          })

        }

      }


    } catch (error) {
      console.log('getAssistantsList::error', error)
    }


  },
  async getSceneList() {
    try {
      const res = await util.request(api.BrandList, this.data.fetcherData, 'POST')
      console.log('getSceneList', res.data.data);
      if (res.code === 200) {
        this.setData({
          sceneList: res.data.data
        })
      }

    } catch (error) {
      console.log('getSceneList::error', error)
    }

  },
  pickerChange: function (e) {
    const abj = {
      'scene': this.data.sceneList,
      'host': this.data.hostList,
      'assistant': this.data.assistantList,
    }
    const {
      type,
      name
    } = e.currentTarget.dataset
    let item = abj[name][e.detail.value];
    let detail = this.data.detail;
    detail[type] = e.detail.value;
    detail[name] = item.name;

    this.setData({
      [name]: item.id,
      detail,
    }, () => {
      console.log('picker值为', type, name, detail, item, )
    })
  },

  handleRoomName: function (e) {
    this.setData({
      'detail.name': e.detail.value
    })
  },

  sceneChange: function (e) {
      console.log('sceneChange', e)
      const index = e.detail.value
    if (index > -1) {
      const select = this.data.sceneList[index]
      console.log('picker值为', select)
      this.setData({
        'detail.scene': select.name,
        "detail.brandId": select.id
      })
    }
  },

  assistantChange: function (e) {
    const index = e.detail.value
    if (index > -1) {
      const select = this.data.assistantList[index]
      console.log('picker值为', select)
      this.setData({
        'detail.assistant': select.nickname,
        "detail.assistantUserId": select.userId
      })
    }
  },
  /**
   * 年月日时分选择类型的回调函数，可以在该函数得到选择的时间
   */
  selectDateMinuteChange(ev) {
    const {
      type
    } = ev.currentTarget.dataset
    let detail = JSON.parse(JSON.stringify(this.data.detail))
    detail[type] = ev.detail.value
    //判断大小
    console.log(detail,this.data.detail)
    if (detail.effectiveEndTime && detail.effectiveStartTime) {
      let value = new Date(detail.effectiveEndTime.replace(/-/g, "/")) - new Date(detail.effectiveStartTime.replace(/-/g, "/"));
      console.log(value,  new Date(detail.effectiveEndTime.replace(/-/g, "/")).getMinutes(),new Date(detail.effectiveStartTime.replace(/-/g, "/")).getMinutes())
      if (value <= 0 ) {
        return wx.showToast({
          title: '结束时间大于开始时间',
          icon: 'none',
          duration: 1000
        })
      }
      if (new Date(detail.effectiveEndTime.replace(/-/g, "/")).getTime()<new Date()) {
        return wx.showToast({
          title: '结束时间需大于现在',
          icon: 'none',
          duration: 1000
        })
      }
    }
    this.setData({
      detail
    })
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  toReportScene: function(e) {
    let sceneList = this.data.sceneList
    if(sceneList && sceneList.length == 0){
      this.toReport()
    }
  },
  toReportAssistant: function(e) {
    let assistantList = this.data.assistantList
    if(assistantList && assistantList.length == 0){
      this.toReport()
    }
  },
  assistantClear(){
    this.setData({
      'detail.assistant': '',
      'detail.assistantUserId': '',
    })
  },
  toReport: function(e) {
    return wx.showToast({
      title: '暂无数据',
      icon: 'none',
      duration: 1000
    })
  },
  sbmit: async function () {
    const {
      name,
      id,
      brandId,
      anchorUserId,
      effectiveStartTime,
      effectiveEndTime,
      assistantUserId
    } = this.data.detail

    let err = ''
    if (!name) {
      err = '请输入房间名称'
    } else if (!brandId) {
      err = '请选择直播场景'
    } else if (!anchorUserId) {
      err = '请选择主持人'
    } else if (!anchorUserId) {
      err = '请选择主持人'
    } else if (!effectiveStartTime) {
      err = '请选择开始时间'
    } else if (!effectiveEndTime) {
      err = '请选择结束时间'
    }
    let iconRule2 = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig
    if(iconRule2.test(name)){
      err = '房间名称仅支持中英文'
    }
    if (err) {
      return wx.showToast({
        title: err,
        icon: 'none',
        duration: 1000
      })
    }
    let res = await util.request(api.createOrUpdate, {
      name,
      brandId, //直播场景ID
      anchorUserId, //主持人ID
      assistantUserId, //助理用户iD
      effectiveStartTime: new Date(effectiveStartTime.replace(/-/g, "/")).getTime() ,
      effectiveEndTime: new Date(effectiveEndTime.replace(/-/g, "/")).getTime() ,
    }, "POST", 'application/json')

    // debugger

    if (res.code == 200) {
      wx.showToast({
        title: '创建成功！！',
        icon: "success"
      })
      // wx.navigateBack({
      //   delta: 0,
      // })
      wx.navigateBack()
    } else {
      wx.showToast({
        title: res.error || '创建失败！！',
        icon: "none"
      })
    }
  }
})