<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['purchaseOrderId']" type="hidden"/>
      </a-form-item>

      <row-list :col="2">

        <row-item>

          <a-form-item
            label="供应商名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-if="contractFlag"
              v-decorator="['contractId', {rules: [{required: true, message: '供应商名称不能为空'}]}]"
              @change="changeContract"
              placeholder="请选择">
              <a-select-option
                v-for="item in contracts"
                :key="item.id"
                :label="item.sellerName"
                :value="item.id">{{ item.sellerName }}
              </a-select-option>
            </a-select>

            <a-select
              v-if="!contractFlag"
              v-decorator="['supplierId', {rules: [{required: true, message: '供应商名称不能为空'}]}]"
              @change="changeSupplier"
              placeholder="请选择">
              <a-select-option
                v-for="item in suppliers"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId">{{ item.supplierName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item v-if="contractFlag">
          <a-form-item
            label="合同编号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled="disabled"
              v-decorator="['contractNo']"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="付款事由"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['item', {rules: [{required: true, message: '付款事由不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in itemMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="付款金额"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['money', {rules: [{required: true, message: '付款金额不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="付款时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['payTime', {rules: [{required: true, message: '付款时间不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="预计报销时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['planReimburseTime', {rules: [{required: true, message: '预计报销时间不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="发票号码"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['invoiceNo']"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="币种"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              @change="changeMoneyType"
              v-decorator="['moneyType', {initialValue: 1, rules: [{required: true, message: '币种不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in moneyTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="汇率"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              v-decorator="['exchangeRate', {rules: [{required: true, message: '汇率不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="经办人"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['executorId', {rules: [{required: true, message: '经办人名称不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="user in users"
                :key="user.userId"
                :label="user.realName"
                :value="user.userId">{{ user.realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-textarea
              v-decorator="['remark']"/>
          </a-form-item>
        </row-item>
      </row-list>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="12" :sm="24">
          <a-form-item
            label="发票"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <upload-file :max-size="100" ref="upload" @catchFile="catchFile"></upload-file>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchasePayment, updatePurchasePayment } from '@/api/purchase/purchase-payment'
import { getOrderSuppliers } from '@/api/purchase/purchase-order'
import { queryPurchaseContract } from '@/api/purchase/purchase-contract'
import { querySysConfig } from '@/api/upms/config'
import { queryUser } from '@/api/upms/user'
import UploadFile from '@/components/Upload/UploadFile'

export default {
  name: 'BasePurchasePayment',
  components: { UploadFile },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      contractFlag: true,
      users: [],
      moneyTypeMap: {},
      order: {},
      suppliers: [],
      supplierMap: {},
      supplierName: null,
      supplierMoney: 0,
      contracts: [],
      contractAccountMoney: 0,
      invoiceUrls: [],
      invoiceNames: [],
      contractMap: {},
      // 下拉框map
      itemMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.itemMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PAY_ITEM)
    const moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    const newMap = {}
    const moneyTypes = this.$store.getters.userInfo.moneyTypes
    for (let i = 0; i < moneyTypes.length; i++) {
      const value = moneyTypes[i]
      newMap[value] = moneyTypeMap[value]
    }
    this.moneyTypeMap = newMap
    const rateMap = {}
    querySysConfig({}).then(res => {
      res.data.forEach((item) => {
        rateMap[item.code] = item.content
      })
      this.rateMap = rateMap
    })
    queryUser({}).then(res => {
      this.users = res.data
    })
  },
  methods: {
    base (record, order) {
      this.visible = true
      this.order = order
      this.contractFlag = order.contractFlag
      const { form: { setFieldsValue } } = this
      if (this.contractFlag) {
        queryPurchaseContract({ purchaseOrderId: order.id }).then(res => {
          this.contracts = res.data
          const map = {}
          this.contracts.forEach((item) => {
            map[item.id] = item
          })
          this.contractMap = map
          if (this.contracts.length > 0) {
            const contractId = this.contracts[0].id
            this.$nextTick(() => {
              setFieldsValue({
                contractId: contractId
              })
            })
            this.changeContract(contractId)
          }
        })
      } else {
        getOrderSuppliers({ id: order.id }).then(res => {
          this.suppliers = res.data
          const map = {}
          this.suppliers.forEach((item) => {
            map[item.supplierId] = item
          })
          this.supplierMap = map
          if (this.suppliers.length > 0) {
            const supplierId = this.suppliers[0].supplierId
            this.$nextTick(() => {
              setFieldsValue({
                supplierId: supplierId
              })
            })
            this.changeSupplier(supplierId)
          }
        })
      }

      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.$nextTick(() => {
          setFieldsValue({
            purchaseOrderId: order.id,
            moneyType: order.moneyType,
            exchangeRate: order.exchangeRate,
            executorId: this.$store.getters.userInfo.userId
          })
        })
        this.invoiceUrls = []
        this.invoiceNames = []
        this.$refs.upload.base([])
        return
      }
      this.modalTitle = '编辑'
      // 日期处理
      record.payTime = this.BaseTool.Moment(record.payTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.planReimburseTime = this.BaseTool.Moment(record.planReimburseTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'demandPlanId',
          'purchasePlanId',
          'purchaseApplyId',
          'purchaseOrderId',
          'moneyType',
          'exchangeRate',
          'contractId',
          'contractNo',
          'supplierId',
          'supplierName',
          'item',
          'money',
          'payTime',
          'planReimburseTime',
          'invoiceNo',
          'executorId',
          'executorName',
          'invoiceUrl',
          'remark',
          'delFlag'
        ])))
        const fileList = []
        if (record.invoiceUrl) {
          this.invoiceUrls = record.invoiceUrl.split(',')
          this.invoiceNames = record.invoiceName.split(',')
          for (let i = 0; i < this.invoiceUrls.length; i++) {
            fileList.push({
              uid: i,
              name: this.invoiceNames[i],
              status: 'done',
              url: this.invoiceUrls[i],
              originUrl: this.invoiceUrls[i]
            })
          }
        }
        this.$refs.upload.base(fileList)
      })
    },
    changeMoneyType (value) {
      const { form: { setFieldsValue } } = this
      let rate = 1
      if (this.order.projectMoneyType !== value) {
        rate = this.rateMap[this.DictCache.TYPE.MONEY_TYPE + value + '_' + this.order.projectMoneyType] || this.rateMap[this.DictCache.TYPE.MONEY_TYPE + this.order.projectMoneyType + '_' + value]
      }
      setFieldsValue({
        exchangeRate: rate
      })
    },
    changeContract (value) {
      const { form: { setFieldsValue } } = this
      this.contractAccountMoney = this.contractMap[value].accountTotalMoney
      setFieldsValue({
        contractNo: this.contractMap[value].no
      })
    },
    changeSupplier (value) {
      const { form: { setFieldsValue } } = this
      const supplier = this.supplierMap[value]
      this.supplierName = supplier.supplierName
      this.supplierMoney = supplier.supplyTotalMoney
      setFieldsValue({
        moneyType: supplier.moneyType,
        exchangeRate: supplier.exchangeRate,
        money: supplier.supplyTotalMoney
      })
    },
    catchFile (fileList) {
      const invoiceUrls = []
      const invoiceNames = []
      fileList.forEach((item) => {
        invoiceUrls.push(item.url)
        invoiceNames.push(item.name)
      })
      this.invoiceUrls = invoiceUrls
      this.invoiceNames = invoiceNames
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.contractFlag) {
          const accountMoney = this.BaseTool.Number.div(values.money, values.exchangeRate, 2)
          if (accountMoney > this.contractAccountMoney) {
            this.$message.error('付款金额（按记账主币）[' + accountMoney + ']不能超过合同金额[' + this.contractAccountMoney + ']')
            return
          }
        } else {
          if (values.money > this.supplierMoney) {
            this.$message.error('付款金额[' + values.money + ']不能超过采购总额[' + this.supplierMoney + ']')
            return
          }
        }

        // 日期处理
        values.payTime = this.BaseTool.Date.formatter(values.payTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.planReimburseTime = this.BaseTool.Date.formatter(values.planReimburseTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.invoiceUrl = this.invoiceUrls.join(',')
        values.invoiceName = this.invoiceNames.join(',')
        values.supplierName = this.supplierName
        if (this.BaseTool.String.isBlank(values.id)) {
          addPurchasePayment(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchasePayment(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    }

  }
}
</script>
