<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" />

          <product-choose-add
            v-if="productField"
            ref="product"
            :default-value="productField.value"
            @change="handleChangeProduct" />

          <wk-audit-add
            v-if="showAudit"
            ref="wkAuditAdd" />
        </view>
      </view>

      <!-- #ifdef MP-WEIXIN -->
      <view class="footer-btn-group">
        <button
          v-if="productField"
          class="button choose-product-btn"
          @click="handleAddProduct">
          添加产品
        </button>
        <button class="button" @click="handleSave">
          保存
        </button>
      </view>
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
  import {
    QueryFieldList,
    AddContract,
    UpdateContract
  } from 'API/crm/contract'
  import {
    QueryBusiness as QueryBusinessByCustomerId,
    QueryContacts as QueryContactsByCustomerId
  } from 'API/crm/customer'
  import {
    QueryProduct as BusinessProduct
  } from 'API/crm/business'

  import ProductChooseAdd from '../components/baseAdd/productChooseAdd.vue'

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

  export default {
    name: 'CreateContract',
    components: {
      ProductChooseAdd
    },
    mixins: [CreateMixins],
    data() {
      return {
        moduleType: 'contract',

        productField: null,
        defaultProductList: {}
      }
    },
    onLoad() {
      this.getFieldList()
    },
    methods: {
      getFieldList() {
        const params = { type: 1 }
        if (this.id) params.id = this.id
        QueryFieldList(params)
          .then(res => {
            let findIndex = res.findIndex(o => o.formType === 'product')
            if (findIndex !== -1) {
              this.productField = res.splice(findIndex, 1)[0]
            }

            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 === 'businessId') {
                // 客户下商机
                field.disabled = true
                field.sys_config = {
                  request: QueryBusinessByCustomerId,
                  otherParams: {},
                  disabledMsg: '请先选择客户'
                }
              } else if (field.fieldName === 'contactsId') {
                // 客户下联系人
                field.disabled = true
                field.sys_config = {
                  request: QueryContactsByCustomerId,
                  otherParams: {},
                  disabledMsg: '请先选择客户'
                }
              }
            })

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

      /**
       * 去选择产品
       */
      handleAddProduct() {
        this.$nextTick(() => {
          if (this.$refs.product) {
            this.$refs.product.handleChoose()
          }
        })
      },

      /**
       * 获取商机下产品
       * @param {Object} id
       */
      getProductList(id) {
        if (!id) return
        BusinessProduct({
          businessId: id,
          pageType: 0,
        })
          .then(response => {
            response.product = response.list
            delete response.list
            this.$set(this.productField, 'value', response)
          })
          .catch(() => {})
      },

      /**
       * 确认选择的产品
       * @param {Object} data
       */
      handleChangeProduct(data) {
        console.log('change product: ', data)
        if (this.$refs.form) {
          this.$refs.form.setFormVal('money', data.totalMoney)
        }
      },

      /**
       * 表单值发生改变
       * @param {Object} data
       */
      handleValueChange(data) {
        console.log('value change: ', 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 = ['businessId', 'contactsId']
          arr.forEach(key => {
            findIndex = this.fieldArr.findIndex(o => o.fieldName === key)
            if (findIndex !== -1 && !bridgeDefault.hasOwnProperty(key)) {
              const fieldItem = deepCopy(this.fieldArr[findIndex])
              if (data.value.length > 0) {
                fieldItem.sys_config.otherParams = {
                  customerId: data.value[0].customerId,
                  pageType: 0
                }
                fieldItem.disabled = false
              } else {
                fieldItem.sys_config.otherParams = {}
                fieldItem.disabled = true
                fieldItem.value = []
              }
              this.$refs.form.updateFields(findIndex, fieldItem)
            }
          })
        } else if (data.field.formType === 'business') {
          // 如果修改的是商机
          if (data.value.length === 0) {
            this.$set(this.productField, 'value', {})
          } else {
            this.getProductList(data.value[0].businessId || data.value[0].id)
            const money = data.value[0].money
            if (this.$isEmpty(money)) return
            findIndex = this.fieldArr.findIndex(o => o.fieldName === 'money')
            if (findIndex !== -1) {
              const fieldItem = deepCopy(this.fieldArr[findIndex])
              fieldItem.value = money
              this.$refs.form.updateFields(findIndex, fieldItem)
            }
          }
        }
      },

      /**
       * 保存
       */
      handleSave() {
        this.loading = true
        this.$refs.form.getForm().then(async form => {
          let startTime = form.entity.startTime
          let endTime = form.entity.endTime
          if (startTime && endTime && startTime > endTime) {
            this.$toast('合同的开始时间不能大于结束时间')
            this.loading = false
            return
          }

          if (this.productField) {
            const productData = this.$refs.product.getForm()
            form.product = productData.product
            form.entity = {
              ...form.entity,
              discountRate: productData.discountRate,
              totalPrice: productData.totalPrice
            }
          }

          this.baseGetAuditSaveData(form)
          this.baseFormatSaveData(form)
          console.log('save: ', form)
          // this.loading = false
          // return

          if (!form.examineFlowData) {
            this.$toast('请完善审批信息')
            this.loading = false
            return
          }
          const request = this.id ? UpdateContract : AddContract
          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>
