<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="添加团队成员">
        <!-- #ifndef MP-WEIXIN -->
        <button
          class="button white-btn"
          @click="handleSave">
          保存
        </button>
        <!-- #endif -->
      </wk-nav-bar>

      <view class="container">
        <wk-form
          ref="form"
          :fields="fieldArr"
          @change="formChange" />
      </view>

      <!-- #ifdef MP-WEIXIN -->
      <view class="footer-btn-group">
        <button class="button" @click="handleSave">
          保存
        </button>
      </view>
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
  import {AddMembers as CustomerAdd} from 'API/crm/customer'
  import {AddMembers as BusinessAdd} from 'API/crm/business'
  import {AddMembers as ContractAdd} from 'API/crm/contract'

  import Fields from '@/utils/fields.js'

  export default {
    name: 'GroupAdd',
    data() {
      return {
        id: null,
        type: null,

        apiMap: {
          customer: {fn: CustomerAdd, fields: 'customerId'},
          business: {fn: BusinessAdd, fields: 'businessId'},
          contract: {fn: ContractAdd, fields: 'contractId'}
        },

        fieldArr: [],

        loading: false
      }
    },
    onLoad(options) {
      this.routerQuery = options
      this.id = options.id
      this.type = options.type
      this.initForm()
    },
    methods: {
      initForm() {
        this.fieldArr = []
        const powerOptions = [
          {label: '只读', value: 1},
          {label: '读写', value: 2}
        ]
        const changeTypeOptions = [
          {label: '联系人', value: '1'},
          {label: '商机', value: '2'},
          {label: '合同', value: '3'},
        ]
        const timeOptions = [
          { label: '不限', value: '0' },
          { label: '截止到', value: '1' }
        ]
        let arr = [
          new Fields({name: '团队成员', formType: 'user', fieldName: 'memberIds', isNull: 1 }),
          new Fields({name: '成员权限', formType: 'select', fieldName: 'power', isNull: 1, defaultValue: [powerOptions[0]], setting: powerOptions})
        ]

        if (this.type === 'customer') {
          arr.push(new Fields({
            name: '添加到其他相关团队',
            formType: 'checkbox',
            fieldName: 'changeType',
            setting: changeTypeOptions,
            maxlength: 2
          }))
        }
        const arr0 = [
          new Fields({
            name: '有效时间',
            formType: 'select',
            fieldName: 'expiresTime',
            defaultValue: [timeOptions[0]],
            setting: timeOptions,
            isNull: 1,
            optionsData: {
              1: [1001]
            },
            remark: 'options_type'
          }),
          new Fields({
            name: '',
            formAssistId: 1001,
            formType: 'date',
            fieldName: 'time',
            defaultValue: null,
            setting: []
          })
        ]
        arr = arr.concat(arr0)
        this.fieldArr = arr
      },

      formChange(data) {
        if (data.field.fieldName === 'expiresTime') {
          if (this.$isEmpty(data.value)) {
            this.$refs.form.setFormVal('expiresTime', [{ label: '不限', value: '0' }])
          }
        }
      },

      handleSave() {
        if (this.loading) return
        this.loading = true
        this.$refs.form.getForm().then(form => {
          // console.log('form: ', form)
          form = form.entity
          const params = {
            power: form.power,
            memberIds: form.memberIds.split(',') || [],
            ids: [this.id]
          }
          if (this.type === 'customer' && !this.$isEmpty(form.changeType)) {
            params.changeType = form.changeType.split(',')
          }
          if (form.expiresTime === '1') {
            if (this.$isEmpty(form.time)) {
              this.$toast('截止时间不能为空')
              this.loading = false
              return
            }
            params.expiresTime = form.time
          } else {
            params.expiresTime = ''
          }

          this.apiMap[this.type].fn(params).then(response => {
            this.$toast('添加成功')
            this.loading = false
            this.$refreshAndToPrev(this)
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          this.loading = false
        })
      }
    }
  }
</script>

<style scoped lang="scss">
	.container {
		width: 100%;
		flex: 1;
		padding-bottom: 20rpx;
		margin-top: 20rpx;
	}
</style>
