<template>
  <el-dialog :visible="visible" @close="close" @open="open" width="640px">
    <template slot="title">
      <div class="el-dialog__title">{{ update ? '编辑' : '新增' }}</div>
    </template>
    <el-form label-width="100px" :rules="rules" :model="model" ref="form">
      <el-form-item :label="$t('币种')" prop="currencies">
        <el-col :span="11">
            <el-select v-model="model.sourceId" :placeholder="$t('请选择原币种')" :disabled="update" clearable style="width: 100%">
              <el-option v-for="item in currencies" :key="item.id" :label="`${$l(item, 'title')} ${item.fuhao}`" :value="item.id"/>
            </el-select>
        </el-col>
        <el-col :span="2" class="center">
          <el-tooltip :content="$t('交换币种')" placement="top">
            <el-button size="mini" type="text" @click="swap" icon="el-icon-sort" style="transform: rotate(90deg)" :disabled="update"/>
          </el-tooltip>
        </el-col>
        <el-col :span="11">
            <el-select v-model="model.targetId" :placeholder="$t('请选择支付币种')" :disabled="update" clearable style="width: 100%">
              <el-option v-for="item in currencies" :key="item.id" :label="`${$l(item, 'title')} ${item.fuhao}`" :value="item.id"/>
            </el-select>
        </el-col>
      </el-form-item>
      <el-form-item :label="$t('金额')" prop="amounts">
        <el-col :span="11">
          <el-input-number :max="100000000" :precision="4" style="width: 100%" v-model="model.sourceAmount" :min="0.0001" :placeholder="$t('请输入金额')"/>
        </el-col>
        <el-col :span="2" class="center">:</el-col>
        <el-col :span="11">
          <el-input-number :max="100000000" :precision="4" style="width: 100%" v-model="model.targetAmount" :min="0.0001" :placeholder="$t('请输入金额')"/>
        </el-col>
      </el-form-item>
      <el-form-item :label="$t('汇率')" prop="rate">
        <el-col :span="11">
          <el-input :value="1" disabled/>
        </el-col>
        <el-col :span="2" class="center">:</el-col>
        <el-col :span="11">
          <el-input :value="rate" disabled/>
        </el-col>
      </el-form-item>
      <el-form-item :label="$t('国家')" prop="countries">
        <el-select v-model="model.countries" clearable filterable multiple :placeholder="$t('请选择国家')" style="width: 100%">
          <el-option v-for="item in countries" :key="item.id" :label="$l(item, 'name')" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('有效期')" prop="expiration">
        <el-col :span="11">
          <el-date-picker v-model="model.expiration" type="datetime" :placeholder="$t('请选择有效期')" :picker-options="pickerOptions" style="width: 100%"/>
        </el-col>
        <el-col :span="2">&nbsp;</el-col>
        <el-col :span="11">
          <div>
          <i v-if="model.expiration && expires > 0" class="diff">{{ expires }}天后过期</i>
          <i v-if="model.expiration && expires < 0" class="diff expired">已过期{{ 0 - expires }}天</i>
          </div>
        </el-col>
      </el-form-item>
      <el-form-item :label="$t('备注')" prop="remarks">
        <el-input type="textarea" v-model="model.remarks" :placeholder="$t('请输入备注')"/>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button type="primary" @click="submit">{{ $t('确定') }}</el-button>
      <el-button @click="close">{{ $t('取消') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { createCurrencyRate, updateCurrencyRate } from '@/api/ecw/currencyRate'
import dayjs from 'dayjs'
import Decimal from 'decimal.js'
import Vue from 'vue'

const modelDefaults = {
  remarks: '',
  countries: [],
  sourceAmount: 1,
  targetAmount: 1,
}

const props = {
  id: {},
  data: { type: Object, required: true, },
  visible: { type: Boolean, default: false, },
  countries: { type: Array, default: [], },
  currencies: { type: Array, default: [], },
}

export default Vue.extend({
  props,
  computed: {
    update() {
      return !!this.id
    },
    rate() {
      return this.decimal(this.model.targetAmount).dividedBy(this.model.sourceAmount).toFixed(8)
    },
    expires() {
      return dayjs(this.model.expiration).diff(dayjs().startOf('day'), 'day')
    },
    pickerOptions() {
      return {
        disabledDate(time) {
          return dayjs(time).isBefore(dayjs().startOf('day').add(1, 'day'))
        },
        shortcuts: [
          { text: this.$t('一周'), onClick(picker) { picker.$emit('pick', dayjs().add(7, 'day')) }, },
          { text: this.$t('一个月'), onClick(picker) { picker.$emit('pick', dayjs().add(1, 'month')) }, },
          { text: this.$t('三个月'), onClick(picker) { picker.$emit('pick', dayjs().add(3, 'month')) }, },
          { text: this.$t('半年'), onClick(picker) { picker.$emit('pick', dayjs().add(6, 'month')) }, },
          { text: this.$t('一年'), onClick(picker) { picker.$emit('pick', dayjs().add(1, 'year')) }, },
        ],
      }
    },
  },
  watch: {
    data(v) {
      this.model = { ...modelDefaults, ...v, }
    },
  },
  model: {
    prop: 'visible',
    event: 'update',
  },
  data() {
    return {
      model: { ...modelDefaults, ...this.data, },
      rules: {
        currencies: { required: true, validator: this.validateCurrencies, },
        amounts: { required: true, validator: this.validateAmounts, required: true, },
        expiration: { required: true, message: this.$t('请选择有效期'), },
      },
    }
  },
  methods: {
    decimal(a) {
      return new Decimal(a || 0)
    },
    swap() {
      this.model = { ...this.model, sourceId: this.model.targetId, targetId: this.model.sourceId, }
    },
    async submit() {
      if (await this.$refs['form'].validate().catch(() => {})) {
        if (this.update) {
          await updateCurrencyRate(this.model.id, this.model)
        } else {
          await createCurrencyRate(this.model)
        }

        this.$emit('update:model', this.model)
        this.close()
      }
    },
    open() {
    },
    close() {
      this.$emit('update:visible', false)
      this.$refs['form'].resetFields()
    },
    validateAmounts(r, v, callback) {
      const { sourceAmount, targetAmount } = this.model
      if (this.decimal(sourceAmount).lt(0.0001) || this.decimal(targetAmount).lt(0.0001)) {
        callback(new Error(this.$t('金额不能小于0.0001')))
      } else {
        callback()
      }
    },
    validateCurrencies(r, v, callback) {
      if (!(this.model.sourceId && this.model.targetId)) {
        callback(new Error(this.$t('原币种或支付币种不能为空')))
      } else if (this.model.sourceId == this.model.targetId) {
        callback(new Error(this.$t('两个币种不能相同')))
      } else {
        callback()
      }
    },
  },
})
</script>

<style scoped>
.text-right {
  text-align: right;
}
.expired {
  color: red!important;
}
.center {
  text-align: center;
}
.diff {
  color: green;
}
.rate {
  font-size: 120%;
  font-weight: bold;
}
</style>
