<template>
  <a-form-model :model="form" :label-col="{span: 4}" :wrapper-col="{span: 18}" ref="ruleForm" :rules="rules">
    <div v-if="type === 'add'" class="mb-3">
      <a-input class="w-80 mr-12" placeholder="请输入请输入管理员或客户经理手机号" v-model="value"></a-input>
      <a-button type="primary" @click="search">搜索</a-button>
    </div>
    <div v-if="(type === 'add' && Object.keys(msg).length > 0) || type === 'edit'">
      <div class="flex justify-between items-center my-4">
        <span class="">名称： {{ msg.user_name || '' }}</span>
        <span>手机号： {{ msg.phone || '' }}</span>
      </div>
      <div class="flex items-center mb-2 mt-6">
        <span class="mr-2 mb-5">开播时间时间段</span>
        <a-form-model-item class="inline-block" label="" prop="day_type">
          <a-select class="mr-2" v-model="form.day_type" default-value="lucy" style="width: 160px" placeholder="请选择时间段" :allowClear="true">
            <a-select-option v-for="item in options" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item class="inline-block mr-2" label="" prop="start">
          <a-time-picker class="w-36" format="HH:mm" valueFormat="HH:mm" v-model="form.start"/>
        </a-form-model-item>
        <span class="inline-block mb-5">-</span>
        <a-form-model-item class="inline-block ml-2" label="" prop="end">
          <a-time-picker class="w-36" format="HH:mm" valueFormat="HH:mm" v-model="form.end"/>
        </a-form-model-item>
      </div>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" @click="onSubmit">确定</a-button>
        <a-button style="margin-left: 10px;" @click="onCancel">取消</a-button>
      </a-form-model-item>
    </div>
  </a-form-model>
</template>

<script lang="ts">
import Vue from 'vue'
import { message, Select, TimePicker } from 'ant-design-vue'
import moment from 'moment'
import { options } from './const'
import StaffService from '@/service/StaffService'
import Live from '@/service/LiveService'
import { staff } from '@/types/staff';

const staff = new StaffService()
const live = new Live()

export default Vue.extend({
  components: {
    'a-select': Select,
    'a-time-picker': TimePicker
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    info: {
      type: Object
    }
  },
  computed: {
    options() {
      return options
    }
  },
  data() {
    const checkStart = (rule: any, value: string, callback: any) => {
      if (!value) {
        return callback(new Error('请选择开始时间'));
      }
      const self = this as any
      const end = self.getTime(self.form.end)
      const start = self.getTime(value)
      if (end < start) {
        message.error('时间选择错误，结束时间不能小于开始时间')
        callback(new Error('请选择正确时间'))
      } else {
        if (self.form.end) {
          (self.$refs.ruleForm as any).validateField('end')
          callback()
        }
      }
    }
    const checkEnd = (rule: any, value: string, callback: any) => {
      if (!value) {
        return callback(new Error('请选择结束时间'));
      }
      const self = this as any
      const end = self.getTime(value)
      const start = self.getTime(self.form.start)
      if (end < start) {
        message.error('时间选择错误，结束时间不能小于开始时间')
        callback(new Error('请选择正确时间'))
      } else {
        if (self.form.start) {
          (self.$refs.ruleForm as any).validateField('start')
          callback()
        }
      }
    }
    const rules = {
      start: [
        { trigger: 'change', required: true, validator: checkStart },
      ],
      end: [
        { trigger: 'change', required: true, validator: checkEnd },
      ],
      day_type: [
        { required: true, message: '请选择开播时段', trigger: 'change' },
      ],
    }
    return {
      rules,
      msg: {} as any,
      form: {
        start: undefined as undefined | number,
        end: undefined as undefined | number,
        day_type: undefined as undefined | number,
        _start: undefined as undefined | number,
        _end: undefined as undefined | number,
      } as any,
      title: '',
      value: '',
      uuid: '',
    }
  },
  methods: {
    moment,
    init() {
      this.msg = {}
      this.form = {
        start: undefined,
        end: undefined,
        day_type: undefined,
        _start: undefined,
        _end: undefined
      }
      this.value = ''
    },
    search() {
      if (!this.value) return
      staff.queryStaff({
        phone: this.value
      }).then(res => {
        const list = res.data.item
        if (list.length === 0) {
          message.error('无此用户')
          return
        }
        this.msg = res.data.item[0]
        this.uuid = this.msg.uuid
      })
    },
    changeHandle(v: string) {

      if (new Date(this.form._end) < new Date(this.form._start)) {
        message.error('请选择正确时间')
      } else {
        message.destroy()
      }
    },
    onSubmit() {
      (this.$refs.ruleForm as any).validate((valid: any) => {
        if (valid) {
          const params = {
            day_type: this.form.day_type,
            time_section: this.form.start + '-' + this.form.end,
            uuid: this.uuid
          }
          // 新增检测用户数量
          if (this.type === 'add') {
            live.addLive().then(res => {
              if (res.code === 200) {
                this.$emit('updated', params)
              } else {
                message.error('当前数量已超过五个，添加失败，请删除后再次添加')
              }
            })
          } else {
            this.$emit('updated', params)
          }
        }
      })
    },
    onCancel() {
      this.$emit('updated', {})
    },
    getTime(v: string) {
      return moment(moment(Date.now()).format('YYYY-MM-DD') + ' ' + v).format('HH:mm')
    },
    setValue() {
      (this.$refs.ruleForm as any).resetFields()
      if (Object.keys(this.info).length > 0) {
        this.msg = this.info
        this.uuid = this.msg.uuid
        const start = this.msg.attr?.time_section.split('-')[0]
        const end = this.msg.attr?.time_section.split('-')[1]
        this.form = {
          start: this.getTime(start),
          end: this.getTime(end),
          day_type: this.msg.attr?.day_type
        }
      }
    }
  },
  mounted() {
    this.setValue()
  },
  watch: {
    show(n) {
      if (n) {
        this.setValue()
      } else {
        this.init()
      }
    }
  }
})
</script>