<template>
  <div>
    <xy-dialog ref="dialog" :width="60" @reset="resetForm" :is-show.sync="isShow" :type="'form'" :title="typeName"
      :form="form" @submit="submit" :rules='rules' :okText="type==='editor'?'确定':'预约并通过'">

      <template v-slot:course_id v-if="type==='more'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>班级(课程)：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.course_id" @change="changeCourse" style="width:100%" placeholder="可选择课程获取学员">
              <el-option v-for="item in course_options" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:user_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>{{type==='more'?'无需预约人':'预约人'}}：
          </div>
          <div class="xy-table-item-content">
            <div v-if="type==='editor'">
              {{form.name}}
            </div>
            <el-select v-else v-model="form.user_id" @change="changeUser" style="width:100%"
              :multiple="type==='more'?true:false" filterable remote reserve-keyword
               :placeholder="type==='more'?'请选择无需预约的学员，不选则全部预约':'请选择学员或查找学员'"
              :remote-method="remoteMethod" :loading="loading">
              <el-option v-for="item in user_options" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:name v-if="type==='add'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>非学员预约：
          </div>
          <div class="xy-table-item-content">
            <el-input @change="changeInput" v-model="form.name" placeholder="请输入预约人姓名"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:mobile v-if="type==='add'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>联系方式：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.mobile" placeholder="请输入预约人联系方式"></el-input>
          </div>
        </div>
      </template>
     <!-- <template v-slot:date>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>预约日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker v-model="form.date" type="date" style="width:100%" placeholder="预约日期"
              value-format="yyyy-MM-dd" format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </div>
      </template> -->
      <template v-slot:timeRange>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>预约时间：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker type="datetimerange" @change="changeTimeRange" v-model="form.timeRange" style="width:100%" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:site>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>预约场地：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.site" placeholder="请选择预约场地" clearable style="width:100%">
              <el-option v-for="item in site_options" :key="item.id" :label="item.real_name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:content v-if="type==='add'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>预约事项：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.content" placeholder="请输入预约事项" clearable style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:plate>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>车牌：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.plate" placeholder="请输入车牌,多个车牌中间以英文,分隔" clearable style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:accompany_total v-if="type==='add'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>同行人数：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.accompany_total" type="number" placeholder="请输入同行人数" clearable
              style="width: 100%;"></el-input>
          </div>
        </div>
      </template>

      <!-- <template v-slot:footerContent>
        <Button type="primary" @click="submit">预约并通过</Button>
        <Button type="primary" @click="isShow = false">取消</Button>
      </template> -->
    </xy-dialog>

  </div>
</template>

<script>
  import myMixins from "@/mixin/selectMixin.js";
  import {
    show,
    save
  } from "@/api/book/index.js"
  import {
    indexStudy
  } from '@/api/student/index.js'
  import {
    index as courseIndex
  } from "@/api/course/index.js"
  import {
    index as getAppointment
  } from "@/api/book/appointment.js"
  export default {
    mixins: [myMixins],
    components: {

    },
    data() {
      return {
        isShow: false,
        type: 'add',
        typeName: '手动预约',
        id: '',
        form: {
          course_id: '',
          user_id: '',
          name: '',
          mobile: '',
          date: '',
          timeRange: '',
          start_time: '',
          end_time: '',
          content: '',
          site: '',
          plate: '',
          accompany_total: 0,
          status: 1,
          reason: ''
        },
        loading: false,
        user_options: [],
        site_options: [],
        course_options: [],
        rules: {
          // user_id: [{
          //   required: true,
          //   message: '请选择预约人'
          // }],
          // date: [{
          //   required: true,
          //   message: '请选择预约日期'
          // }],
          mobile: [{
            required: true,
            message: '请输入联系方式'
          }],
          timeRange: [{
            required: true,
            message: '请选择时间段'
          }],
          site: [{
            required: true,
            message: '请选择预约场地'
          }],
        }
      }
    },
    created() {
      this.getCourseList()
      this.getUserList('')
      this.getSites()
    },
    methods: {
      changeTimeRange(e){
        console.log(e)
        if(e){
          this.form.start_time = e[0]
          this.form.end_time = e[1]
          this.form.date = this.formatDate(e[0])
          console.log(this.form.date,this.form.start_time,this.form.end_time)
        }else{
          this.form.start_time = ''
          this.form.end_time = ''
          this.form.date = ''
          this.form.timeRange = ''
        }
      },
      compareTime(startTime) {
        let date1 = this.$moment()
        let sign1 = this.$moment(startTime)
        return sign1.isBefore(date1)
      },
      submit(status) {
        this.form.status = 1

        console.log(this.form)
        if(this.compareTime(this.form.start_time)){
          this.$Message.warning('预约开始时间不能早于当前时间')
          return
        }
        if (this.type === 'add') {
          if (this.base.isNull(this.form.user_id) && this.base.isNull(this.form.name)) {
            this.$Message.warning('请选择学员或输入预约人姓名')
            return
          }
        }
        if (this.type === 'more') {
          let _arr = []
          if (this.base.isNull(this.form.user_id)) {
            this.user_options.map(item => {
              _arr.push(item.id)
            })
          } else {
            _arr = this.user_options.filter(item => !this.form.user_id.includes(item.id))
            _arr = _arr.map(item => item.id)
          }
          console.log("_arr", _arr)
          if(_arr.length===0){
            this.$Message.warning('当前没有筛选出学员')
            return
          }
          this.form.user_id = _arr.join(",")
        }
        if (this.type === "editor") {
          this.form.status = 0
        }
        save(this.form).then(res => {
          if (res.success < res.total) {
            this.$Message.warning(res.err.join("。"))
          } else {
            this.$message({
              type: 'success',
              message: '预约成功'
            })
          }
          this.isShow = false
          this.$emit('refresh')
        })
      },

      getDetail() {
        show({
          id: this.id,
          show_relation: ['user', 'appointmentConfig']
        }).then(res => {
          this.form = this.base.requestToForm(res, this.form)
          this.form.status = res.status ? res.status : 0
          this.form.site = res.site?parseInt(res.site):''
          this.form.timeRange = [res.start_time, res.end_time]
        })
      },
      formatHH(val) {
        if (val) {
          return this.$moment(val).format("HH:mm:ss")
        } else {
          return ''
        }
      },
      formatDate(val) {
        if (val) {
          return this.$moment(val).format("YYYY-MM-DD")
        } else {
          return ''
        }
      },
      changeUser(e) {
        if (e) {
          this.form.user_id = e
          if (this.type === "add") {
            this.user_options.map(item => {
              if (item.id === e) {
                this.form.mobile = item.mobile
                this.form.name = item.name
              }
            })
          }
        }
        console.log(this.form.user_id, this.form.name)
      },
      changeInput(e) {
        console.log("input", e)
        if(e){
          this.form.name = e
          this.form.user_id = 0
        }
         console.log(this.form.user_id, this.form.name)
      },
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.getUserList(query)
        } else {
          this.user_options = [];
        }
      },
      async getUserList(query) {
        const res = await indexStudy({
          page: 1,
          page_size: 99,
          name: query,
          course_id: this.form.course_id,
        })
        this.user_options = res.list.data
        if(this.user_options.length===0){
          this.$Message.warning("当前搜索没有学员")
        }
        this.loading = false
      },
      async getSites() {
        const res = await getAppointment({
          page: 1,
          page_size: 999,
          // filter: [{
          //   key: 'status',
          //   op: 'eq',
          //   value: 1
          // }]
        })
        this.site_options = res.data
      },
      changeCourse(e) {
        if (e) {
          this.form.course_id = e
          this.getUserList('')
        } else {
          this.form.course_id = ''
          this.getUserList('')
        }
      },
      async getCourseList() {
        const res = await courseIndex({
          page: 1,
          page_size: 9999
        })
        this.course_options = res.data
      },
      resetForm() {
        this.form.timeRange = ""
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
            this.typeName = '编辑'
          } else if (this.type === 'more') {
            this.typeName = '批量预约'
          } else {
            this.typeName = '手动预约'
          }
        } else {
          this.id = ''
          this.type = "add"
          this.typeName = '手动预约'
          this.course_id = ''
          this.$refs['dialog'].reset()
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  .bookInfo {
    &>div {
      span {
        display: inline-block;
      }

      span:first-child {
        width: 20%;
        text-align: right;
      }

      span:last-child {
        width: 80%;
        text-align: left;
      }
    }
  }
</style>
