<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view
      :class="{'has-product': !!productField}"
      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" />

          <template v-if="routerQuery && routerQuery.type === 'invoice'">
            <view class="invoice-desc">
              发票信息
              <text class="control-btn" @click="handleToChooseInvoice">
                选择发票信息
              </text>
            </view>
            <wk-form
              ref="invoiceForm"
              :fields="invoiceFieldArr"
              @change="invoiceFormChange" />
          </template>

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

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

          <view class="empty-box" />
        </view>
      </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 { QueryField, CheckOnlyField } from 'API/base'
  import { PreviewFiledName } from 'API/examine'
  import { QueryBusinessSetting } from 'API/crm/flow'

  import {
    QueryFieldList as LeadsQueryFieldList,
    AddLeads,
    UpdateLeads,
  } from 'API/crm/leads'
  import {
    QueryFieldList as CustomerQueryFieldList,
    AddCustomer,
    UpdateCustomer
  } from 'API/crm/customer'
  import {
    QueryFieldList as ContactsQueryFieldList,
    AddContacts,
    UpdateContacts
  } from 'API/crm/concat'
  import {
    QueryFieldList as ReceivablesQueryFieldList,
    AddReceivables,
    UpdateReceivables
  } from 'API/crm/received'
  import {
    QueryFieldList as ProductQueryFieldList,
    AddProduct,
    UpdateProduct
  } from 'API/crm/product'
  import {
    QueryFieldList as BusinessQueryFieldList,
    AddBusiness,
    UpdateBusiness,
    QueryProduct as BusinessProduct
  } from 'API/crm/business'
  import {
    QueryFieldList as ContractQueryFieldList,
    AddContract,
    UpdateContract,
    GetList as GetContractList,
    QueryProduct as ContractProduct
  } from 'API/crm/contract'
  import {
    QueryFieldList as ReceivablesPlanQueryFieldList,
    AddReceivablesPlan,
    UpdateReceivablesPlan
  } from 'API/crm/receivedPlan'
  import {
    QueryFieldList as InvoiceQueryFieldList,
    AddInvoice,
    UpdateInvoice
  } from 'API/crm/invoice'

  import {
    QueryBusiness as QueryBusinessByCustomerId,
    QueryContacts as QueryContactsByCustomerId,
    QueryContract as QueryContractByCustomerId,
    QueryInvoiceInfo as QueryInvoiceInfoByCustomerId
  } from 'API/crm/customer'

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

  import formMixins from '@/mixins/formMixins.js'
  import { deepCopy } from '@/utils/lib.js'
  import { isArray, isObject } from '@/utils/types.js'
  import invoiceField from './invoiceField.js'
  import moment from 'moment'

  export default {
    name: 'AddOrUpdate',
    components: {
      ProductChooseAdd
    },
    mixins: [formMixins],
    data() {
      return {
        id: null,
        batchId: null,
        guid: null,

        showForm: true,
        routerQuery: {},
        fieldArr: [],
        invoiceFieldArr: invoiceField,

        productField: null,
        defaultProductList: {},
        businessStatusList: [],

        showAudit: false,
        auditUser: null,
        authInfo: {},
        auditConditionFields: [],

        selectedInvoiceInfo: [],

        loading: false,
        timer: null,

        typeMap: {
          leads: {
            addFn: AddLeads,
            updateFn: UpdateLeads,
            fieldFn: LeadsQueryFieldList,
            field: 'leadsId',
            label: 1,
            value: '线索'
          },
          customer: {
            addFn: AddCustomer,
            updateFn: UpdateCustomer,
            fieldFn: CustomerQueryFieldList,
            field: 'customerId',
            label: 2,
            value: '客户'
          },
          contacts: {
            addFn: AddContacts,
            updateFn: UpdateContacts,
            fieldFn: ContactsQueryFieldList,
            field: 'contactsId',
            label: 3,
            value: '联系人'
          },
          business: {
            addFn: AddBusiness,
            updateFn: UpdateBusiness,
            fieldFn: BusinessQueryFieldList,
            field: 'businessId',
            label: 5,
            value: '商机'
          },
          contract: {
            addFn: AddContract,
            updateFn: UpdateContract,
            fieldFn: ContractQueryFieldList,
            field: 'contractId',
            label: 6,
            value: '合同'
          },
          receivables: {
            addFn: AddReceivables,
            updateFn: UpdateReceivables,
            fieldFn: ReceivablesQueryFieldList,
            field: 'receivablesId',
            label: 7,
            value: '回款'
          },
          product: {
            addFn: AddProduct,
            updateFn: UpdateProduct,
            fieldFn: ProductQueryFieldList,
            field: 'productId',
            label: 4,
            value: '产品'
          },
          receivables_plan: {
            addFn: AddReceivablesPlan,
            updateFn: UpdateReceivablesPlan,
            fieldFn: ReceivablesPlanQueryFieldList,
            field: 'receivablesPlanId',
            label: 8,
            value: '回款计划'
          },
          invoice: {
            addFn: AddInvoice,
            updateFn: UpdateInvoice,
            fieldFn: InvoiceQueryFieldList,
            field: 'invoiceId',
            label: 18,
            value: '发票'
          }
        },
      }
    },
    computed: {
      navTitle() {
        const str = {
          leads: '线索',
          customer: '客户',
          contacts: '联系人',
          business: '商机',
          contract: '合同',
          receivables: '回款',
          receivables_plan: '回款计划',
          product: '产品',
          invoice: '发票'
        }[this.routerQuery.type]

        const actionStr = this.routerQuery.id ? '编辑' : '新建'
        return actionStr + str
      }
    },
    onLoad(options) {
      this.routerQuery = options || {}
      this.id = options.id
      this.batchId = options.batchId
      this.guid = this.$guid()

      if (options.type === 'business' && options.id) {
        QueryBusinessSetting().then(res => {
          this.businessStatusList = res
          this.getFieldList()
        }).catch()
      } else {
        this.getFieldList()
      }
    },
    onUnload() {
      getApp().globalData.formBridge = {}
    },
    methods: {
      getFieldList() {
        const request = this.typeMap[this.routerQuery.type].fieldFn
        if (!request) return
        const params = { type: 1 }
        if (this.routerQuery.id) params.id = this.routerQuery.id
        request(params).then(res => {
          let findIndex = res.findIndex(o => o.formType === 'product')
          if (findIndex !== -1) {
            this.productField = res.splice(findIndex, 1)[0]
          }

          res = this.formatFieldArr(res)
          res.forEach(field => {
            // 自动编号为非必填
            if (field.autoGeneNumber === 1) {
              field.isNull = 0
            }
            if (this.routerQuery.type === 'business' && this.id && field.value) {
              // 商机下 商机状态组
              if (field.formType === 'business_type') {
                field.value = this.businessStatusList.filter(o => o.flowId === field.value)
              } else {
                field.value = this.mixinsFormatFieldValue(field)
              }
            } else if (this.routerQuery.type === 'receivables' && this.id && field.value) {
              // 回款下 合同和回款计划
              field.value = this.mixinsFormatFieldValue(field)
              if (field.fieldName === 'customerId') {
                const findRes = res.find(o => o.fieldName === 'contractId')
                if (findRes) {
                  const fieldItem = deepCopy(this.fieldArr[findIndex])
                  if (field.value.length > 0) {
                    findRes.sys_config.otherParams = {
                      searchList: [
                        {
                          formType: 'text',
                          name: 'customer_id',
                          type: 1,
                          values: [field.value[0].customerId]
                        },
                        {
                          formType: 'checkStatus',
                          name: 'checkStatus',
                          type: 1,
                          values: [1, 10]
                        }
                      ]
                    }
                    findRes.disabled = false
                  } else {
                    findRes.sys_config.otherParams = {}
                    findRes.disabled = true
                    findRes.value = []
                  }
                }
              } else if (field.fieldName === 'receivablesPlanId') {
                const findRes = res.find(o => o.formType === 'contract')
                if (findRes) {
                  if (findRes.value.length > 0) {
                    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 = []
                  }
                }
              } else {
                field.value = this.mixinsFormatFieldValue(field)
              }
            } else if (this.routerQuery.type === 'product' && this.id && field.value) {
              // 产品下上下架状态
              if (field.fieldName === 'status') {
                field.value = field.setting.filter(o => o.value == field.value)
              } else {
                field.value = this.mixinsFormatFieldValue(field)
              }
            } else {
              field.value = this.mixinsFormatFieldValue(field)
            }

            // if (!this.$isEmpty(field.authLevel) && !field.disabled) {
            if (!this.$isEmpty(field.authLevel)) {
              // 判断字段权限，如果没有权限则直接禁止修改
              field.disabled = this.getDisabledStatusByAuth(field)
              if (field.disabled) {
                if (field.sys_config) {
                  field.sys_config.disabledMsg = ''
                }
              }
            }
          })
          this.fieldArr = res
          this.setForm()
          if ([
            'receivables',
            'contract',
            'invoice'
          ].includes(this.routerQuery.type)) {
            this.getAuditList()
          }
        }).catch(() => {})
      },

      /**
       * 根据权限判断字段是否可编辑
       * @param {Object} field
       */
      getDisabledStatusByAuth(field) {
        const crmType = this.routerQuery.type
        if (crmType === 'business' && ['business_type', 'business_status'].includes(field.formType)) return false
        if (crmType === 'contract' && ['business', 'contacts', 'customer'].includes(field.formType)) return false
        if (crmType === 'receivables' && ['contract', 'customer'].includes(field.formType)) return false
        if (crmType === 'visit' && ['business', 'contacts', 'customer'].includes(field.formType)) return false
        if (crmType === 'invoice' && ['contractId', 'contractMoney'].includes(field.fieldName)) return true

        // 1 不能查看不能编辑  2 可查看  3 可查看可编辑
        return field.authLevel !== 3 // false 可编辑
      },

      /**
       * 注入字段配置信息
       * @param {Object} res
       */
      formatFieldArr(res) {
        const crmType = this.routerQuery.type
        if (crmType === 'business') {
          // 如果有商机阶段则删掉该字段，商机阶段只能在详情中进行修改
          const findIndex = res.findIndex(o => o.formType === 'business_status')
          if (findIndex !== -1) {
            res.splice(findIndex, 1)
          }
        } else if (crmType === 'contract') {
          let findRes = res.find(o => o.fieldName === 'businessId')
          if (findRes) {
            // 客户下商机
            findRes.disabled = true
            findRes.sys_config = {
              request: QueryBusinessByCustomerId,
              otherParams: {},
              disabledMsg: '请先选择客户'
            }
          }
          findRes = res.find(o => o.fieldName === 'contactsId')
          if (findRes) {
            // 客户下联系人
            findRes.disabled = true
            findRes.sys_config = {
              request: QueryContactsByCustomerId,
              otherParams: {},
              disabledMsg: '请先选择客户'
            }
          }
          findRes = res.find(o => o.autoGeneNumber === 1)
          if (findRes) {
            findRes.isNull = 0
          }
        } else if (crmType === 'receivables') {
          let findRes = res.find(o => o.fieldName === 'contractId')
          if (findRes) {
            // 客户下合同
            findRes.disabled = true
            findRes.sys_config = {
              request: GetContractList,
              otherParams: {},
              disabledMsg: '请先选择客户',
              optionsConfig: {
                labelField: 'num',
                valueField: 'contractId'
              }
            }
          }
          findRes = res.find(o => o.fieldName === 'planId')
          if (findRes) {
            // 合同下回款计划
            findRes.disabled = true
            findRes.sys_config = {
              otherParams: {},
              disabledMsg: '请先选择合同'
            }
          }
        } else if (crmType === 'product') {
          let findRes = res.find(o => o.fieldName === 'status')
          if (findRes) {
            // 产品上下架
            findRes.sys_config = {
              optionsConfig: {
                labelField: 'name',
                valueField: 'value'
              }
            }
          }
        } else if (crmType === 'invoice') {
          let findRes = res.find(o => o.fieldName === 'contractId')
          if (findRes) {
            //  客户下合同
            findRes.disabled = true
            findRes.sys_config = {
              request: GetContractList,
              otherParams: {},
              disabledMsg: '请先选择客户',
              optionsConfig: {
                labelField: 'num',
                valueField: 'contractId'
              }
            }
          }
          findRes = res.find(o => o.fieldName === 'invoiceType')
          if (findRes) {
            findRes.setting = [
              { label: '增值税专用发票', value: 1 },
              { label: '增值税普通发票', value: 2 },
              { label: '国税通用机打发票', value: 3 },
              { label: '地税通用机打发票', value: 4 },
              { label: '收据', value: 5 }
            ]
          }
        }
        return res
      },

      setForm() {
        const bridge = getApp().globalData.formBridge
        // console.log('setForm bridge: ', bridge)
        if (!bridge.default) return
        this.$nextTick(() => {
          this.$refs.form.setForm(bridge.default || {})
          Object.keys(bridge.default).forEach(key => {
            this.$refs.form.setDisabled(key, true)
            this.$refs.form.setConfig(key, { disabledMsg: '' })
          })
        })

        // #ifdef APP-PLUS
        // App 偶发会出现字段渲染不上的问题，在此强制刷新页面
        this.$nextTick(() => {
          if (!this.$isEmpty(bridge.default)) {
            this.$refs.form.updateView()
          }
        })
        // #endif
      },

      /**
       * 获取审批流程条件
       */
      getAuditList() {
        const label = {
          contract: 1,
          receivables: 2,
          invoice: 3
        }[this.routerQuery.type] || ''

        PreviewFiledName({
          label
        }).then(res => {
          this.showAudit = res !== null
          if (!this.showAudit) return
          const mapIns = new Map()
          this.auditConditionFields = res.filter(o =>	!mapIns.has(o.fieldId) && mapIns.set(o.fieldId, 1))
          console.log('PreviewFiledName: ', this.auditConditionFields)
          this.$nextTick(() => {
            const dataMap = {}
            const bridge = getApp().globalData.formBridge || {}
            this.auditConditionFields.forEach(o => {
              const findRes = this.fieldArr.find(f => f.fieldName === o.fieldName)
              if (findRes) {
                let value = null
                if (bridge.default && bridge.default.hasOwnProperty(o.fieldName)) {
                  value = bridge.default[o.fieldName]
                } else {
                  value = findRes.value
                }

                switch (findRes.formType) {
                case 'select':
                  if (this.$isEmpty(value)) value = ''
                  if (isArray(value)) {
                    value = value[0].value
                  }
                  break
                case 'checkbox':
                  if (this.$isEmpty(value)) value = ''
                  if (isArray(value)) {
                    value = value.map(o => o.value).join(',')
                  }
                  break
                default:
                  value = this.$isEmpty(value) ? '' : value
                }
                o._val = value
                dataMap[o.fieldName] = value
              }
            })

            this.$refs.wkAuditAdd.getAuditInfo({
              label,
              dataMap
            })
          })
        }).catch()
      },

      handleAddProduct() {
        this.$nextTick(() => {
          if (this.$refs.product) {
            this.$refs.product.handleChoose()
          }
        })
      },

      getProductList(type, id) {
        if (!id) return
        if (type === 'business') {
          // 获取商机下产品
          BusinessProduct({businessId: id, pageType: 0}).then(response => {
            response.product = response.list
            delete response.list
            this.$set(this.productField, 'value', response)
          }).catch()
        } else if (type === 'contract') {
          // 获取合同下产品
          ContractProduct({contractId: id, pageType: 0}).then(response => {
            response.product = response.list
            delete response.list
            this.$set(this.productField, 'value', response)
          }).catch()
        }
      },

      handleValueChange(data) {
        console.log('value change: ', data)
        this.changeAuditFlow(data.field, data.value)
        let findIndex = -1
        const crmType = this.routerQuery.type
        const bridge = getApp().globalData.formBridge
        const bridgeDefault = bridge.default || {}

        if (crmType === 'contract') {
          // 合同
          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('business', 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)
              }
            }
          }
        } else if (crmType === 'receivables') {
          // 回款
          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 = []
              }
              this.$refs.form.updateFields(findIndex, fieldItem)
            }
          } else if (data.field.formType === 'contract') {
            findIndex = this.fieldArr.findIndex(o => o.fieldName === 'planId')
            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 === 'planId') {
            if (data.value.length > 0) {
              this.$nextTick(function() {
                this.$refs.form.setForm({
                  returnTime: moment(data.value[0].returnDate).format('YYYY-MM-DD'),
                  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: []
                })
              })
            }
          }
        } else if (crmType === 'invoice') {
          //  发票
          if (data.field.formType === 'contract') {
            const arr = ['contractMoney', 'invoiceMoney']
            arr.forEach(fieldName => {
              findIndex = this.fieldArr.findIndex(o => o.fieldName === fieldName)
              if (findIndex !== -1) {
                const fieldItem = deepCopy(this.fieldArr[findIndex])
                if (data.value.length > 0) {
                  fieldItem.value = data.value[0].money || 0
                } else {
                  fieldItem.value = undefined
                }
                this.$refs.form.updateFields(findIndex, fieldItem)
              }
            })
          } else 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 = {
                  searhList: [
                    {
                      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 = []
              }
              this.$refs.form.updateFields(findIndex, fieldItem)
            }
          }
        }
      },

      /**
       * 根据审批条件变更审批流
       */
      changeAuditFlow(field, value) {
        if (!this.showAudit) return
        if (![
          'contract',
          'receivables',
          'invoice'
        ].includes(this.routerQuery.type)) return
        const findRes = this.auditConditionFields.find(o => o.fieldName === field.fieldName)
        if (!findRes) return
        if (this.timer) {
          clearTimeout(this.timer)
          this.timer = null
        }
        this.timer = setTimeout(() => {
          // number floatnumber select checkbox
          switch (field.formType) {
          case 'select':
            if (this.$isEmpty(value)) value = ''
            if (isArray(value)) {
              value = value[0].value
            }
            break
          case 'checkbox':
            if (this.$isEmpty(value)) value = ''
            if (isArray(value)) {
              value = value.map(o => o.value).join(',')
            }
            break
          default:
            value = this.$isEmpty(value) ? '' : value
          }
          findRes._val = value
          const dataMap = {}
          this.auditConditionFields.forEach(o => {
            if (o.hasOwnProperty('_val')) {
              dataMap[o.fieldName] = this.$isEmpty(o._val) ? '' : o._val
            } else {
              dataMap[o.fieldName] = ''
            }
          })
          this.$nextTick(() => {
            const label = {
              contract: 1,
              receivables: 2,
              invoice: 3
            }[this.routerQuery.type] || ''

            this.$refs.wkAuditAdd.getAuditInfo({
              label,
              dataMap
            })
            clearTimeout(this.timer)
            this.timer = null
          })
        }, 500)
      },

      handleChangeProduct(data) {
        console.log('change product: ', data)
        if (
          this.$refs.form &&
          ['business', 'contract'].includes(this.routerQuery.type)
        ) {
          this.$refs.form.setFormVal('money', data.totalMoney)
        }
      },

      invoiceFormChange(data) {
        // console.log('invoiceFormChange: ', data)
        if (data.field.fieldName === 'titleType') {
          const val = this.$refs.invoiceForm.getValueByFieldName('titleType')
          const arr = [
            'taxNumber',
            'depositBank',
            'depositAccount',
            'depositAddress',
          ]
          arr.forEach(key => {
            this.$refs.invoiceForm.updateVisibleStatus(key, val == 1)
          })
        }
      },

      /**
       * 去选择发票信息
       */
      handleToChooseInvoice() {
        console.log('to choose invoice')
        const customerId = this.$refs.form.getValueByFieldName('customerId')
        if (!customerId) {
          this.$toast('请先选择客户')
          return
        }
        const bridge = getApp().globalData.selectedValBridge
        bridge.invoice = {
          guid: this.guid,
          maxlength: 1,
          title: '选择关联发票抬头',
          config: {
            labelField: 'invoiceTitle',
            valueField: 'infoId',
            showCreate: false
          },
          defaultVal: this.selectedInvoiceInfo,
          params: { customerId },
          request: QueryInvoiceInfoByCustomerId
        }
        uni.$on('selected-relevance', this.selectedInvoice)
        this.$Router.navigateTo({
          url: '/pages_common/selectList/relevance',
          query: {
            type: 'invoice'
          }
        })
      },

      /**
       * 确认选择的发票
       */
      selectedInvoice(data) {
        if (data.guid === this.guid) {
          if (data.data.length > 0) {
            this.selectedInvoiceInfo = data.data
            const valData = deepCopy(data.data[0])

            this.invoiceFieldArr.forEach(field => {
              let value = valData[field.fieldName] || ''
              if (field.fieldName === 'titleType') {
                value = field.setting.filter(o => o.value === valData.titleType)
              }
              this.$refs.invoiceForm.setFormVal(field.fieldName, value)
            })
          }
        }
        uni.$off('selected-relevance')
      },

      handleSave() {
        const apiObj = this.typeMap[this.routerQuery.type] || null
        if (!apiObj || this.loading) return
        this.loading = true

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

          // 审批信息
          if (this.showAudit) {
            const data = this.$refs.wkAuditAdd.getSaveData()
            if (data === null) {
              this.loading = false
              return
            }
            const dataMap = {}
            this.auditConditionFields.forEach(o => {
              if (o.hasOwnProperty('_val')) {
                dataMap[o.fieldName] = this.$isEmpty(o._val) ? '' : o._val
              }
            })
            const label = {
              contract: 1,
              receivables: 2,
              invoice: 3
            }[this.routerQuery.type] || ''

            form.examineFlowData = {
              ...data,
              label,
              dataMap
            }
          }

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

          if (this.id && this.batchId) {
            form.entity[apiObj.field] = Number(this.id) || this.id
            form.entity.batchId = this.batchId
          }

          if (this.id && this.type === 'customer') {
            if (Number(this.id) === Number(form.entity.superiorCustomerId)) {
              this.$toast('上级客户不能为当前客户')
              this.loading = false
              return
            }
          }

          if (this.id && this.type === 'pContactsId') {
            if (Number(this.id) === Number(form.entity.pContactsId)) {
              this.$toast('直属上级不能为当前联系人')
              this.loading = false
              return
            }
          }

          if (!form.hasOwnProperty('field')) {
            form.field = []
          }

          const bridge = getApp().globalData.formBridge || {}
          if (bridge.assignForm) {
            form = Object.assign(form, bridge.assignForm)
          }

          const arr = form.field
            .filter(o => o.formType !== 'desc_text')
            .map(o => {
              return {
                fieldName: o.fieldName,
                name: o.name,
                type: o.type,
                fieldId: o.fieldId,
                value: o.value,
                fieldType: o.fieldType
              }
            })
          form.field = arr

          if (this.routerQuery.type === 'invoice') {
            const invoiceForm = await this.$refs.invoiceForm.getForm()
            console.log('invoiceForm: ', invoiceForm)
            if (invoiceForm.entity.titleType !== 1) {
              const arr = [
                'taxNumber',
                'depositBank',
                'depositAccount',
                'depositAddress',
              ]
              arr.forEach(key => {
                invoiceForm.entity[key] = ''
              })
            }

            Object.assign(form.entity, invoiceForm.entity || {})
          }

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

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

<style scoped lang="scss">
.main-container {
  /* #ifndef MP-WEIXIN */
  &.has-product {
    padding-bottom: $tabbar-height;
  }
  /* #endif */

  .container {
    flex: 1;
    width: 100%;
    background-color: white;
    margin-top: 20rpx;
    overflow: hidden;
    .scroll-content {
      width: 100%;
      height: 100%;
      overflow: auto;

      .empty-box {
        width: 100%;
        height: 30rpx;
        background-color: white;
      }
    }
  }

  .invoice-desc {
    width: 100%;
    font-size: $wk-font-sm;
    background-color: #F3F5FA;
    padding: 20rpx 24rpx;

    .control-btn {
      color: $theme-color;
      float: right;
    }
  }

  .footer-btn-group {
    .button {
      flex: 1;
    }
    .choose-product-btn {
      color: $theme-color;
      border: 1rpx solid $theme-color;
      background-color: white;
      margin-right: 30rpx;
    }
  }
}
</style>
