<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-input-search
              enter-button="选择"
              v-decorator="['purchaseOrderNo', {rules: [{required: true, message: '编号不能为空'}]}]"
              @search="handleSelect"
            />
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="付款记录"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-search
              enter-button="选择"
              v-decorator="['paymentId']"
              @search="handleSelectPay"
            />
          </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
              :disabled="payFlag"
              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-select
              @change="changeMoneyType"
              :disabled="flag"
              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
              :disabled="flag"
              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-form>
    <purchase-order-select-modal ref="selectModal" @selected="handleSelected"></purchase-order-select-modal>
    <purchase-payment-select-order-modal ref="selectModalPay" @selected="handleSelectedPay"></purchase-payment-select-order-modal>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import { addPurchaseReimburseOrder, updatePurchaseReimburseOrder } from '@/api/purchase/purchase-reimburse-order'
import { querySysConfig } from '@/api/upms/config'
import { queryUser } from '@/api/upms/user'
import PurchaseOrderSelectModal from '@/views/purchase/purchase-order/modules/PurchaseOrderSelectModalForPay'
import PurchasePaymentSelectOrderModal from '@/views/purchase/purchase-payment-order/modules/PurchasePaymentSelectOrderModal'

export default {
  name: 'BasePurchaseReimburseOrder',
  components: { PurchaseOrderSelectModal, PurchasePaymentSelectOrderModal },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      contractFlag: true,
      users: [],
      moneyTypeMap: {},
      reimburse: {},
      order: {},
      invoiceUrls: [],
      invoiceNames: [],
      record: {},
      flag: true,
      payFlag: false,
      // 下拉框map
      itemMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.itemMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REIMBURSE_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, reimburse) {
      this.visible = true
      this.reimburse = reimburse
      // 如果是空标识添加
      const { form: { setFieldsValue } } = this
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.flag = !!reimburse.moneyType
        this.payFlag = false
        this.$nextTick(() => {
          setFieldsValue({
            moneyType: reimburse.moneyType,
            exchangeRate: reimburse.exchangeRate,
            payTime: this.BaseTool.Moment(new Date(), this.BaseTool.Date.PICKER_NORM_DATE_PATTERN),
            executorId: this.$store.getters.userInfo.userId
          })
        })
      }
      // this.modalTitle = '编辑'
      // this.addFlag = false
      // // 日期处理
      // 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)
      // console.log(record.planReimburseTime)
      // this.flag = false
      // this.record = record
      // fetchPurchaseOrder({ id: record.purchaseOrderId }).then(res => {
      //   this.chose(res.data)
      // })
    },
    handleSelect () {
      this.$refs.selectModal.base(null, { purchaserId: this.$store.getters.userInfo.userId, unReimburseMoney: 0 })
    },
    handleSelectPay () {
      this.$refs.selectModalPay.base(null, { executorId: this.$store.getters.userInfo.userId, status: 1, noReimburse: 1, purchaseOrderId: this.order.id })
    },
    handleSelected (record, keys, rows) {
      const [ row ] = rows
      this.order = row
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue({
          purchaseOrderId: row.id,
          purchaseOrderNo: row.billNo
        })
      })
    },
    handleSelectedPay (record, keys, rows) {
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.payFlag = true
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue({
          paymentId: row.id,
          money: row.money
        })
      })
    },
    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
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期处理
        values.payTime = this.BaseTool.Date.formatter(values.payTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.reimburseId = this.reimburse.id
        if (this.BaseTool.String.isBlank(values.id)) {
          addPurchaseReimburseOrder(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchaseReimburseOrder(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>
