// pages/answer/answer.ts
import { list } from '../../apis/report'
import { defaultConfig, defaultConfigFind } from '../../apis/inspection'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deal: null,
    oldDataDeal: false,
    expirationDay: '',

    reportId: '',

    selectIndex: '',
    reportList: [],
    dealOptions: [
      {
        label: '每次都询问',
        value: null,
      },
      {
        label: '每次都同意',
        value: true,
      },
      {
        label: '每次都拒绝',
        value: false,
      },
    ]
  },

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

  getInfo() {
    defaultConfigFind().then((res:any) => {
      console.log(res)
      if (res.d) {
        const { deal, expirationDay, oldDataDeal, reportId } = res.d
        this.setData({
          deal, expirationDay, oldDataDeal, reportId
        })
        this.setSelect()
      }
    })
  },

  getReportList() {
    list({
      size: 999999
    }).then((res:any) => {
      this.setData({
        reportList: res.d.records
      })
      this.setSelect()
    })
  },

  submit(){
    const {selectIndex, expirationDay, deal, oldDataDeal, reportList} = this.data
    if (!selectIndex) {
      wx.showToast({
        icon: 'none',
        title: '请选择报告'
      })
      return
    }
    if (!expirationDay) {
      wx.showToast({
        icon: 'none',
        title: '请输入查验有效期'
      })
      return
    }
    defaultConfig({
      expirationDay, deal, oldDataDeal,
      // @ts-ignore
      reportId: reportList[selectIndex].id
    }).then(() => {
      wx.showToast({
        icon: 'none',
        title: '设置成功!'
      })
      wx.navigateBack({
        delta: 1
      })
    })
  },

  setSelect() {
    const { reportList, reportId } = this.data
    if (reportList && reportId) {
      const index = reportList.findIndex((item:any) => item.id === reportId)
      if (index !== -1) {
        this.setData({
          selectIndex: index + ''
        })
      }
    }
  },

  reportChange(e:WechatMiniprogram.CustomEvent) {
    const { value } = e.detail
    this.setData({
      selectIndex: value
    })
  },
  changeDeal(e:WechatMiniprogram.BaseEvent) {
    const { value } = e.currentTarget.dataset
    this.setData({
      deal: value
    })
  },
  radioChange() {
    const { oldDataDeal } = this.data
    this.setData({
      oldDataDeal: !oldDataDeal
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})