<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">
            <span v-if="type==='editor'">
              {{form.name}}
            </span>
            <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!='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-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="siteData" @change="changeSite" multiple collapse-tags placeholder="请选择预约场地" clearable style="width:100%">
              <el-option v-for="item in site_options" :key="item.id" :label="item.show_name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:content 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-input v-model="form.content" placeholder="请输入预约事项" clearable style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:plate  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-input v-model="form.plate" placeholder="请输入车牌,多个车牌中间以英文,分隔" clearable style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:accompany_total 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-input v-model="form.accompany_total" :disabled="type==='editor'" type="number" placeholder="请输入同行人数" clearable
              style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:accompany v-if="type!='more'">
        <div>
          陪同人：<Button v-if="type==='add'" type="primary" @click="accompanyList.push({name:'',mobile:''})">新增</Button>
        </div>
        <div>
          <xy-table style="width:800px;max-width:800px;height:300px" :list="accompanyList" :isPage="false" :table-item="accompany_item">
            <template v-slot:name>
              <el-table-column align='center' label="姓名"  width="300" header-align="center">
                <template slot-scope="scope">
                  <el-input :disabled="type==='editor'" v-model="scope.row.name"></el-input>
                </template>
              </el-table-column>
            </template>
            <template v-slot:mobile>
              <el-table-column align='center' label="联系方式" width="300" header-align="center">
                <template slot-scope="scope">
                  <el-input :disabled="type==='editor'" v-model="scope.row.mobile"></el-input>
                </template>
              </el-table-column>
            </template>
            <template v-slot:btns>
              <el-table-column align='center' label="操作" width="200" header-align="center">
                <template slot-scope="scope">
                  <el-popconfirm v-if="type==='add'" style="margin-left:10px" @confirm="accompanyList.splice(scope.$index,1)" title="确定删除吗？">
                    <el-button type="danger" size="small" slot="reference">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </template>
          </xy-table>
        </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: '',
        siteData:[],
        accompanyList:[],
        accompany_item:[{
          prop:'name',
          label: '姓名',
        },{
          prop:'mobile',
          label: '联系方式',
        }],
        form: {
          course_id: '',
          user_id: '',
          name: '',
          mobile: '',
          date: '',
          timeRange: '',
          start_time: '',
          end_time: '',
          content: '',
          site: '',
          plate: '',
          accompany_total: 0,
          accompany:[],
          status: 1,
          reason: ''
        },
        loading: false,
        allUser:[],
        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 = ''
        }
      },
      changeSite(e){
        console.log("eqwe",e)
        if(e.length>0){
          this.form.site = e.join(",")
        }else{
          this.form.site = ''
        }
      },
      compareTime(startTime) {
        let date1 = this.$moment()
        let sign1 = this.$moment(startTime)
        return sign1.isBefore(date1)
      },
      submit(status) {
        this.form.status = 1
        if(this.compareTime(this.form.start_time)){
          this.$Message.warning('预约开始时间不能早于当前时间')
          return
        }
        if (this.type === 'more') {
          console.log("this.form.user_id",this.form.user_id)
          let _arr = []
          if (this.base.isNull(this.form.user_id)) {
            this.allUser.map(item => {
              _arr.push(item.id)
            })
          } else {
            let _filterarr = this.allUser.filter(item => !this.form.user_id.includes(item.id))
            console.log("_filterarr",_filterarr)
            _filterarr.map(item => {
              _arr.push(item.id)
            })
          }
          console.log("_arr", _arr)
          if(_arr.length===0){
            this.$Message.warning('当前没有筛选出学员')
            return
          }
          this.form.user_id = _arr.join(",")
        }

        if (this.type === 'add') {
          if (this.base.isNull(this.form.user_id) && this.base.isNull(this.form.name)) {
            this.$Message.warning('请选择学员或输入预约人姓名')
            return
          }

        }

        // return
        if (this.type === "editor") {
          this.form.status = 0
        }
        console.log("accompanyList",this.accompanyList)
        if(this.type==='add' || this.type==='editor'){
          if(this.accompanyList.length>0){
            var nullCount = 0
            var errMobile = 0
            this.form.accompany_total = this.accompanyList.length
            this.accompanyList.map(item=>{
              if(this.base.isNull(item.name) || this.base.isNull(item.mobile)){
                nullCount++
              }
              if(!this.base.isNull(item.mobile) && !this.base.isPhone(item.mobile)){
                errMobile++
              }
            })
            console.log("nullCount",nullCount,errMobile)
            if(nullCount>0){
              this.$Message.warning("陪同人姓名或联系方式不能为空")
              return
            }
            if(errMobile>0){
              this.$Message.warning("陪同人联系方式不正确")
              return
            }
            this.form.accompany = this.accompanyList
          }else{
            this.form.accompany = []
            this.form.accompany_total = 0
          }
        }
        // return
        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']
        }).then(res => {
          this.form = this.base.requestToForm(res, this.form)
          this.form.status = res.status ? res.status : 0
          let _arr = res.site?res.site.split(","):[]
          _arr.map(item=>{
            this.siteData.push(parseInt(item))
          })
          this.form.timeRange = [res.start_time, res.end_time]
          this.accompanyList = res.appointment_accompany
        })
      },
      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.remoteUserList(query)
        }
      },
      async remoteUserList(query) {
        const res = await indexStudy({
          page: 1,
          page_size: 300,
          name: query,
          course_id: this.form.course_id,
          status:1
        })
        this.user_options = res.list.data
        if(res.list.data===0){
          this.$Message.warning("当前搜索没有学员")
        }
        this.loading = false
      },
      async getUserList(query) {
        const res = await indexStudy({
          page: 1,
          page_size: 300,
          name: query,
          course_id: this.form.course_id,
          status:1
        })
        this.user_options = res.list.data
        this.allUser = 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
          }]
        })
        res.data.map(item=>{
          item.show_name = item.content?`${item.real_name}(${item.content})`:item.real_name
        })
        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.siteData = []
          this.accompanyList = []
          this.form = {
            course_id: '',
            user_id: '',
            name: '',
            mobile: '',
            date: '',
            timeRange: '',
            start_time: '',
            end_time: '',
            content: '',
            site: '',
            plate: '',
            accompany_total: 0,
            accompany:[],
            status: 1,
            reason: ''
          }
          this.$refs['dialog'].reset()
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .accompany{
    flex-basis: 100%;
    padding:0 60px;
  }
  .bookInfo {
    &>div {
      span {
        display: inline-block;
      }

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

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