<template>
  <platform-page @change="onTenantChange">
    <template #default>
      <schema-table
        ref="table"
        class="c-sibling-item far"
        :schema="schema"
      />
      <radio-table-dialog
        ref="stockDialog"
        title="库存"
        :schema="stockSchema"
        @confirm="onChoosen"
      />
      <confirm-dialog
        ref="addDialog"
        title="分配"
        @confirm="onSave"
      >
        <div class="c-grid-form sm u-align-self--center">
          <span class="c-grid-form__label">类型</span>
          <schema-select
            v-model="credit.auditType"
            class="u-width--xs"
            :schema="auditTypeSchema"
            disabled
          />
          <span class="c-grid-form__label">次数</span>
          <div class="l-flex--row">
            <el-input-number
              v-model="credit.initialAmount"
              class="c-sibling-item"
              :min="1"
              :max="remaining"
              step-strictly
            />
            <span class="c-sibling-item u-color--info light">1 ~ {{ remaining }}</span>
          </div>
          <span class="c-grid-form__label u-required">有效期</span>
          <el-date-picker
            v-model="credit.date"
            class="u-width--auto"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            :clearable="false"
          />
        </div>
      </confirm-dialog>
    </template>
  </platform-page>
</template>

<script>
import {
  AssetType,
  AssetTypeInfo
} from '@/constant'
import {
  getCredits,
  getTenantCredits,
  addCredit,
  deleteCredit
} from './api'

export default {
  name: 'StockAssign',
  data () {
    const auditTypeOptions = [
      { value: AssetType.IMAGE, label: AssetTypeInfo[AssetType.IMAGE] },
      { value: AssetType.VIDEO, label: AssetTypeInfo[AssetType.VIDEO] }
    ]

    return {
      tenant: null,
      auditTypeSchema: {
        options: auditTypeOptions
      },
      schema: {
        list: this.getTenantCredits,
        buttons: [
          { type: 'add', label: '分配', on: this.onAdd }
        ],
        filters: [
          { key: 'auditType', type: 'select', placeholder: '类型', options: auditTypeOptions }
        ],
        cols: [
          { label: '类型', render: this.transformAuditType, width: 100, align: 'center' },
          { prop: 'effectiveDate', label: '生效日期' },
          { prop: 'expiryDate', label: '结束日期' },
          { prop: 'initialAmount', label: '总次数' },
          { prop: 'remaining', label: '剩余次数' },
          { type: 'invoke', render: [
            { label: '删除', on: this.onDel }
          ] }
        ]
      },
      stockSchema: {
        list: getCredits,
        filters: [
          { key: 'auditType', type: 'select', placeholder: '类型', options: auditTypeOptions }
        ],
        cols: [
          { label: '类型', render: this.transformAuditType, width: 100, align: 'center' },
          { prop: 'effectiveDate', label: '生效日期' },
          { prop: 'expiryDate', label: '结束日期' },
          { label: '可分配', render: ({ initialAmount, allocatedAmount }) => `${initialAmount - allocatedAmount}` }
        ]
      },
      fromCredit: {},
      credit: {},
      pickerOptions: {
        disabledDate: this.disabledDate
      }
    }
  },
  computed: {
    remaining () {
      return this.fromCredit
        ? this.fromCredit.initialAmount - this.fromCredit.allocatedAmount
        : 0
    }
  },
  methods: {
    disabledDate (date) {
      if (this.fromCredit) {
        const { effectiveDate, expiryDate } = this.fromCredit
        return date < new Date(`${effectiveDate} 00:00:00`) || date > new Date(`${expiryDate} 00:00:00`)
      }
      return false
    },
    transformAuditType (data) {
      return AssetTypeInfo[data.auditType]
    },
    onTenantChange (tenant) {
      if (!this.tenant || this.tenant.id !== tenant.id) {
        this.tenant = tenant
        this.$refs.table?.pageTo(1)
      }
    },
    getTenantCredits (params) {
      return getTenantCredits({
        tenant: this.tenant.path,
        ...params
      })
    },
    onAdd () {
      this.$refs.stockDialog.show()
    },
    onChoosen ({ value, done }) {
      const { auditType, initialAmount, allocatedAmount, effectiveDate, expiryDate } = value
      if (initialAmount - allocatedAmount < 1) {
        this.$message({
          type: 'warning',
          message: '可分配次数不足，请重新选择'
        })
        return
      }
      this.fromCredit = value
      this.credit = {
        auditType,
        initialAmount: this.remaining,
        date: [effectiveDate, expiryDate]
      }
      done()
      this.$refs.addDialog.show()
    },
    onSave (done) {
      const { auditType, initialAmount, date } = this.credit
      if (!date) {
        this.$message({
          type: 'warning',
          message: '请选择有效期'
        })
        return
      }
      addCredit({
        admin: 0,
        fromCredit: this.fromCredit.id,
        tenant: this.tenant.path,
        auditType,
        initialAmount,
        effectiveDate: date[0],
        expiryDate: date[1]
      }).then(() => {
        done()
        this.$refs.table.pageTo(1)
      })
    },
    onDel (credit) {
      deleteCredit(credit).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
