// pages/certificateCreate/certificateCreate.ts
import { certificateSave } from '../../apis/report'
import { getPayInfo } from '../../apis/pay'
import { timeCheck } from "../../apis/inspection"
import { parseTime } from "../../utils/index"
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    name: '',
    authorizationTimes: '',
    endDate: '',

    startDate: parseTime(new Date().getTime(), '{y}-{m}-{d}'),
    isEveryone: false,
    unNum: false,
    unTime: false,

    dayPrice: '0.00',
    electronicCertificateSinglePayment: '0.00',
    memberShow: false,
    etcDefaultName: '',
    whiteList: <any>[],
    phone: '',
    addPhoneShow: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    const { id } = options
    this.setData({
      id
    })
    this.getNum()
    this.getPrice()
    this.nameInit()
  },
  nameInit() {
    const now = new Date();

    let etcDefaultName =
      now.getFullYear() +
      "" +
      (now.getMonth() + 1 < 10
        ? "0" + (now.getMonth() + 1)
        : now.getMonth() + 1) +
      "" +
      (now.getDate() < 10 ? "0" + now.getDate() : now.getDate()) +
      "" +
      (now.getHours() < 10 ? '0' + now.getHours() : now.getHours()) +
      (now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()) +
      (now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds());

    this.setData({
      etcDefaultName: etcDefaultName + ',可点击修改'
    })
  },
  submit() {
    const { id, name, authorizationTimes, endDate, unNum, unTime, etcDefaultName, whiteList, isEveryone } = this.data
    // if (!name) {
    //   wx.showToast({
    //     icon: 'none',
    //     title: '请输入证书名称'
    //   })
    //   return
    // }
    if (!unNum && !authorizationTimes) {
      wx.showToast({
        icon: 'none',
        title: '请输入查看次数'
      })
      return
    }
    if (!unTime && !endDate) {
      wx.showToast({
        icon: 'none',
        title: '请选择授权期限'
      })
      return
    }
    certificateSave({
      reportId: id,
      name: name ? name : etcDefaultName.split(',')[0],
      authorizationTimes: unNum ? undefined : authorizationTimes,
      endDate: unTime ? undefined : (new Date(endDate + ' 23:59:59').getTime() / 1000),
      whiteList: isEveryone ? undefined : whiteList.toString()
    }).then(() => {
      this.hideShadow()
      wx.showToast({
        icon: 'none',
        title: '创建成功!'
      })
      wx.navigateBack({
        delta: 1
      })
    }).catch(err => {
      if (err.c === 501005) {
        this.showShadow()
      } else {
        this.hideShadow()
      }
    })
  },
  buyOnce() {
    app.pay('ELECTRONIC_CERTIFICATE_SINGLE_PAYMENT').then(() => {
      this.submit()
    })
  },
  getNum() {
    if (!app.memberVerify()) return
    timeCheck().then((res: any) => {
      this.setData({
        num: res.d
      })
    })
  },
  getPrice() {
    getPayInfo({}).then((res: any) => {
      const { electronicCertificateSinglePayment, annualFee } = res.d
      this.setData({
        electronicCertificateSinglePayment,
        dayPrice: (annualFee / 100 / 356).toFixed(2)
      })
    })
  },
  jumpMember() {
    wx.navigateTo({
      url: '/pages/member/member'
    })
    this.hideShadow()
  },
  showShadow() {
    this.setData({
      memberShow: true
    })
  },
  hideShadow() {
    this.setData({
      memberShow: false
    })
  },
  bindDateChange(e: WechatMiniprogram.CustomEvent) {
    const { value } = e.detail
    this.setData({
      endDate: value
    })
  },
  switchChange(e: WechatMiniprogram.CustomEvent) {
    const { key } = e.currentTarget.dataset
    const { value } = e.detail
    this.setData({
      [key]: value
    })
  },
  showAddPhone() {
    this.setData({
      addPhoneShow: true
    })
  },
  handleContact() {
    let { whiteList } = this.data
    wx.chooseContact({
      success: t => {
        let temp = t.phoneNumber.replaceAll('-', '').replaceAll(' ', '')
        if (temp.length !== 11) {
          wx.showToast({
            icon: 'none',
            title: '手机号格式错误!'
          })
          return
        } else {
          whiteList.push(temp)
          this.setData({
            whiteList
          })
        }
      },
      fail: e => console.log(e),
      complete: () => { }
    })
  },
  closeAddPhone() {
    this.setData({
      addPhoneShow: false
    })
  },
  addPhone() {
    let { whiteList, phone } = this.data

    if (!phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入授权手机号'
      })
      return
    }
    if (phone.length !== 11) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误'
      })
      return
    }
    // console.log(phone);
    if (whiteList.indexOf(phone) > -1) {
      wx.showToast({
        icon: 'none',
        title: '已添加该手机号'
      })
      return
    }
    whiteList.push(phone)
    this.setData({
      whiteList,
      addPhoneShow: false,
      phone: ''
    })
  },
  handleDeletePhone(e) {
    let { whiteList } = this.data
    whiteList.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      whiteList
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})

export { }
