<template>
  <a-card :bordered="false" :title="modalTitle" v-show="visible">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right" >
          <!--          <a-popconfirm v-show="currentTab=== 2" title="提交审批操作过后将无法更改，确认进行该操作吗？" @confirm="save(DictCache.VALUE.PURCHASE_DEMAND_PLAN_STATUS.PURCHASE_DEMAND_PLAN_STATUS_SHE)">-->
          <!--            <a-button type="danger">提交审批</a-button>-->
          <!--          </a-popconfirm>-->
          <a-button v-show="currentTab!== 0" style="margin-left: 8px" @click="prev()">上一步</a-button>
          <a-button style="margin-left: 8px" v-show="currentTab!== 2" type="primary" @click="next()">下一步</a-button>
          <a-button style="margin-left: 8px" v-show="currentTab=== 2" type="primary" @click="save()">保存</a-button>
          <a-popconfirm
            style="margin-left: 8px"
            v-show="currentTab=== 2"
            title="提交操作过后将无法更改，确认进行该操作吗？"
            @confirm="save(1)">
            <a-button type="danger">提交</a-button>
          </a-popconfirm>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回列表</a-button>
        </span>
      </a-col>
    </a-row>
    <a-steps class="steps" :current="currentTab">
      <a-step title="填报基本信息" />
      <a-step title="选择采购单" />
      <a-step title="确认" />
    </a-steps>
    <title-divider title="基本信息" v-show="currentTab=== 2" width="90px"></title-divider>
    <a-form :form="form" v-show="currentTab === 0 || currentTab=== 2">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" 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-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-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 v-show="currentTab === 2">

          <a-form-item
            label="付款金额"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              disabled="disabled"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-model="money"/>
          </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>
    <title-divider v-show="currentTab=== 2" title="选择采购单" width="90px"></title-divider>
    <purchase-payment-order ref="purchasePaymentOrder" @ok="updateMoney" v-show="currentTab=== 1 || currentTab=== 2"></purchase-payment-order>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchasePayment, fetchPurchasePayment, updatePurchasePayment } from '@/api/purchase/purchase-payment'
import { queryUser } from '@/api/upms/user'
import UploadFile from '@/components/Upload/UploadFile'
import PurchasePaymentOrder from '@/views/purchase/purchase-payment-order/PurchasePaymentOrder'

export default {
  name: 'BasePurchasePayment',
  components: { PurchasePaymentOrder, UploadFile },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      addFlag: true,
      user: this.$store.getters.userInfo,
      currentTab: 0,
      record: {},
      money: 0,
      id: '-1',
      users: [],
      moneyTypeMap: {},
      invoiceUrls: [],
      invoiceNames: [],
      // 下拉框map
      itemMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.itemMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PAY_ITEM)
    queryUser({}).then(res => {
      this.users = res.data
    })
  },
  methods: {
    base (record) {
      this.addFlag = true
      this.form.resetFields()
      const { form: { setFieldsValue } } = this
      this.currentTab = 0
      this.BaseTool.ListForm.clearOneList(this)
      this.visible = true
      // 如果是空标识添加
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.id = '-1'
        this.modalTitle = '添加付款'
        this.invoiceUrls = []
        this.invoiceNames = []
        this.$refs.upload.base([])
        const { form: { setFieldsValue } } = this
        this.$nextTick(() => {
          setFieldsValue({
            payTime: this.BaseTool.Moment(new Date(), this.BaseTool.Date.PICKER_NORM_DATE_PATTERN),
            planReimburseTime: this.BaseTool.Moment(new Date(), this.BaseTool.Date.PICKER_NORM_DATE_PATTERN),
            executorId: this.$store.getters.userInfo.userId
          })
        })
        return
      }
      this.modalTitle = '编辑'
      this.addFlag = false
      // 日期处理
      this.id = record.id
      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)
      })
    },
    catchFile (fileList) {
      const invoiceUrls = []
      const invoiceNames = []
      fileList.forEach((item) => {
        invoiceUrls.push(item.url)
        invoiceNames.push(item.name)
      })
      this.invoiceUrls = invoiceUrls
      this.invoiceNames = invoiceNames
    },
    viewList (id) {
      this.$nextTick(() => {
        const modal = this.$refs.purchasePaymentOrder
        modal.base(id)
      })
    },
    next () {
      if (this.currentTab === 0) {
        this.save()
      } else {
        this.currentTab += 1
      }
      if (this.currentTab === 2) {
        fetchPurchasePayment({ id: this.id }).then(res => {
          this.money = res.data.money
        })
      }
    },
    updateMoney () {
      fetchPurchasePayment({ id: this.id }).then(res => {
        this.money = res.data.money
      })
    },
    prev () {
      this.currentTab -= 1
    },
    save (value) {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          console.log(errors)
          this.confirmLoading = false
          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.submitType = value
        // 日期处理
        if (this.addFlag) {
          addPurchasePayment(values)
            .then((res) => {
              this.currentTab += 1
              const record = res.data
              this.viewList(record.id)
              this.id = record.id
              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)
              const { form: { setFieldsValue } } = this
              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)
              })
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchasePayment(values)
            .then(() => {
              if (this.currentTab === 2) {
                this.handleCancel({})
                return
              }
              this.currentTab += 1
              this.viewList(values.id)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
