// pages/interaction/interaction.js
const app = getApp(),
  {
    globalData: {
      util: {
        regeneratorRuntime,
        api: {
          departments,
          matters,
          interactionSave,
          guide
        },
        showTip,
        request: {
          post_auth,
          get
        },
        getUserInfo,
        goSuccess,
        get_global_param,
        verify: {
          isPhone,
          form_verify
        },
        pickerChange
      }
    }
  } = app,
  t = {
    name: '请选择'
  },
  init = {
    dep_index: 0,
    matter_index: 0,
    title: '',
    content: '',
    name: '',
    consultantPhone: ''
  }, verify = {
    consultantName: "请输入姓名",
    consultantPhone: x => x ? !isPhone(x) && '您输入的联系方式格式不正确' : '请输入联系方式',
    content: (x, { type }) => !x && `请输入${type == 1 ? '投诉' : '咨询'}内容`,
    deptUnid: (x, { type }) => !x && `请选择${type == 1 ? '投诉' : '咨询'}部门`,
    serviceUnid: (x, { type }) => !x && `请选择${type == 1 ? '投诉' : '咨询'}事项`,
    title: (x, { type }) => !x && `请输入${type == 1 ? '投诉' : '咨询'}主题`
  };


Page({
  data: Object.assign({
    dep_list: [t],
    matter_list: [t],
    tab: ['咨询', '投诉']
  }, init),

  async _pickerChange(_index, value) {
    this.setData({
      [_index]: value | 0
    })
    if (_index != 'dep_index') return
    let deptUnid = this.data.dep_list[value].id, matter_list = [t]
    if (deptUnid) {
      let list = await get(matters, { deptUnid })
      if (!list._err)
        matter_list = [t, ...list.map(({ UNID: id, SERVICE_NAME: name }) => ({ id, name }))]
    }
    this.setData({
      matter_index: 0,
      matter_list
    })

  },
  async formSubmit({ detail: { value } }) {
    const msg = form_verify(value, verify)
    if (msg) return showTip(msg)
    const { _err } = await post_auth(interactionSave, value, { loading: true, loadingMsg: '信息提交中。。。' });
    if (_err) return _err.status && showTip('提交失败')
    await goSuccess('interaction')
    this.setData(init)
  },
  async onLoad() {
    const list = await get(departments)
    this.setData({
      dep_list: list._err ? [t] : [t, ...list.map(({ deptUnid: id, deptName: name }) => ({ id, name }))]
    })
  },
  async onShow() {
    const { unid, tab_index = 0 } = get_global_param(), { name = '', phone = '' } = await getUserInfo()
    if (unid) {
      const { preService: { deptUnid, deptName, serviceName } = {}, } = await get(guide, { unid })
      this.setData({
        serviceUnid: unid,
        deptUnid,
        deptName,
        serviceName
      })
    }
    this.setData(Object.assign({}, init, {
      flag: !!unid,
      name,
      phone,
      tab_index
    }))
  },
  pickerChange,
  // tab切换
  tab({ currentTarget: { dataset: { index: tab_index } } }) {
    this.setData({
      tab_index
    })
  }
})