<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="invoice-desc">
            发票信息
            <text class="control-btn" @click="handleToChooseInvoice">
              选择发票信息
            </text>
          </view>
          
          <wk-form
            ref="invoiceForm"
            :fields="invoiceFieldArr"
            @change="invoiceFormChange" />
            
          <wk-audit-add
            v-if="showAudit"
            ref="wkAuditAdd" />
            
          <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,
    AddInvoice,
    UpdateInvoice
  } from 'API/crm/invoice'
  import {
    GetList as GetContractList
  } from 'API/crm/contract'
  import {
    QueryInvoiceInfo as QueryInvoiceInfoByCustomerId
  } from 'API/crm/customer'
  import formMixins from '@/mixins/formMixins.js'
  import { deepCopy } from '@/utils/lib.js'
  import invoiceField from './invoiceField.js'
  import CreateMixins from '../mixins/create.js'
  
  export default {
    name: 'CreateInvoice',
    mixins: [CreateMixins, formMixins],
    data() {
      return {
        moduleType: 'invoice',
        
        invoiceFieldArr: invoiceField,
      }
    },
    onLoad() {
      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 === 'invoiceType') {
                field.setting = [
                  { label: '增值税专用发票', value: 1 },
                  { label: '增值税普通发票', value: 2 },
                  { label: '国税通用机打发票', value: 3 },
                  { label: '地税通用机打发票', value: 4 },
                  { label: '收据', value: 5 }
                ]
              }

              if (field.fieldName === 'invoiceType') {
                console.log(field)
                field.setting.forEach((item) => {
                  if (item.value == field.value) {
                    field.value = [item]
                  }
                })
                console.log(field)
              } else {
                field.value = this.mixinsFormatFieldValue(field)
              }
            })
            
            this.fieldArr = res
            this.setForm()
            this.getAuditList()
          })
          .catch(() => {
          })
      },
      
      /**
       * 表单值发生改变
       * @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 === '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 = {
                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)
          }
        }
      },
      
      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() {
        this.loading = true
        this.$refs.form.getForm().then(async form => {
          this.baseGetAuditSaveData(form)
          this.baseFormatSaveData(form)
          
          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

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