<template>
  <a-modal
    v-model="opened"
    :title="title"
    centered
    :maskClosable="false"
    width="60%"
    :footer="null"
    @cancel="cancel"
  >
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol">
        <a-row>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="收款日期" prop="receiptDate">
              <a-date-picker
                id="fcDetailModal-receiptDate"
                inputReadOnly
                v-if="!isEditDetail"
                style="width:100%"
                format="YYYY-MM-DD"
                v-model="form.receiptDate"
                placeholder="请选择收款日期" />
              <span v-else>{{ form.receiptDate }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="付款方类型" prop="payerType">
              {{ form.payerTypeDictValue }}
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 经销售 -->
        <a-row v-if="form.payerType=='DEALER'" >
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="付款方" prop="dealerSn">
              <!-- <dealerSubareaScopeList ref="settleClientName" @change="custChange" :disabled="true" /> -->
              {{ form.payerName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="付款账户类型" prop="payerAccountType">
              <v-select
                id="fcDetailModal-payerAccountType"
                v-model="form.payerAccountType"
                showType="radio"
                code="PAYER_ACCOUNT_TYPE"
                placeholder="请选择付款账户类型"
                @change="accountTypeChange"
              ></v-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-if="form.payerType=='DEALER'" >
          <!-- 公户 -->
          <a-col :span="12" v-if="form.payerAccountType=='PUBLIC'">
            <a-form-model-item style="margin-bottom:5px;" label="营业执照名称">
              <a-input id="fcDetailModal-payerAccountInfo" :maxLength="30" placeholder="请输入营业执照名称" v-model="form.payerAccountInfo"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- 私户 -->
          <a-col :span="12" v-if="form.payerAccountType=='PRIVATE'">
            <a-form-model-item style="margin-bottom:5px;" label="付款账户">
              <a-input id="fcDetailModal-payerAccountInfo1" :maxLength="30" placeholder="付款账户" v-model="form.payerAccountInfo"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="财务编码">
              {{ form.dealerCode||'--' }}
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 部门或其它 -->
        <a-row v-if="form.payerType=='DEPT'" >
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="付款方" prop="payerName">
              <!-- <a-input :maxLength="30" placeholder="请输入付款方名称" disabled v-model="form.payerName"></a-input> -->
              {{ form.payerName }}
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="付款账户">
              <a-input id="fcDetailModal-payerAccountInfo2" :maxLength="30" placeholder="付款账户" v-model="form.payerAccountInfo"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider />
        <a-row>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="订单金额">
              <a-input-number
                style="width:100%"
                id="fcDetailModal-orderAmount"
                v-if="!isEditDetail"
                :min="0"
                :max="99999999"
                :precision="2"
                placeholder="请输入订单金额"
                v-model="form.orderAmount"></a-input-number>
              <span v-else>{{ Number(form.orderAmount).toFixed(2) }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="收款金额">
              <a-input-number
                style="width:100%"
                id="fcDetailModal-receiptAmount"
                v-if="!isEditDetail"
                :min="0"
                :max="99999999"
                :precision="2"
                placeholder="请输入收款金额"
                v-model="form.receiptAmount"></a-input-number>
              <span v-else>{{ Number(form.receiptAmount).toFixed(2) }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="使用授信">
              <a-checkbox id="fcDetailModal-useCreditFlag" v-if="!isEditDetail" v-model="form.useCreditFlag" @change="form.detailItemUseList=[]">是</a-checkbox>
              <span v-else>{{ form.useCreditFlag?'是':'否' }}</span>
              <span v-if="form.useCreditFlag">合计: {{ useTotalAmount||'--' }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="授信还款">
              <a-checkbox id="fcDetailModal-payCreditFlag" v-if="!isEditDetail" v-model="form.payCreditFlag" @change="form.detailItemPayList=[]">是</a-checkbox>
              <span v-else>{{ form.payCreditFlag?'是':'否' }}</span>
              <span v-if="form.payCreditFlag">合计:  {{ payTotalAmount||'--' }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="余款抵扣">
              <a-input-number
                id="fcDetailModal-balanceAmount"
                v-if="!isEditDetail"
                style="width:100%"
                :min="0"
                :max="99999999"
                :precision="2"
                placeholder="请输入余款抵扣"
                v-model="form.balanceAmount"></a-input-number>
              <span v-else>
                {{ Number(form.balanceAmount).toFixed(2) }}
              </span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="跨月打款">
              <a-input-number
                style="width:100%"
                id="fcDetailModal-nextMonthAmount"
                v-if="!isEditDetail"
                :min="0"
                :max="99999999"
                :precision="2"
                placeholder="请输入跨月打款金额"
                v-model="form.nextMonthAmount"></a-input-number>
              <span v-else>{{ Number(form.nextMonthAmount).toFixed(2) }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="特殊申请发货">
              <a-input-number
                style="width:100%"
                v-if="!isEditDetail"
                id="fcDetailModal-specialSendAmount"
                :min="0"
                :max="99999999"
                :precision="2"
                placeholder="请输入特殊申请发货金额"
                v-model="form.specialSendAmount"></a-input-number>
              <span v-else>{{ Number(form.specialSendAmount).toFixed(2) }}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="足额打款">
              <v-select
                showType="radio"
                id="fcDetailModal-fullPaymentFlag"
                v-if="!isEditDetail"
                v-model="form.fullPaymentFlag"
                code="FLAG"
                placeholder="请选择是否足额打款"
                allowClear></v-select>
              <span v-else>
                {{ form.fullPaymentFlag == '1' ? '是' : '否' }}
              </span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="户名" prop="bankAccount">
              <SelectInput
                v-model="form.bankAccount"
                ref="bankList"
                id="fcDetailModal-bankAccount"
                code="FINANCE_BOOK_BANK_INFO"
                placeholder="请选择户名"
                @change="handleChange"
                @loaded="getBankNameList"
                isTree
                :isInput="false"
                allowClear
              ></SelectInput>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="汇入银行" prop="bankName">
              <a-select
                placeholder="请选择汇入银行"
                allowClear
                id="fcDetailModal-bankName"
                v-model="form.bankName"
                style="width: 100%">
                <a-select-option v-for="item in bankNameList" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item style="margin-bottom:5px;" label="说明" :labelCol="{span:3}" :wrapper-col="{ span: 20 }">
              <a-textarea
                :rows="2"
                v-if="!isEditDetail"
                id="fcDetailModal-explainInfo"
                :maxLength="500"
                placeholder="请输入说明（最多500个字符）"
                v-model="form.explainInfo"></a-textarea>
              <div v-else>
                {{ form.explainInfo||'--' }}
              </div>
            </a-form-model-item>
          </a-col>
          <!-- 使用授信列表 -->
          <a-col :span="22" :offset="1" v-if="form.useCreditFlag">
            <div style="padding:10px 0">使用授信项目:</div>
            <fcDetailSxItem title="使用授信" @updateItemAmount="updateUseAmount" :readOnly="isEditDetail" :list="form.detailItemUseList" ref="useCreditItem"></fcDetailSxItem>
          </a-col>
          <!-- 授信还款列表 -->
          <a-col :span="22" :offset="1" v-if="form.payCreditFlag">
            <div style="padding:10px 0">授信还款项目:</div>
            <fcDetailSxItem title="授信还款" @updateItemAmount="updatePayAmount" :readOnly="isEditDetail" :list="form.detailItemPayList" ref="payCreditItem"></fcDetailSxItem>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;margin-top: 50px;">
              <a-button @click="cancel" style="margin-right: 15px" id="fcDetailModal-btn-back">取消</a-button>
              <a-button type="primary" :loading="confirmLoading" @click="handleSubmit" id="fcDetailModal-btn-submit">保存</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { commonMixin } from '@/utils/mixin'
import { VSelect, SelectInput, Upload } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import fcDetailSxItem from './fcDetailSxItem.vue'
import { financeBookDetailSave, financeBookDetailQueryBySn, lastPayerAccountInfo } from '@/api/financeBook.js'
import { dealerDetailBySn } from '@/api/dealer'
export default {
  name: 'FcDetailModal',
  mixins: [commonMixin],
  components: { VSelect, SelectInput, Upload, dealerSubareaScopeList, fcDetailSxItem },
  props: {
    show: {
      type: [Boolean],
      default: false
    },
    bookSn: {
      type: String,
      default: ''
    },
    bookNo: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      opened: this.show,
      spinning: false,
      disabled: false,
      title: '新增收款明细',
      confirmLoading: false,
      isEditDetail: false,
      bookDetailSn: '', // 收款明细sn
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      form: {
        payerType: 'DEALER', // 付款方
        payerAccountType: 'PUBLIC', // 付款账户
        dealerSn: undefined, // 客户sn
        payerName: '', // 付款方名称
        payerAccountInfo: '', // 付款账户
        licenseName: '', // 营业执照
        receiptDate: moment(), // 收款日期
        dealerCode: '', // 财务编码
        orderAmount: '', // 订单金额
        receiptAmount: '', // 收款金额
        useCreditFlag: false, // 是否使用授信
        detailItemUseList: [], // 授信使用项目
        payCreditFlag: false, // 是否授信还款
        detailItemPayList: [], // 授信还款项目
        balanceAmount: '', // 余额
        nextMonthAmount: '', // 下月额度
        specialSendAmount: '', // 特批额度
        bankAccount: '东莞箭冠', // 汇入银行户名
        bankName: '东莞银行', // 汇入银行
        fullPaymentFlag: '1', // 足额打款
        explainInfo: '' // 说明
      },
      rules: {
        receiptDate: [ { required: true, message: '请选择收款日期', trigger: ['change', 'blur'] } ],
        payerType: [ { required: true, message: '请选择付款方类型', trigger: ['change', 'blur'] } ],
        dealerSn: [ { required: true, message: '请选择付款方', trigger: ['change', 'blur'] } ],
        payerName: [ { required: true, message: '请输入付款方名称', trigger: ['change', 'blur'] } ],
        payerAccountType: [ { required: true, message: '请选择付款账户类型', trigger: ['change', 'blur'] } ],
        bankAccount: [{ required: true, message: '请选择户名', trigger: ['change', 'blur'] }],
        bankName: [{ required: true, message: '请选择汇入银行', trigger: ['change', 'blur'] }]
      },
      useTotalAmount: '',
      payTotalAmount: '',
      bankNameList: ['东莞银行']
    }
  },
  methods: {
    accountTypeChange (v) {
      this.$refs.ruleForm.clearValidate()
      // 已选经销商
      if (this.form.dealerSn) {
        // 查询账户信息
        this.getLastPayerAccount()
      } else {
        this.form.licenseName = ''
        this.form.payerAccountInfo = ''
      }
      // 公户
      if (this.form.payerAccountType == 'PUBLIC') {
        this.form.bankAccount = '东莞箭冠'
        this.form.bankName = '东莞银行'
      } else {
        this.form.bankAccount = '张丽添'
        this.form.bankName = '农业银行'
      }
      this.getBankNameList()
    },
    // 户名改变
    handleChange (v, row) {
      if (v) {
        this.form.bankAccount = v
        this.bankNameList = row ? row.code.split(',') : []
        this.form.bankName = undefined
      }
    },
    getLastPayerAccount () {
      this.spinning = true
      this.confirmLoading = true
      lastPayerAccountInfo({
        payerAccountType: this.form.payerAccountType,
        dealerSn: this.form.dealerSn
      }).then(res => {
        this.spinning = false
        this.confirmLoading = false
        this.form.payerAccountInfo = res.data || ''
      })
    },
    // 查询经销商信息
    getDealerDetail (sn) {
      dealerDetailBySn({ sn: sn }).then(res => {
        const val = { key: sn }
        val.row = res.data
        this.custChange(val)
      })
    },
    // 客户
    custChange (v) {
      if (v && v.key) {
        this.form.dealerSn = v.key
        this.form.payerName = v.row ? v.row.dealerName : ''
        this.form.dealerCode = v.row ? v.row.kdMidCustomerFnumber : ''
        this.form.licenseName = v.row ? v.row.licenseName : ''
        // 查询账户信息
        this.getLastPayerAccount()
      } else {
        this.form.dealerSn = ''
        this.form.payerName = ''
        this.form.dealerCode = ''
        this.form.licenseName = ''
        this.form.payerAccountInfo = ''
      }
    },
    updateUseAmount (v) {
      this.useTotalAmount = v
    },
    updatePayAmount (v) {
      this.payTotalAmount = v
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.salesSaveFun()
        } else {
          return false
        }
      })
    },
    validItem (data) {
      return data.find(item => !item.itemName || !item.itemAmount)
    },
    // 新建或编辑销售单
    salesSaveFun () {
      const _this = this
      const form = JSON.parse(JSON.stringify(_this.form))
      form.receiptDate = moment(form.receiptDate).format('YYYY-MM-DD')
      form.payCreditFlag = form.payCreditFlag ? 1 : 0
      form.useCreditFlag = form.useCreditFlag ? 1 : 0
      form.bookSn = this.bookSn
      form.bookNo = this.bookNo
      delete form.dealerCode
      if (form.payerType == 'DEPT') {
        delete form.payerAccountType
      }
      console.log(form)
      if ((form.useCreditFlag && form.detailItemUseList.length == 0) || this.validItem(form.detailItemUseList)) {
        this.$message.info('使用授信项目不能为空')
        return
      }
      if ((form.payCreditFlag && form.detailItemPayList.length == 0) || this.validItem(form.detailItemPayList)) {
        this.$message.info('授信还款项目不能为空')
        return
      }
      _this.spinning = true
      financeBookDetailSave(form).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$emit('refashData')
          _this.cancel()
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 新增时设置默认值
    setDetail (data) {
      this.form = Object.assign(this.form, { payerTypeDictValue: data.payerTypeDictValue, payerType: data.payerType, dealerSn: data.dealerSn, payerName: data.payerName })
      this.$nextTick(() => {
        if (this.form.dealerSn) {
          this.getDealerDetail(this.form.dealerSn)
        } else {
          this.form.bankAccount = '张丽添'
          this.form.bankName = '农业银行'
        }
        this.getBankNameList()
      })
    },
    //  详情
    getDetail (bookDetailSn, detail, isEditDetail) {
      this.spinning = true
      this.confirmLoading = true
      this.title = '编辑收款明细'
      this.bookDetailSn = bookDetailSn
      this.isEditDetail = isEditDetail
      financeBookDetailQueryBySn({ bookDetailSn: this.bookDetailSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.handleChange(data.bankAccount)
          this.form = Object.assign(this.form, data)
          this.form.receiptDate = moment(this.form.receiptDate).format('YYYY-MM-DD')
          this.form.payCreditFlag = this.form.payCreditFlag == 1
          this.form.useCreditFlag = this.form.useCreditFlag == 1
          this.$nextTick(() => {
            this.getBankNameList()
          })
        }
        this.spinning = false
        this.confirmLoading = false
      })
    },
    getBankNameList () {
      const blist = this.$refs.bankList.list.find(item => item.dispName == this.form.bankAccount)
      this.bankNameList = blist && blist.code.split(',') || []
    },
    cancel () {
      this.opened = false
      this.$emit('cancel')
      this.pageInit()
    },
    pageInit () {
      this.$nextTick(() => {
        this.title = '新增收款明细'
      })
      this.bankNameList = []
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields()
      }
      this.form = {
        payerType: 'DEALER',
        payerAccountType: 'PUBLIC',
        dealerSn: undefined,
        payerName: '',
        payerAccountInfo: '',
        licenseName: '',
        receiptDate: moment(),
        dealerCode: '',
        orderAmount: '',
        receiptAmount: '',
        useCreditFlag: false,
        detailItemUseList: [],
        payCreditFlag: false,
        detailItemPayList: [],
        balanceAmount: '',
        nextMonthAmount: '',
        specialSendAmount: '',
        bankAccount: '东莞箭冠',
        bankName: '东莞银行',
        fullPaymentFlag: '1',
        explainInfo: ''
      }
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
    }
  }
}
</script>
