<template>
  <a-modal
    :visible="visible"
    :title="modalType==='edit'?'编辑会员类型':'新增会员类型'"
    @ok="handleOk"
    width="60%"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <div>
        <a-form-model :model="form" ref="form">
          <div class="block-title">
            绑定景点和渠道
          </div>
          <a-form-model-item
            label="已绑定景点"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-select mode="multiple" v-model="bindScenic">
              <a-select-option
                v-for="scenic in scenicList"
                :key="scenic.id"
                :value="scenic.id"
              >
                <a-badge :status="scenic.status==='active'?'success':'error'"/>{{ scenic.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
            label="已绑定渠道"
            v-bind="formItemLayout2"
            style="width:100%"
          >
            <a-select mode="multiple" v-model="bindChannel">
              <a-select-option
                v-for="channel in salesChannel"
                :key="channel.id"
                :value="channel.id"
              >
                {{ channel.description }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <div class="block-title">
            基础信息
          </div>
          <a-form-model-item
            label="会员类型名称"
            v-bind="formItemLayout"
            prop="name"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input v-model="form.name"></a-input>
          </a-form-model-item>

          <a-form-model-item
            label="价格码"
            v-bind="formItemLayout"
            prop="ticket_product_id"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <a-select style="width: 100%" :disabled="modalType==='edit'" v-model="form.ticket_product_id">
              <a-select-option
                v-for="(i,index) in ticketProductList"
                :value="i.ticket_product_id"
                :key="index"
              >
                <a-badge :status="i.status==='active'?'success':'error'"/>
                {{ i.ticket_product_id }} - {{ i.description }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
            label="会员卡时长类型"
            v-bind="formItemLayout"
            prop="valid_days_type"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-select v-model="form.valid_days_type" @change="handleChange(form.valid_days_type)">
              <a-select-option value="days">
                按天
              </a-select-option>
              <a-select-option value="range">
                按范围
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
            v-if="form.valid_days_type==='range'"
            label="会员卡时长范围"
            v-bind="formItemLayout"
            prop="use_valid_range"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-range-picker v-model="form.use_valid_range" :allowClear="false" />
          </a-form-model-item>

          <a-form-model-item
            v-if="form.valid_days_type==='days'"
            label="会员卡时长天数"
            v-bind="formItemLayout"
            prop="use_valid_days"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number :min="1" v-model="form.use_valid_days">
            </a-input-number>
          </a-form-model-item>

          <a-form-model-item
            label="价格"
            v-bind="formItemLayout"
            prop="price"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number
              :precision="2"
              :min="0"
              :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
              v-model="form.price"
            />
          </a-form-model-item>

          <a-form-model-item
            label="购买人实名认证"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-model="form.need_realname"
            />
          </a-form-model-item>

          <a-form-item
            label="游客实名认证"
            v-bind="formItemLayout"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-model="form.player_need_realname"
            />
          </a-form-item>

          <a-form-model-item
            label="显示二维码"
            v-bind="formItemLayout"
            prop="show_qrcode"
          >
            <a-switch
              checkedChildren="是"
              unCheckedChildren="否"
              v-model="form.show_qrcode"></a-switch>
          </a-form-model-item>

          <a-form-model-item
            label="线上办理会员"
            v-bind="formItemLayout"
            prop="is_member_online"
          >
            <a-switch
              checkedChildren="是"
              unCheckedChildren="否"
              v-model="form.is_member_online"></a-switch>
          </a-form-model-item>

          <a-form-model-item
            label="是否录入人脸"
            v-if="form.is_member_online"
            v-bind="formItemLayout"
            prop="is_member_online_face"
          >
            <a-switch
              checkedChildren="是"
              unCheckedChildren="否"
              v-model="form.is_member_online_face"></a-switch>
          </a-form-model-item>
          <a-form-model-item
            label="是否是兑换票"
            v-bind="formItemLayout"
            prop="is_convertible"
          >
            <a-switch
              checkedChildren="是"
              unCheckedChildren="否"
              v-model="form.is_convertible"></a-switch>
          </a-form-model-item>
          <a-form-model-item
            label="佣金"
            v-bind="formItemLayout"
            prop="commission"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number
              :precision="2"
              :min="0"
              :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
              v-model="form.commission"
            />
          </a-form-model-item>

          <a-form-model-item
            label="会员人数"
            v-if="form.is_member_online"
            v-bind="formItemLayout"
            prop="person_num"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number v-model="form.person_num"></a-input-number>
          </a-form-model-item>

          <a-form-model-item
            label="会员卡封面"
            v-bind="formItemLayout"
            prop="card_pic"
          >
            <a-upload
              :action="uploadUrl"
              listType="picture-card"
              :fileList="fileList"
              :before-upload="beforeImageUpload"
              @preview="handlePreview"
              @change="handleImageChange($event)"
            >
              <div v-if="fileList.length < 1">
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  点击上传
                </div>
              </div>
            </a-upload>
          </a-form-model-item>

          <div class="block-title">
            销售限制
          </div>
          <a-form-model-item
            label="售票日期范围"
            v-bind="formItemLayout"
            prop="sellDate"
            :rules="[{ required: true, message: '请选择销售日期' }]"
          >
            <a-range-picker v-model="form.sellDate"/>
          </a-form-model-item>

          <a-form-model-item
            label="使用日期范围"
            v-bind="formItemLayout"
            prop="useDate"
            :rules="[{ required: true, message: '请选择使用日期' }]"
          >
            <a-range-picker v-model="form.useDate"/>
          </a-form-model-item>

          <a-form-model-item
            label="可售开始时间"
            v-bind="formItemLayout"
            prop="sale_time_start"
            :rules="[{ required: true, message: '请选择时间' }]"
          >
            <a-time-picker v-model="form.sale_time_start"/>
          </a-form-model-item>

          <a-form-model-item
            label="可售截止时间"
            v-bind="formItemLayout"
            prop="sale_time_end"
            :rules="[{ required: true, message: '请选择时间' }]"
          >
            <a-time-picker v-model="form.sale_time_end"/>
          </a-form-model-item>

          <a-form-model-item
            label="使用开始时间"
            v-bind="formItemLayout"
            prop="use_time_start"
            :rules="[{ required: true, message: '请选择结束时间' }]"
          >
            <a-time-picker v-model="form.use_time_start"/>
          </a-form-model-item>

          <a-form-model-item
            label="使用截止时间"
            v-bind="formItemLayout"
            prop="use_time_end"
            :rules="[{ required: true, message: '请选择结束时间' }]"
          >
            <a-time-picker v-model="form.use_time_end"/>
          </a-form-model-item>

          <a-form-model-item
            label="最小起订数"
            v-bind="formItemLayout"
            prop="book_min"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number :min="0" v-model="form.book_min">
            </a-input-number>
          </a-form-model-item>

          <a-form-model-item
            label="最大限订数"
            v-bind="formItemLayout"
            prop="book_max"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number :min="0" v-model="form.book_max">
            </a-input-number>
          </a-form-model-item>

          <a-form-model-item
            label="可提前预定天数"
            v-bind="formItemLayout"
            prop="book_future_days"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number :min="0" v-model="form.book_future_days">
            </a-input-number>
          </a-form-model-item>

          <a-alert type="warning">
            <div slot="message"><b class="red">【白名单】</b>：以下列数字开头的<b class="red">游客身份证</b>才可购买。<b class="red">打开游客实名认证,才可生效</b></div>
          </a-alert>
          <a-form-item
            style="width:100%"
            label="身份证号白名单"
            v-bind="formItemLayout2"
          >
            <a-tag
              :key="tag"
              v-for="tag in limitIdentities"
              closable
              :disable-transitions="false"
              @close="handleClose(tag,'limitIdentities')">
              {{ tag }}
            </a-tag>
            <a-input
              type="text"
              class="input-new-tag"
              placeholder="2~6位数字"
              v-if="limitIdentities.inputVisible"
              v-model="limitIdentities.inputValue"
              ref="limitIdentitiesInput"
              size="small"
              :min-length="2"
              :max-length="6"
              @keyup.enter.native="handleInputConfirm('limitIdentities')"
              @blur="handleInputConfirm('limitIdentities')"
            ></a-input>
            <a-button v-else type="primary" size="small" @click="showInput('limitIdentities')">添加</a-button>
          </a-form-item>

          <div class="block-title">
            销售数量设置
          </div>
          <a-form-model-item
            label="是否限制销售数量"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="is_restricted_sales"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-model="form.is_restricted_sales"
            />
          </a-form-model-item>

          <a-form-model-item
            v-if="form.is_restricted_sales"
            label="每天可销售数量"
            v-bind="formItemLayout"
            prop="sales_volume"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number :min="0" v-model="form.sales_volume">
            </a-input-number> （不限制填 0）
          </a-form-model-item>

          <a-form-model-item
            label="是否加入限购"
            style="width:100%"
            v-bind="formItemLayout2"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-model="form.is_order_limit"
            />
          </a-form-model-item>
          <a-form-model-item
            label="选择限购组"
            v-if="form.is_order_limit"
            v-bind="formItemLayout"
          >
            <a-select
              v-model="form.order_limit_group"
            >
              <a-select-option
                v-for="(i,index) in limitGroupList"
                :value="i.id"
                :key="index"
              >
                {{ i.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
            v-if="form.is_restricted_sales"
            label="总库存"
            v-bind="formItemLayout"
            prop="total_sales_limit"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input-number :min="0" v-model="form.total_sales_limit">
            </a-input-number> （不限制填 0）
          </a-form-model-item>

          <div class="block-title">
            退票设置
          </div>
          <a-form-model-item
            label="是否可退"
            v-bind="formItemLayout2"
            prop="is_refund"
            style="width:100%"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-model="form.is_refund"
            />
          </a-form-model-item>

          <template v-if="form.is_refund">
            <a-form-model-item
              label="提前可退天数"
              v-bind="formItemLayout"
              prop="refund_advance_days"
              :rules="[{ required: true, message: '请输入' }]"
            >
              <RefundAdvanceDay v-model="form.refund_advance_days"></RefundAdvanceDay>
            </a-form-model-item>

            <a-form-model-item
              label="当日可退截止时间"
              v-bind="formItemLayout"
              prop="refund_today_endtime"
              :rules="[{ required: true, message: '请选择结束时间' }]"
            >
              <RefundDayEndtime v-model="form.refund_today_endtime"></RefundDayEndtime>
            </a-form-model-item>

            <a-form-model-item
              label="退票策略"
              v-bind="formItemLayout"
              prop="refund_strategy"
            >
              <a-select v-model="form.refund_strategy.type">
                <a-select-option value="FIXED">
                  固定价格
                </a-select-option>
                <a-select-option value="RATE">
                  固定费率
                </a-select-option>
                <a-select-option value="TIME_RATE">
                  阶梯费率
                </a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item
              label="退票费率"
              v-if="form.refund_strategy.type==='RATE'"
              v-bind="formItemLayout"
              :rules="[{ required: true, message: '请输入' }]"
              prop="refund_strategy.rate"
            >
              <a-input-number
                :precision="2"
                :min="0"
                :max="1"
                :step="0.01"
                v-model="form.refund_strategy.rate"
              />（0 表示全额退款）
            </a-form-model-item>

            <a-form-model-item
              label="退票价格"
              v-if="form.refund_strategy.type==='FIXED'"
              v-bind="formItemLayout"
              :rules="[{ required: true, message: '请输入' }]"
              prop="refund_strategy.price"
            >
              <a-input-number
                :precision="2"
                :min="0"
                :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
                v-model="form.refund_strategy.price"
              />
            </a-form-model-item>
            <br>
            <a-form-model-item
              label="阶梯费率"
              v-if="form.refund_strategy.type==='TIME_RATE'"
              v-bind="formItemLayout"
            >
              <a-button
                class="addBtn"
                type="primary"
                icon="plus"
                @click="handleAdd"
                size="small"
              >新增</a-button>
              <br>
              <ul class="priceList">
                <li
                  v-for="(item,index) in timeRateList"
                  :key="index"
                >

                  <template>
                    <div style="display:flex;margin-bottom:10px;width:400px">
                      <span style="white-space:nowrap">时间：</span>
                      <a-select v-model="item.timeEffect" slot="prepend" placeholder="请选择">
                        <a-select-option value="+">开场前</a-select-option>
                        <a-select-option value="-">开场后</a-select-option>
                      </a-select>
                      <a-input-number
                        style="width:100%"
                        v-model="item.timeNum"
                        controls-position="right"
                        :min="0"
                        :max="999"></a-input-number>
                      <a-select v-model="item.timeType" slot="prepend" placeholder="请选择">
                        <a-select-option value="minute">分钟</a-select-option>
                        <a-select-option value="hour">小时</a-select-option>
                        <a-select-option value="day">天</a-select-option>
                        <a-select-option value="week">周</a-select-option>
                        <a-select-option value="month">月</a-select-option>
                      </a-select>
                      <span style="white-space:nowrap" v-if="item.timeEffect">{{ item.timeEffect ==='-'?'之后':'以内' }}</span>
                      <span style="white-space:nowrap;margin-left:20px">费率：</span>
                      <a-input-number
                        style="width:100%;"
                        :precision="2"
                        :min="0"
                        :max="1"
                        :step="0.01"
                        v-model="item.rate"
                      />
                      <a-tooltip placement="top">
                        <template slot="title">
                          <span>删除</span>
                        </template>

                        <a-popconfirm
                          title="确定删除吗？"
                          @confirm="handleDelete(index)"
                          ok-text="是"
                          cancel-text="否"
                        >
                          <a-button
                            type="danger"
                            icon="close"
                            size="small"
                            style="width:100px"
                          ></a-button>
                        </a-popconfirm>
                      </a-tooltip>
                    </div>
                  </template>
                </li>
              </ul>
            </a-form-model-item>
          </template>

          <div class="block-title">
            详情介绍
          </div>

          <a-form-model-item
            label="标签"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="tags"
          >
            <a-select
              mode="multiple"
              style="width: 100%"
              v-model="form.tags"
            >
              <a-select-option
                v-for="(i,index) in tagList"
                :value="i.id"
                :key="index"
              >
                {{ i.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
            label="购票须知"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="purchase_notice"
          >
            <Editor ref="editor" v-model="form.purchase_notice"></Editor>

          </a-form-model-item>

          <a-form-model-item
            label="使用须知"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="description"
          >
            <Editor ref="editor" v-model="form.description"></Editor>

          </a-form-model-item>

          <a-form-model-item
            label="退改须知"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="withdrawal_notice"
          >
            <Editor ref="editor" v-model="form.withdrawal_notice"></Editor>

          </a-form-model-item>

          <a-form-model-item
            label="其他须知"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="other_notice"
          >
            <Editor ref="editor" v-model="form.other_notice"></Editor>

          </a-form-model-item>

          <div class="block-title">
            购票协议
          </div>

          <a-form-model-item
            label="是否显示会员购票协议"
            v-bind="formItemLayout"
            prop="is_use_purchase_protocol"
          >
            <a-switch
              checkedChildren="是"
              unCheckedChildren="否"
              v-model="form.is_use_purchase_protocol"></a-switch>
          </a-form-model-item>

          <a-form-model-item
            label="购票协议"
            v-bind="formItemLayout2"
            style="width:100%"
            prop="purchase_protocol"
          >
            <Editor ref="editor" v-model="form.purchase_protocol"></Editor>

          </a-form-model-item>

        </a-form-model>
      </div>
    </a-spin>
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="previewVisible=false"
    >
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage"
      >
    </a-modal>

    <ImageCropper
      ref="cropper"
      :width="326"
      :height="148"
      @success="handleCropper"
    ></ImageCropper>
  </a-modal>
</template>

<script>
import { setTicketTypeById, getTicketTypeById, getTicketScenic, setTicketScenic, getTicketChannel, setTicketChannel, addTicketType } from '@/api/ticketSetting/ticket'
import ticketMixin from './ticketMixin.js'
import ImageCropper from '@/components/ImageCropper'
import Editor from '@/components/Editor/index.vue'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  mixins: [ticketMixin],
  components: {
    ImageCropper,
    Editor
  },
  data () {
    return {
      visible: false,
      loading: false,
      formData: null,
      bindScenic: [],
      bindChannel: [],
      timeRateList: [
        { timeEffect: '+',
          timeNum: '30',
          timeType: 'minute',
          rate: 0
        }
      ],
      limitIdentities: [],
      fileList: [],
      previewVisible: false,
      previewImage: '',
      form: {}
    }
  },
  methods: {
    handleAdd () {
      let lastTimeRate
      if (this.timeRateList.length > 0) {
        lastTimeRate = JSON.parse(JSON.stringify(this.timeRateList[this.timeRateList.length - 1]))
      } else {
        lastTimeRate = { seconds: '', rate: '' }
      }
      this.timeRateList.push({
        ...lastTimeRate
      })
    },
    handleDelete (index) {
      this.timeRateList.splice(index, 1)
    },
    show (id) {
      this.visible = true

      this.$nextTick(() => {
        this.initForm()
        // this.$refs.form.resetFields()

        this.fileList = []

        if (id) { // 编辑
          this.id = id
          this.modalType = 'edit'

          this.loading = true

          Promise.all([this.getTicketDetail(), this.getTicketScenic(), this.getTicketChannel()])
            .finally(() => {
              this.loading = false
            })
        } else { // 新增
          this.modalType = 'add'
          this.bindScenic = []
          this.bindChannel = []
        }
      })
    },
    // 获取门票详情
    getTicketDetail () {
      return getTicketTypeById(this.id).then(res => {
        this.form = this.form2Render(res.extraInfo)
        if (this.form.refund_strategy && this.form.refund_strategy.type === 'TIME_RATE') {
          this.timeRateList = this.form.refund_strategy.contents.map(item => {
            const timeEffect = item.seconds > 0 ? '+' : '-'
            const obj = this.formatTime(Math.abs(item.seconds))
            return {
              timeEffect: timeEffect,
              timeNum: obj.timeNum,
              timeType: obj.timeType,
              rate: item.rate
            }
          }).reverse()
        }
        if (res.extraInfo.card_pic) {
          this.fileList = [{
            uid: '0',
            name: '图0',
            url: res.extraInfo.card_pic,
            thumbUrl: res.extraInfo.card_pic,
            percent: 100
          }]
        } else {
          this.fileList = []
        }
      })
    },
    // 获取门票景点
    getTicketScenic () {
      return getTicketScenic(this.id).then(res => {
        const scenicList = res.extraInfo.list.filter(s => {
          return this.scenicList.find(i => {
            return i.id === s.id
          })
        })
        this.bindScenic = scenicList.map(i => i.id)
      })
    },
    // 获取门票渠道
    getTicketChannel () {
      return getTicketChannel(this.id).then(res => {
        this.bindChannel = res.extraInfo.list.map(i => i.id)
      })
    },
    handleOk (e) {
      e.preventDefault()
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.book_max < this.form.book_min) {
            this.$message.error('最小起订数不能大于最大限订数')
            return
          }
          if (this.form.refund_strategy && this.form.refund_strategy.type === 'TIME_RATE') {
            this.form.refund_strategy.contents = this.timeRateList.map(item => {
              const seconds = item.timeEffect + item.timeNum * this.calculateTime(item.timeType)
              const rate = item.rate
              return {
                seconds,
                rate
              }
            })
          }
          const params = this.render2Form(this.form)
          params.limit_identities = this.limitIdentities

          params.card_pic = (this.fileList[0] && this.fileList[0].url) || ''
          if (this.modalType === 'edit') {
            setTicketTypeById(this.form.id, params).then(res => {
              this.$message.success('操作成功')
              this.$emit('update')

              this.handleScenicChange()
              this.handleChannelChange()
              this.handleCancel()
            })
          } else {
            params.type = 'MEMBER'
            addTicketType(params).then(res => {
              this.$message.success('添加成功')
              this.$emit('update')

              this.id = res.extraInfo
              this.handleScenicChange()
              this.handleChannelChange()
              this.handleCancel()
            })
          }
        }
      })
    },
    handleScenicChange () {
      const params = {
        scenics: this.bindScenic.length > 0 ? this.bindScenic : null
      }
      setTicketScenic(this.id, params).then(res => {
        this.$message.success('绑定修改成功')
      })
    },
    handleChannelChange () {
      const params = {
        channels: this.bindChannel.length > 0 ? this.bindChannel : null
      }
      setTicketChannel(this.id, params).then(res => {
        this.$message.success('绑定修改成功')
      })
    },
    handleImageChange (info) {
      const fileList = info.fileList
      // console.error(info.file)
      // if (info.file.status === 'uploading') {
      //   var reader = new FileReader() // 实例化文件读取对象
      //   reader.readAsDataURL(info.file.originFileObj) // 将文件读取为 DataURL,也就是base64编码
      //   reader.onload = (ev) => { // 文件读取成功完成时触发
      //     var dataURL = ev.target.result // 获得文件读取成功后的DataURL,也就是base64编码

      //     this.$refs.cropper.show({
      //       img: dataURL
      //     })
      //   }
      //   return
      // }

      // if (!info.file.status) {
      //   const index = fileList.findIndex(item => {
      //     return item.uid === info.file.uid
      //   })
      //   fileList.splice(index, 1)
      // }
      this.fileList = fileList
    },
    beforeImageUpload (file) {
      const isImage = file.type.indexOf('image') > -1
      if (!isImage) {
        this.$message.error('请选择图片格式的文件')
        return
      }

      var reader = new FileReader() // 实例化文件读取对象
      reader.readAsDataURL(file) // 将文件读取为 DataURL,也就是base64编码
      reader.onload = (ev) => { // 文件读取成功完成时触发
        var dataURL = ev.target.result // 获得文件读取成功后的DataURL,也就是base64编码

        this.$refs.cropper.show({
          img: dataURL
        })
      }
      return false
    },
    handleCropper (i) {
      const index = this.fileList.length

      this.fileList = [{
        uid: index + '',
        name: '图' + index,
        url: i.link,
        thumbUrl: i.link,
        size: i.size,
        percent: 100
      }]
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange (e) {
      if (e === 'days') {
        this.form.use_valid_days = 1 // 默认值
      }
    },
    handleInputConfirm (prop) {
      const inputValue = this[prop].inputValue
      if (inputValue) {
        if (this[prop].indexOf(inputValue) < 0) {
          this[prop].push(inputValue)
        } else {
          this.$message.error('已重复')
        }
      }
      this[prop].inputVisible = false
      this[prop].inputValue = ''
    },
    showInput (prop) {
      this.$set(this[prop], 'inputVisible', true)

      this.$nextTick(_ => {
        this.$refs[`${prop}Input`].$refs.input.focus()
      })
    },
    handleClose (tag, prop) {
      this[prop].splice(this[prop].indexOf(tag), 1)
    },
    calculateTime (e) {
      switch (e) {
        case 'minute':
          return 60
        case 'hour':
          return 60 * 60
        case 'day':
          return 60 * 60 * 24
        case 'week':
          return 60 * 60 * 24 * 7
        case 'month':
          return 60 * 60 * 24 * 30
        default:
          return 0
      }
    },
    formatTime (e) {
      switch (true) {
        case (e === 0):
          return {
            timeNum: e,
            timeType: 'minute'
          }
        case (e % (60 * 60 * 24 * 30) === 0):
          return {
            timeNum: e / (60 * 60 * 24 * 30),
            timeType: 'month'
          }
        case (e % (60 * 60 * 24 * 7) === 0):
          return {
            timeNum: e / (60 * 60 * 24 * 7),
            timeType: 'week'
          }
        case (e % (60 * 60 * 24) === 0):
          return {
            timeNum: e / (60 * 60 * 24),
            timeType: 'day'
          }
        case (e % (60 * 60) === 0):
          return {
            timeNum: e / (60 * 60),
            timeType: 'hour'
          }
        case (e % 60 === 0):
          return {
            timeNum: e / 60,
            timeType: 'minute'
          }
        default:
          return 0
      }
    }
  }
}
</script>

<style scoped>
.ant-form-item{
  width: 50%; display: inline-block;
}
</style>
