<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 inputReadOnly style="width:100%" format="YYYY-MM-DD" v-model="form.receiptDate" placeholder="请选择收款日期" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="客户名称" prop="dealerSn">
              <dealerSubareaScopeList ref="settleClientName" @change="custChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="财务编码">
              {{ form.dealerCode||'--' }}
              <!-- <a-input :maxLength="100" placeholder="请输入财务编码" v-model="form.dealerCode"></a-input> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="营业执照名称">
              {{ form.licenseName||'--' }}
              <!-- <a-input :maxLength="100" placeholder="请输入营业执照名称" v-model="form.licenseName"></a-input> -->
            </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%"
                :min="0"
                :max="999999"
                :precision="2"
                placeholder="请输入订单金额"
                v-model="form.orderAmount"></a-input-number>
            </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%"
                :min="0"
                :max="999999"
                :precision="2"
                placeholder="请输入收款金额"
                v-model="form.receiptAmount"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="使用授信">
              <a-checkbox v-model="form.useCreditFlag" @change="form.detailItemUseList=[]">是</a-checkbox>
              <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 v-model="form.payCreditFlag" @change="form.detailItemPayList=[]">是</a-checkbox>
              <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
                style="width:100%"
                :min="0"
                :max="999999"
                :precision="2"
                placeholder="请输入余款抵扣"
                v-model="form.balanceAmount"></a-input-number>
            </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%"
                :min="0"
                :max="999999"
                :precision="2"
                placeholder="请输入跨月打款金额"
                v-model="form.nextMonthAmount"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="户名">
              <a-select placeholder="请选择户名" v-model="form.bankAccount" style="width: 100%" @change="handleChange">
                <a-select-option v-for="item in bankList" :value="item.bankAccount">
                  {{ item.bankAccount }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item style="margin-bottom:5px;" label="汇入银行">
              <a-select placeholder="请选择汇入银行" 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="12">
            <a-form-model-item style="margin-bottom:5px;" label="足额打款">
              <v-select
                v-model="form.fullPaymentFlag"
                code="FLAG"
                placeholder="请选择是否足额打款"
                allowClear></v-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" :maxLength="500" placeholder="请输入备注（最多500个字符）" v-model="form.remarks"></a-textarea>
            </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" :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" :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 type="primary" :loading="confirmLoading" @click="handleSubmit" id="chooseCustom-btn-submit">保存</a-button>
              <a-button @click="cancel" style="margin-left: 15px" id="chooseCustom-btn-back">取消</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, Upload } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import fcDetailSxItem from './fcDetailSxItem.vue'
import { financeBookDetailSave, financeBookDetailQueryBySn } from '@/api/financeBook.js'
export default {
  name: 'FcDetailModal',
  mixins: [commonMixin],
  components: { VSelect, 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,
      bookDetailSn: '',
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      form: {
        dealerSn: undefined,
        dealerName: '',
        receiptDate: moment(),
        dealerCode: '',
        licenseName: '',
        orderAmount: '',
        receiptAmount: '',
        useCreditFlag: false,
        detailItemUseList: [],
        payCreditFlag: false,
        detailItemPayList: [],
        balanceAmount: '',
        nextMonthAmount: '',
        bankAccount: undefined,
        bankName: undefined,
        fullPaymentFlag: undefined,
        remarks: ''
      },
      rules: {
        receiptDate: [ { required: true, message: '请选择收款日期', trigger: ['change', 'blur'] } ],
        dealerSn: [ { required: true, message: '请选择客户', trigger: ['change', 'blur'] } ]
      },
      useTotalAmount: '',
      payTotalAmount: '',
      bankList: [
        {
          bankAccount: '张丽友',
          bankName: ['建设银行', '微信收款']
        },
        {
          bankAccount: '张丽添',
          bankName: ['农业银行']
        },
        {
          bankAccount: '东莞箭冠',
          bankName: ['东莞银行']
        },
        {
          bankAccount: '江西箭冠',
          bankName: ['九江银行']
        }
      ],
      bankNameList: []
    }
  },
  methods: {
    handleChange (v) {
      console.log(v)
      const row = this.bankList.find(item => item.bankAccount == v)
      this.bankNameList = row.bankName
      this.form.bankName = undefined
    },
    // 客户
    custChange (v) {
      this.form.dealerSn = v.key
      this.form.dealerName = v.name
      this.form.licenseName = v.row ? v.row.licenseName : ''
      this.form.dealerCode = v.row ? v.row.kdMidCustomerFnumber : ''
    },
    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.dealerName
      delete form.licenseName
      delete form.dealerCode
      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
        }
      })
    },
    //  详情
    getDetail (bookDetailSn) {
      this.spinning = true
      this.confirmLoading = true
      this.title = '编辑收款明细'
      this.bookDetailSn = bookDetailSn
      financeBookDetailQueryBySn({ bookDetailSn: this.bookDetailSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          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
          // 回显客户
          if (this.form.dealerSn) {
            this.$refs.settleClientName.getDetail(this.form.dealerSn)
          }
        }
        this.spinning = false
        this.confirmLoading = false
      })
    },
    cancel () {
      this.opened = false
      this.$emit('cancel')
      this.pageInit()
    },
    pageInit () {
      this.$nextTick(() => {
        this.title = '新增收款明细'
        this.$refs.ruleForm.resetFields()
        this.$refs.settleClientName.resetForm()
        this.bankNameList = []
        this.form = {
          dealerSn: undefined,
          dealerName: '',
          receiptDate: moment(),
          dealerCode: '',
          licenseName: '',
          orderAmount: '',
          receiptAmount: '',
          useCreditFlag: false,
          detailItemUseList: [],
          payCreditFlag: false,
          detailItemPayList: [],
          balanceAmount: '',
          nextMonthAmount: '',
          bankAccount: undefined,
          bankName: undefined,
          fullPaymentFlag: undefined,
          remarks: ''
        }
      })
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
      if (!newValue) {
        this.pageInit()
      }
    }
  }
}
</script>
