<template>
  <a-modal
    v-model="opened"
    :title="title"
    centered
    :maskClosable="false"
    :width="800"
    :footer="null"
    @cancel="cancel"
  >
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="chooseCustom-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol">
        <a-form-model-item label="申请人" prop="applyPersonSn">
          <employee style="width: 100%;" @change="employeeChange" ref="applyPerson" v-model="form.applyPersonSn"></employee>
        </a-form-model-item>
        <a-form-model-item label="收款事由" prop="bookReason">
          <a-input :maxLength="100" placeholder="请输入收款事由（最多100个字符）" v-model="form.bookReason"></a-input>
        </a-form-model-item>
        <a-form-model-item label="付款方类型" prop="payerType">
          <v-select
            v-model="form.payerType"
            showType="radio"
            code="PAYER_TYPE"
            :disabled="!!bookSn"
            @change="payerTypeChange"
            placeholder="请选择付款方类型"
          ></v-select>
        </a-form-model-item>
        <a-form-model-item v-if="form.payerType=='DEALER'" label="付款方" prop="dealerSn">
          <dealerSubareaScopeList :disabled="!!bookSn" ref="settleClientName" @change="custChange" />
        </a-form-model-item>
        <a-form-model-item v-if="form.payerType=='DEPT'" label="付款方" prop="payerName">
          <a-input :maxLength="30" placeholder="请输入付款方名称" v-model="form.payerName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea :rows="4" :maxLength="500" placeholder="请输入备注（最多500个字符）" v-model="form.remarks"></a-textarea>
        </a-form-model-item>
        <a-form-model-item label="附件" help="（支持图片、word、excel、PDF等格式，最多10个附件）">
          <Upload
            style="height: 100%;"
            v-model="form.attachmentList"
            ref="attachList"
            :fileSize="10"
            :maxNums="10"
            fileType="*"
            uploadType="attach"
            :action="attachAction"
            @change="changeAttach"
            upText="上传附件"></Upload>
        </a-form-model-item>
        <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-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect, Upload } from '@/components'
import employee from '../../expenseManagement/expenseReimbursement/employee.js'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { financeBookSave, financeBookFindBySn } from '@/api/financeBook.js'
export default {
  name: 'FcBaseModal',
  mixins: [commonMixin],
  components: { VSelect, Upload, employee, dealerSubareaScopeList },
  props: {
    show: [Boolean],
    itemSn: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      opened: this.show,
      spinning: false,
      disabled: false,
      title: '新增财务收款单',
      confirmLoading: false,
      bookSn: this.itemSn,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 }
      },
      attachList: [],
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo',
      form: {
        applyPersonSn: undefined,
        bookReason: '',
        payerType: 'DEALER',
        dealerSn: undefined,
        payerName: undefined,
        remarks: '',
        attachmentList: ''
      },
      rules: {
        applyPersonSn: [ { required: true, message: '请选择申请人', trigger: ['change', 'blur'] } ],
        bookReason: [ { 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'] } ]
      }
    }
  },
  methods: {
    // 申请人员
    employeeChange (v, r) {
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField(['applyPersonSn'])
      })
    },
    payerTypeChange (v) {
      this.$refs.ruleForm.clearValidate()
      // 重置数据
      this.form.dealerSn = ''
      this.form.payerName = ''
    },
    // 客户
    custChange (v) {
      console.log(v)
      if (v && v.key) {
        this.form.dealerSn = v.key
        this.form.payerName = v.row ? v.row.dealerName : ''
      } else {
        this.form.dealerSn = ''
        this.form.payerName = ''
      }
    },
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
      this.attachList.map(item => {
        item.fileType = item.extName
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.salesSaveFun()
        } else {
          return false
        }
      })
    },
    // 新建或编辑销售单
    salesSaveFun () {
      const _this = this
      const form = JSON.parse(JSON.stringify(_this.form))
      form.attachmentList = this.attachList
      _this.spinning = true
      financeBookSave(form).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          if (this.bookSn) {
            _this.$emit('refashData')
          } else {
            _this.$router.push({ name: 'financialCollectionEdit', params: { sn: res.data.bookSn } })
          }
          _this.cancel()
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    //  详情
    getDetail () {
      this.spinning = true
      this.confirmLoading = true
      financeBookFindBySn({ bookSn: this.bookSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.form = Object.assign(this.form, data)
          // 获取附件列表
          this.form.attachmentList = ''
          this.attachList = res.data.attachmentList
          this.$refs.attachList.setFileList(this.attachList)
          // 回显客户
          if (this.form.dealerSn && this.form.payerType == 'DEALER') {
            this.$nextTick(() => {
              this.$refs.settleClientName.getDetail(this.form.dealerSn)
            })
          }
        } else {
          this.$refs.ruleForm.resetFields()
        }
        this.spinning = false
        this.confirmLoading = false
      })
    },
    cancel () {
      this.opened = false
      this.$emit('cancel')
      this.$refs.ruleForm.resetFields()
    },
    pageInit () {
      this.$nextTick(() => {
        this.attachList = []
        this.$refs.attachList.setFileList('')
        this.$refs.ruleForm.resetFields()
        if (this.$refs.settleClientName) {
          this.$refs.settleClientName.resetForm()
        }
        this.form = {
          applyPersonSn: undefined,
          bookReason: '',
          payerType: 'DEALER',
          dealerSn: undefined,
          payerName: undefined,
          remarks: '',
          attachmentList: ''
        }
        if (this.bookSn) { //  编辑页
          this.getDetail()
          this.title = '编辑财务收款单'
        }
      })
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
      if (!newValue) {
        this.pageInit()
      }
    },
    itemSn (a, b) {
      this.bookSn = a
    }
  }
}
</script>
