<template>
  <div>
    <el-dialog :title="exData.id ? '编辑': '新增'"
               :visible.sync="dialog"
               width="600px"
               :close-on-click-modal="false"
               top="50px">
      <el-form ref="form"
               :model="form"
               :rules="formRules"
               label-width="160px">
        <el-form-item prop="place_time"
                      :rules="formRules.time"
                      label="开放预定日期：">
          <el-date-picker
            style="width: 100%"
            v-model="form.place_time"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="place_name"
                      :rules="formRules.required"
                      label="座位名称：">
          <el-input v-model="form.place_name"
                    placeholder="请输入座位名称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item prop="place_desc"
                      :rules="formRules.required"
                      label="说明：">
          <el-input type="textarea"
                    :rows="4"
                    placeholder="请输入座位说明"
                    v-model="form.place_desc">
          </el-input>
        </el-form-item>
        <el-form-item prop="place_user_max"
                      :rules="formRules.InterNum"
                      label="单桌人数：">
          <el-input v-model="form.place_user_max"
                    placeholder="请输入人数"
                    @input="form.place_user_max=form.place_user_max.replace(/[^\d]/g, '').replace(/^0*/, '')"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="预定方式:" required>
          <el-select v-model="form.place_pre_type">
            <el-option label="整桌预定" :value="0"></el-option>
            <el-option label="座位预定" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="place_price"
                      :rules="formRules.numPot2"
                      label="单价(元)：">
          <el-input v-model="form.place_price"
                    placeholder="请输入单价"
                    @input="form.place_price=form.place_price.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                    clearable></el-input>
        </el-form-item>
        <el-form-item prop="place_latest_time"
                      :rules="formRules.required"
                      label="最晚到店时间：">
          <el-time-select style="width: 100%"
                          placeholder="请选择最晚到店时间"
                          v-model="form.place_latest_time"
                          :picker-options="{start: '00:00', step: '00:05', end: '23:59'}">
          </el-time-select>
        </el-form-item>
        <el-form-item prop="place_max_time"
                      :rules="formRules.checkInterNum"
                      label="最晚保留时间(分钟)：">
          <el-input v-model="form.place_max_time"
                    placeholder="请输入分钟数"
                    @input="form.place_max_time=form.place_max_time.replace(/[^\d]/g, '').replace(/^0*/, '')"
                    clearable></el-input>
        </el-form-item>
        <el-form-item prop="place_pre_num"
                      :rules="form.id !== '' ? [] : formRules.required"
                      label="已预定："
                      v-if="form.id">
          <el-input v-model="form.place_pre_num"
                    disabled
                    placeholder=""
                    clearable></el-input>
        </el-form-item>
        <el-form-item :label="!form.id ? '桌号设置：' : '开放预定数量：'"></el-form-item>
        <el-form-item v-for="(desk, index) in form.place_number"
                      :label="(index + 1) + '桌'"
                      :key="index"
                      :prop="'place_number.' + index + '.value'"
                      :rules="formRules.required">
          <el-input style="width: 75%"
                    v-model="desk.value"
                    placeholder="请设置桌号"></el-input>
          <div style="display: inline-block;width: 25%;text-align: right;">
            <el-button type="warning"
                       :disabled="form.place_number.length <= 1"
                       @click.prevent="removeDeskNum(desk)">删除
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-center">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button @click.prevent="addDomain">新增桌号</el-button>
        <el-button type="primary" :disabled="booLock" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fen2Yuan, yuan2Fen } from '@/utils'

export default {
  components: {},
  props: {
    value: {
      type: Boolean,
      default: true
    },
    exData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    const date = new Date()
    const yyyy = date.getFullYear()
    const MM = (date.getMonth() + 1).toString().padStart(2, '0')
    const dd = (date.getDate()).toString().padStart(2, '0')
    return {
      dialog: !!this.value,
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      form: {
        place_time: yyyy + '-' + MM + '-' + dd, // 年月日, 回传后端时间格式要求2021-05-23
        place_name: '', // 座位名称
        place_desc: '', // 座位描述
        place_user_max: '', // 最多到店人数
        place_pre_type: 0, // 预定方式
        place_price: '', // 座位价格(单位为分)
        place_latest_time: '', // 最晚到店时间，回传后端时间格式要求2021-05-23 21:15:00
        place_max_time: '', // 最晚保留时间
        place_pre_num: 0, // 已预定
        // 座位编号(数组)
        place_number: [
          {
            value: ''
          }
        ]
      },
      booLock: false
    }
  },
  methods: {
    removeDeskNum (item) {
      var index = this.form.place_number.indexOf(item)
      if (this.form.place_number.length <= 1) {
        this.$message.warning('桌数不能小于1')
        return
      }
      if (index !== -1) {
        this.form.place_number.splice(index, 1)
      }
    },
    addDomain () {
      this.form.place_number.push({
        value: ''
      })
    },
    handleSubmit () {
      const url = this.exData.id ? '/v1/bar/place/modify' : '/v1/bar/place/add'
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.booLock = true
          const data = await this.$fetch(url, {
            ...this.form,
            place_latest_time: `${this.form.place_time} ${this.form.place_latest_time}:00`,
            place_price: yuan2Fen(this.form.place_price)
          })
          this.booLock = false
          if (data.code === 200) {
            this.$message.success('提交成功')
            this.$emit('success')
            this.dialog = false
          }
        }
      })
    }
  },
  mounted () {
    if (this.exData.id) {
      this.$set(this.form, 'id', this.exData.id)
      for (const key in this.exData) {
        if (this.form.hasOwnProperty(key)) {
          let value = this.exData[key]
          if ((Array.isArray(value) && value.length >= 1) || (Object.prototype.toString.call(value) === '[object Object]') || (typeof value === 'string' && value) || typeof value === 'number') {
            if (key === 'place_price') {
              value = fen2Yuan(value)
            }
            if (key === 'place_number') {
              value = JSON.parse(value)
            }
            if (key === 'place_latest_time') {
              value = value.replace(/(\d{4}-\d{2}-\d{2}\s*)(\d{2}:\d{2})(\W.*)/, '$2')
            }
            this.$set(this.form, key, value)
          }
        }
      }
    }
  },
  watch: {
    dialog (val) {
      if (!val) this.$emit('input', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.top-tip {
  margin-top: -20px;
  margin-bottom: 20px;
}
</style>
