<template>
  <div class="l-flex">
    <template v-if="groups">
      <div class="c-tree-sidebar u-overflow-y--auto">
        <el-tree
          ref="groupTree"
          :data="groups"
          class="c-tree-sidebar__main"
          node-key="path"
          highlight-current
          @node-click="onGroupTreeClick"
        />
      </div>
      <schema-table
        ref="table"
        :schema="schema"
      >
        <table-dialog
          ref="stockDialog"
          title="总库存"
          :schema="stockSchema"
          @choosen="onChoosen"
        />
        <confirm-dialog
          ref="addDialog"
          title="分配"
          @confirm="onSave"
        >
          <div class="c-grid-form u-align-self--center">
            <span class="c-grid-form__label">类型：</span>
            <schema-select
              v-model="credit.auditType"
              :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 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"
            />
          </div>
        </confirm-dialog>
      </schema-table>
    </template>
    <template v-else>
      <div
        v-loading="loading"
        class="l-flex__auto l-flex--row center"
      >
        <template v-if="!loading">
          <warning
            v-if="error"
            @click="getTreeData"
          />
          <div
            v-else
            class="u-bold"
          >
            暂无租户，请先添加租户
          </div>
        </template>
      </div>
    </template>
  </div>
</template>

<script>
import { getTopGroups } from '@/api/user'
import {
  getCredits,
  getTenantCredits,
  addCredit,
  deleteCredit
} from './api'

export default {
  name: 'StockAssign',
  data () {
    const auditTypeOptions = [
      { value: 1, label: '图片' },
      { value: 2, label: '视频' }
    ]

    return {
      loading: true,
      error: false,
      groups: null,
      group: null,
      auditTypeSchema: {
        options: auditTypeOptions
      },
      schema: {
        condition: { auditType: void 0 },
        list: this.getTenantCredits,
        buttons: [
          { type: 'add', label: '分配', on: this.onAdd }
        ],
        filters: [
          { key: 'auditType', type: 'select', placeholder: '全部类型', options: auditTypeOptions }
        ],
        cols: [
          { label: '审核类型', render: this.transformAuditType },
          { prop: 'effectiveDate', label: '生效日期' },
          { prop: 'expiryDate', label: '结束日期' },
          { prop: 'initialAmount', label: '总次数' },
          { prop: 'remaining', label: '剩余次数' },
          { type: 'invoke', render: [
            { label: '删除', on: this.onDel }
          ] }
        ]
      },
      stockSchema: {
        condition: { auditType: void 0 },
        list: getCredits,
        filters: [
          { key: 'auditType', type: 'select', placeholder: '全部类型', options: auditTypeOptions }
        ],
        cols: [
          { label: '审核类型', render: this.transformAuditType },
          { prop: 'effectiveDate', label: '生效日期' },
          { prop: 'expiryDate', label: '结束日期' },
          { label: '可分配', render ({ initialAmount, allocatedAmount }) {
            return initialAmount - allocatedAmount
          } }
        ]
      },
      fromCredit: {},
      credit: {},
      pickerOptions: {
        disabledDate: this.disabledDate
      }
    }
  },
  computed: {
    remaining () {
      return this.fromCredit
        ? this.fromCredit.initialAmount - this.fromCredit.allocatedAmount
        : 0
    }
  },
  created () {
    this.getTreeData()
  },
  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 ['', '图片', '视频'][data.auditType]
    },
    getTreeData () {
      this.loading = true
      this.error = false
      getTopGroups().then(
        ({ data }) => {
          if (data.length) {
            this.groups = data
            this.group = this.groups[0]
            this.$nextTick(() => {
              this.$refs.groupTree.setCurrentKey(this.group.path)
            })
          }
        },
        () => {
          this.error = true
        }
      ).finally(() => {
        this.loading = false
      })
    },
    onGroupTreeClick (group) {
      if (!this.group || this.group.id !== group.id) {
        this.group = group
        this.$refs.table.pageTo(1)
      }
    },
    getTenantCredits (params) {
      return getTenantCredits({
        tenant: this.group.path,
        ...params
      })
    },
    onAdd () {
      this.$refs.stockDialog.show()
    },
    onChoosen ({ value, done }) {
      const { auditType, initialAmount, allocatedAmount } = value
      if (initialAmount - allocatedAmount < 1) {
        this.$message({
          type: 'warning',
          message: '可分配次数不足，请重新选择'
        })
        return
      }
      this.fromCredit = value
      this.credit = {
        auditType,
        initialAmount: 1,
        date: ''
      }
      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.group.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>
