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

      <view class="container">
        <view class="scroll-content">
          <wk-form
            ref="form"
            :fields="fieldArr"
            :batch-id="batchId"
            @change="handleValueChange" />

          <view class="empty-box" />
        </view>
      </view>

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

<script>
  import {
    QueryFieldList,
    AddContacts,
    UpdateContacts,
    GetList as crmContactsIndex
  } from 'API/crm/concat'

  import CreateMixins from '../mixins/create.js'
  import { deepCopy } from '@/utils/lib.js'

  export default {
    name: 'CreateContacts',
    mixins: [CreateMixins],
    data() {
      return {
        moduleType: 'contacts',
      }
    },
    onLoad() {
      this.getFieldList()
    },
    methods: {
      getFieldList() {
        const params = { type: 1 }
        if (this.id) params.id = this.id
        QueryFieldList(params)
          .then(res => {
            let searchList = []
            if (this.routerQuery.id) {
              let customerId = res.filter((item, index) => {
                return item.fieldName === 'customerId'
              })[0].value[0].customerId
              searchList.push({
                formType: 'text',
                name: 'customer_id',
                type: 1,
                values: [customerId]
              })
            }

            res.forEach(field => {
              // 自动编号为非必填
              if (field.autoGeneNumber === 1) {
                field.isNull = 0
              }

              if (!this.$isEmpty(field.authLevel)) {
                // 判断字段权限，如果没有权限则直接禁止修改
                field.disabled = this.getDisabledStatusByAuth(field)
                if (field.disabled) {
                  if (field.sys_config) {
                    field.sys_config.disabledMsg = ''
                  }
                }
              }

              field.value = this.mixinsFormatFieldValue(field)
              if (field.fieldName === 'parentContactsId') {
                if (this.routerQuery.id) {
                  field.sys_config = {
                    otherParams: {
                      searchList: searchList,
                      type: 3
                    }

                  }
                } else {
                  field.disabled = true
                  field.sys_config = {
                    disabledMsg: '请先选择客户'
                  }
                }

                // 客户下直属上级
              }
            })

            this.fieldArr = res
            this.setForm()
          })
          .catch(() => {
          })
      },

      /**
       * 表单值发生改变
       * @param {Object} data
       */
      handleValueChange(data) {
        this.changeAuditFlow(data.field, data.value)
        let findIndex = -1
        const bridge = getApp().globalData.formBridge
        const bridgeDefault = bridge.default || {}

        if (data.field.formType === 'customer') {
          // 如果修改的是客户
          const arr = ['parentContactsId']
          arr.forEach(key => {
            findIndex = this.fieldArr.findIndex(o => o.fieldName === key)
            if (findIndex !== -1 && !bridgeDefault.hasOwnProperty(key)) {
              const fieldItem = deepCopy(this.fieldArr[findIndex])
              fieldItem.value = []
              if (data.value.length > 0) {
                const searchList = [{
                  formType: 'text',
                  name: 'customer_id',
                  type: 1,
                  values: [data.value[0].customerId]
                }]
                fieldItem.sys_config.otherParams = {
                  searchList: searchList,
                  type: 3
                }
                fieldItem.disabled = false
              } else {
                fieldItem.sys_config = {
                  disabledMsg: '请先选择客户',
                  otherParams: {}
                }
                fieldItem.disabled = true
              }
              this.$refs.form.updateFields(findIndex, fieldItem)
            }
          })
        }
      },

      /**
       * 保存
       */
      handleSave() {
        this.loading = true
        this.$refs.form.getForm().then(async form => {
          if (this.id == form.entity.parentContactsId) {
            this.$toast('直属上级不能为当前联系人')
            this.loading = false
            return
          }

          this.baseFormatSaveData(form)
          // this.loading = false
          // return

          const request = this.id ? UpdateContacts : AddContacts
          request(form).then(() => {
            this.$toast(this.id ? '修改成功' : '添加成功')
            this.$refreshAndToPrev(this)
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          this.loading = false
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  @import '../style/create.scss';
</style>
