<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" />
            
          <wk-audit-add
            v-if="showAudit"
            ref="wkAuditAdd" />
            
          <view class="empty-box" />
        </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,
    AddReceivables,
    UpdateReceivables
  } from 'API/crm/received'
  import {
    GetList as GetContractList,
    QueryProduct as ContractProduct
  } from 'API/crm/contract'
  
  import CreateMixins from '../mixins/create.js'
  import { deepCopy } from '@/utils/lib.js'
  
  export default {
    name: 'CreateReceivables',
    mixins: [CreateMixins],
    data() {
      return {
        moduleType: 'receivables',
        crmType: ''
      }
    },
    onLoad(options) {
      this.crmType = options.crmType
      this.getFieldList()
    },
    methods: {
      getFieldList() {
        const params = { type: 1 }
        if (this.id) params.id = this.id
        QueryFieldList(params)
          .then(res => {
            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 = ''
                  }
                }
              }

              // 客户下合同
              if (field.fieldName === 'contractId') {
                field.disabled = true
                field.sys_config = {
                  request: GetContractList,
                  otherParams: {},
                  disabledMsg: '请先选择客户',
                  optionsConfig: {
                    labelField: 'num',
                    valueField: 'contractId'
                  }
                }
              } else if (field.fieldName === 'receivablesPlanId') {
                field.disabled = true
                field.sys_config = {
                  otherParams: {},
                  disabledMsg: '请先选择合同'
                }
              }
              
              field.value = this.mixinsFormatFieldValue(field)
            })
            
            // 合同字段
            let findIndex = -1
            let fieldItem = null
            const customerField = res.find(o => o.formType === 'customer')
            if (customerField) {
              findIndex = res.findIndex(o => o.fieldName === 'contractId')
              if (findIndex !== -1) {
                fieldItem = deepCopy(res[findIndex])
                if (customerField.value.length > 0) {
                  fieldItem.sys_config.otherParams = {
                    searchList: [
                      {
                        formType: 'text',
                        name: 'customer_id',
                        type: 1,
                        values: [customerField.value[0].customerId]
                      },
                      {
                        formType: 'checkStatus',
                        name: 'checkStatus',
                        type: 1,
                        values: [1, 10]
                      }
                    ]
                  }
                  fieldItem.disabled = false
                } else {
                  fieldItem.sys_config.otherParams = {}
                  fieldItem.disabled = true
                  fieldItem.value = []
                }
                res[findIndex] = fieldItem
              }
            }

            // 回款计划字段
            findIndex = res.findIndex(o => o.fieldName === 'receivablesPlanId')
            if (findIndex !== -1) {
              const findRes = res.find(o => o.fieldName === 'contractId')
              if (findRes) {
                const field = res[findIndex]
                if (findRes.value.length) {
                  field.sys_config.otherParams = {
                    contractId: findRes.value[0].contractId,
                    receivablesId: this.id
                  }
                  field.disabled = false
                } else {
                  field.sys_config.otherParams = {}
                  field.disabled = true
                  field.value = []
                }
              }
            }
            
            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') {
          findIndex = this.fieldArr.findIndex(o => o.fieldName === 'contractId')
          if (findIndex !== -1) {
            const fieldItem = deepCopy(this.fieldArr[findIndex])
            if (data.value.length > 0) {
              fieldItem.sys_config.otherParams = {
                searchList: [
                  {
                    formType: 'text',
                    name: 'customer_id',
                    type: 1,
                    values: [data.value[0].customerId]
                  },
                  {
                    formType: 'checkStatus',
                    name: 'checkStatus',
                    type: 1,
                    values: [1, 10]
                  }
                ]
              }
              fieldItem.disabled = false
            } else {
              fieldItem.sys_config.otherParams = {}
              fieldItem.disabled = true
              fieldItem.value = []
            }
            if (!this.crmType || this.crmType === 'customer') {
              this.$refs.form.updateFields(findIndex, fieldItem)
            }
            // this.$nextTick(() => {
            //   this.handleValueChange({
            //     field: fieldItem,
            //     index: findIndex,
            //     value: fieldItem.value || []
            //   })
            // })
          }
        } else if (data.field.formType === 'contract') {
          findIndex = this.fieldArr.findIndex(o => o.fieldName === 'receivablesPlanId')
          if (findIndex !== -1) {
            const fieldItem = deepCopy(this.fieldArr[findIndex])
            if (data.value.length > 0) {
              const otherParams = {
                contractId: data.value[0].contractId
              }
              if (this.id) {
                otherParams.receivablesId = this.id
              }
              fieldItem.sys_config.otherParams = otherParams
              fieldItem.disabled = false
            } else {
              fieldItem.sys_config.otherParams = {}
              fieldItem.disabled = true
              fieldItem.value = []
            }
            this.$refs.form.updateFields(findIndex, fieldItem)
          }
        } else if (data.field.fieldName === 'receivablesPlanId') {
          if (data.value.length > 0) {
            this.$nextTick(function() {
              this.$refs.form.setForm({
                returnTime: data.value[0].returnDate,
                money: data.value[0].money,
                returnType: [{
                  label: data.value[0].returnType,
                  value: data.value[0].returnType
                }]
              })
            })
          } else {
            this.$nextTick(function() {
              this.$refs.form.setForm({
                returnTime: '',
                money: '',
                returnType: []
              })
            })
          }
        }
      },
      
      /**
       * 保存
       */
      handleSave() {
        this.loading = true
        this.$refs.form.getForm().then(async form => {
          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 ? UpdateReceivables : AddReceivables
          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>
