<!--
 记上课
 claId: 记上课班级
 diffNowDay: 排课记上课 可记间隔今天几天的排课
 appointClaTime: 选定排课 记上课
 appointCourseTimeId: 选定排课的 编号
 -->
<template>
  <el-dialog title="记上课（记录实际上课信息）" :visible.sync="open" class="compact" width="850px">
    <el-row v-loading="loadingClaDetail" class="cla-detail">
      <div class="cla-base-info" style="border-bottom-width: 2px;">
        <div class="item">
          <div class="item-name">校区:</div>
          <div class="item-value">{{ claTimeInfo.deptName }}</div>
        </div>
        <div class="item">
          <div class="item-name">所属课程:</div>
          <div class="item-value">{{ claTimeInfo.courseName }}</div>
        </div>

        <div class="item">
          <div class="item-name required">上课教练:</div>
          <div class="item-value">
            <staff-select v-model="form.teacherId" :dept-id="claInfo.departId"  placeholder="请选择上课教练" />
          </div>
        </div>
        <div class="item">
          <div class="item-name required">上课教室:</div>
          <div class="item-value">
            <room-select v-model="form.roomId" :dept-id="claInfo.departId" placeholder="请选择上课教室" />
          </div>
        </div>
        <div class="item">
          <div class="item-name required">上课日期:</div>
          <div class="item-value">
            <el-date-picker
              v-model="form.realClaDate"
              clearable
              size="small"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="上课日期"
              style="width: 135px;"
              :picker-options="beginDatePickerOptions"
            />
          </div>
        </div>
        <div class="item">
          <div class="item-name required">
            <span>上课时间:</span>
          </div>
          <div class="item-value">
            <el-time-select
              v-model="form.realStartTime"
              size="small"
              :picker-options="{
                start: '08:00',
                step: '00:01',
                end: '20:00'
              }"
              style="width: 135px;"
              placeholder="上课时间"
            />
          </div>
        </div>
        <div class="item">
          <div class="item-name required">
            <span>下课时间:</span>
          </div>
          <div class="item-value">
            <el-time-select
              v-model="form.realEndTime"
              size="small"
              :picker-options="{
               start: '08:00',
                step: '00:01',
                end: '20:00'
              }"
              style="width: 135px;"
              placeholder="下课时间"
            />
          </div>
        </div>
        <div class="item">
          <div class="item-name required">上课主题:</div>
          <div class="item-value">
            <el-input v-model="form.classTheme" size="small" placeholder="输入上课主题" />
          </div>
        </div>
        <div class="item">
          <div class="item-name required">
            <span>备注:</span>
          </div>
          <div class="item-value">
            <el-input v-model="form.memo" size="small" placeholder="备注" />
          </div>
        </div>
        <span style="color: #999; font-size: 12px; "> * 操作顺序： 先为会员签到，然后再上课；（上完的课程无法再为会员签到！）</span>

      </div>

    </el-row>
    <el-row :gutter="10" class="mb8" style="margin-top: 10px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-collection"
          size="mini"
          @click="handleAutoDealStudentAttendStatusInfo()"
        >签到</el-button>
      </el-col>
      <span style="color: #999; font-size: 12px; "> * 说明：会员签到的同时系统自动划扣会员卡内次数或金额 ；</span>
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      class="add-cla-time-attend-table"
      :height="500"
      :data="claStudentList"
      border
      :header-cell-style="{'text-align': 'center'}"
      :cell-style="{'text-align': 'center'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="studentName" label="会员" fixed="left" />
      <el-table-column align="center" prop="sex" label="性别" :formatter="sexFormatter" width="50"/>
      <el-table-column align="center" prop="phone" label="联系电话" width="110"/>
      <el-table-column align="center" prop="bookStatus" label="预约状态" :formatter="bookStatusFormatter" width="80" />
      <el-table-column align="center" prop="checkIn" label="是否签到" width="190" >
        <template slot-scope="scope">
          <el-radio-group v-model="scope.row.checkIn" >
            <el-radio  :label="0">未签到</el-radio>
            <el-radio  :label="1">已签到</el-radio>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="cardNo" label="会员卡号" width="100" />
      <el-table-column align="center" prop="cardTypeName" label="卡项名称" width="100" />
      <el-table-column align="center" prop="remainingCount" label="会员卡余次" width="90" />
      <el-table-column align="center" prop="remainingTotalFee" label="会员卡余额" width="90" />
      <el-table-column align="center" prop="expiryDate" label="会员卡到期日" width="100" />
      <el-table-column align="center" prop="chargeType" label="收费方式">
        <template slot-scope="scope">
          <span>{{ chargeTypeFormatter(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="deductCnt" label="划扣次数" width="80" />
      <el-table-column align="center" prop="deductFee" label="划扣金额" width="80" />

      <el-table-column align="center" prop="createTime" label="预约时间" width="100" />
      <el-table-column align="center" prop="checkInTime" label="签到时间" width="100" />
      <el-table-column align="center" prop="countBefore" label="划扣前次数" width="90" >
        <template slot-scope="scope">
          <span>{{ scope.row.countBefore==null?'-':scope.row.countBefore}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="countAfter" label="划扣后次数" width="90" >
        <template slot-scope="scope">
          <span>{{ scope.row.countAfter==null?'-':scope.row.countAfter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="feeBefore" label="划扣前金额" width="90" >
        <template slot-scope="scope">
          <span>{{ scope.row.feeBefore==null?'-':scope.row.feeBefore}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="feeAfter" label="划扣后金额" width="90" >
        <template slot-scope="scope">
          <span>{{ scope.row.feeAfter==null?'-':scope.row.feeAfter}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="claStudentList.length > 0" :loading="loading" type="primary" @click="handleClaAttend">上课</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { selectDictLabel } from '@/utils/commonUtils'
import staffSelect from '@/components/system/staff/staffSelect'
import claTimeSelect from '@/components/sc/claTime/claTimeSelect'
import roomSelect from '@/components/sc/base/roomSelect'
import claSelect from '@/components/sc/course/cla/claSelect'
import deptSelect from '@/components/system/dept/deptSelect'
import moment from 'moment'
import {claTimeInfo as loadClaTimeInfo,confirmCla,searchCourseClaStudent} from "@/api/school/sc/cla/claTime";
import memberCardApi from "@/api/school/sc/memberCard";
export default {
  components: {
    staffSelect,
    claTimeSelect,
    roomSelect,
    claSelect,
    deptSelect
  },
  props: {
    // 班级
    claId: {
      type: String,
      default: undefined
    },
    // 排课记上课 可记间隔今天几天的排课
    diffNowDay: {
      type: Number,
      default: 0
    },
    // 选定排课 记上课
    appointClaTime: {
      type: Boolean,
      default: false
    },
    // 选定排课 记上课 的 编号
    appointCourseTimeId: {
      type: String,
      default: undefined
    },
  },
  data() {
    return {
      title: '记上课',
      open: false,
      loading: false,
      loadingClaDetail: false,
      // 班级信息
      claInfo: {},
      // 课程信息
      claCourseInfo: {},
      // 排课信息
      claTimeInfo: {},
      form: {

        deptId: undefined,
        claId: undefined,
        realClaDate: '',
        realStartTime: '',
        realEndTime: '',
        teacherId: undefined,
        roomId: undefined,
        classTheme: undefined,
        memo:""

      },
      // 自定义上课可选日期
      beginDatePickerOptions: {
        disabledDate(time) {
          return moment(time).add(0, 'days').valueOf() > Date.now()
        }
      },
      dataList: [],
      claStudentList: [],
      chargeTypeOptions: [],
      sexOptions: [],
      // 选择上课的会员
      chooseStudentCourseIds: [],
      // 每个会员 的到课状态
      studentAttendStatusForm: {},

      // 选择的校区
      chooseDeptId: undefined,
      chooseBookIds:[]
    }
  },
  computed: {
  },
  watch: {
    open: {
      handler(newValue) {
        if (newValue === true) {
          this.resetData()
          this.loadClaInfo()
        }
      },
      immediate: true
    },
  },
  created() {
    this.getDictListByDictType('charge_type').then(response => {
      this.chargeTypeOptions = response.data
    })
    this.getDictListByDictType('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getDictListByDictType('book_status').then(response => {
      this.bookStatusOptions = response.data
    })
  },
  methods: {
    resetData() {
      this.claInfo = {
        claName: '',
        deptName: '',
        departId: undefined
      }
      this.claCourseInfo = {
        courseName: ''
      }
      this.dataList = []

    },
    loadClaInfo() {
        this.loadingClaDetail = true
        loadClaTimeInfo(this.appointCourseTimeId).then(response => {
          this.claTimeInfo = response.data
          // 自动设置表单信息
          this.autoSetFormByClaTimeInfo()
          this.loadingClaDetail = false
        })

      this.getList()
    },
    // 自动设置 表单信息
    autoSetFormByClaTimeInfo() {
      this.form.teacherId = this.claTimeInfo.teacherId
      this.form.roomId = this.claTimeInfo.roomId
      this.form.realClaDate = this.claTimeInfo.claDate
      this.form.realStartTime = this.claTimeInfo.startTime.substr(0, 5)
      this.form.realEndTime = this.claTimeInfo.endTime.substr(0, 5)
      this.form.memo = this.claTimeInfo.memo
      this.form.classTheme = this.claTimeInfo.classTheme
      this.form.courseTimeId=this.appointCourseTimeId
    },
    // 选择计划排课日期变化
    handleClaDateChange(claTimeInfo) {
      this.claTimeInfo = claTimeInfo
      this.form.realStartTime = claTimeInfo.startTime.substr(0, 5)
      this.form.realEndTime = claTimeInfo.endTime.substr(0, 5)
      this.form.classTheme = claTimeInfo.classTheme
      // 如果是指定排课
      if (this.appointClaTime) {
        this.chooseClaId = claTimeInfo.claId
        // 加载班级 课程信息
        this.loadClaInfo()
      }
    },
    sexFormatter(row, column) {
      return selectDictLabel(this.sexOptions, row.sex)
    },
    chargeTypeFormatter(row, column) {
      return selectDictLabel(this.chargeTypeOptions, row.chargeType)
    },
    bookStatusFormatter(row, column) {
      return selectDictLabel(this.bookStatusOptions, row.bookStatus)
    },
    getList() {
      this.loading = true
      let claStudentList = []
      searchCourseClaStudent({courseTimeId: this.appointCourseTimeId}).then(response => {
        claStudentList = response.data
        this.total = response.data.total
        this.claStudentList = claStudentList
        this.loading = false
      })
      this.loading = false
    },

    // 签到
    handleAutoDealStudentAttendStatusInfo() {
      this.$nextTick(() => {
        this.claStudentList.forEach(row => {
          if ([0,1,2].includes(row.bookStatus)&&row.checkIn==0){
            //会员卡是否到期expiryDateb  yyyy-MM-dd
            if (row.expiryDate){
              // 1. 转换输入日期为Date对象（注意：yyyy-MM-dd格式直接传入会默认按UTC时区解析，需处理为本地时区）
              const [year, month, day] = row.expiryDate.split('-').map(Number);
              // 月份是0开始的（0=1月，11=12月），所以要减1
              const expiryDate1 = new Date(year, month - 1, day);

              // 2. 获取今天的日期（仅保留年月日，重置时分秒为0）
              const today = new Date();
              const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());

              // 3. 比较时间戳（毫秒数）
              if (expiryDate1.getTime() < todayStart.getTime()){
                this.msgError('会员：'+row.studentName+'的会员卡已过期，无法使用！')
                return ;
              }
            }
            // 余额是否足够 remainingCount deductCnt remainingTotalFee deductFee
            if (row.chargeType=='count'&&row.remainingCount<row.deductCnt){
              this.msgError('会员：'+row.studentName+'的会员卡余次不足，无法使用！')
              return ;
            }
            if (row.chargeType=='total_fee'&&row.remainingTotalFee<row.deductFee){
              this.msgError('会员：'+row.studentName+'的会员卡余额不足，无法使用！')
              return ;
            }
            this.chooseBookIds.push(row.bookId)
            this.$refs.table.toggleRowSelection(row, true)
          }
        })
        if (this.chooseBookIds==null || this.chooseBookIds.length<1){
          this.msgError('没有可以满足签到条件的会员！')
          this.$refs.table.clearSelection();
          return ;
        }
        //批量签到 this.chooseBookIds
        memberCardApi.checkIn({bookIds:this.chooseBookIds}).then(response => {
          if (response.success){
            this.msgSuccess('签到成功')
            this.getList()
          }else {
            this.msgError(response.respMsg)
          }
          this.loading = false

        }).catch(() => {
          this.loading = false
        })
      })


    },
    // 上课/修改
    handleClaAttend() {
      console.log('上课')
        // 自定义上课
        if (this.form.teacherId === undefined || this.form.teacherId === '' || this.form.teacherId === null) {
          this.msgError('请选择上课教练')
          return
        } else if (this.form.realClaDate === undefined || this.form.realClaDate === '' || this.form.realClaDate === null) {
          this.msgError('请选择上课日期')
          return
        } else if (this.form.realStartTime === undefined || this.form.realStartTime === '' || this.form.realStartTime === null) {
          this.msgError('请选择上课时间')
          return
        } else if (this.form.realEndTime === undefined || this.form.realEndTime === '' || this.form.realEndTime === null) {
          this.msgError('请选择下课时间')
          return
        }
        if (this.form.courseTimeId === undefined || this.form.courseTimeId === '' || this.form.courseTimeId === null) {
          this.msgError('页面数据错误，请刷新重试！')
          return
        }
      const studentAttendList = []


      this.form.claId = this.claId
      this.loading = true
      confirmCla(this.form).then(response => {
        this.loading = false
        if (response.respCode === '0000') {
          this.$emit('success')
          this.open = false
          this.msgSuccess('记上课成功')
        } else {
          this.msgError(response.msgDetail)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleSelectionChange(selection) {
      this.chooseStudentCourseIds = selection.map(item => item.studentCourseId)
    },
    handleAttendStatusChange(attendStatus, row) {
      if (row.chargeType !== 'date') {
        if (attendStatus === '2') {
          this.studentAttendStatusForm[row.studentCourseId].stuLoseHour = 0
          this.studentAttendStatusForm[row.studentCourseId].disable = true
        } else {
          this.studentAttendStatusForm[row.studentCourseId].stuLoseHour = this.form.attendType === 'rule' ? this.claTimeInfo.payHour : this.claInfo.everyStuLoseHour
          this.studentAttendStatusForm[row.studentCourseId].disable = false
        }
      }
    },
  }
}
</script>
<style lang="scss" scoped src="@/styles/sc/cla/cla-detail.scss"></style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .cla-detail .cla-base-info .item .item-name{
    width: 90px;
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  .add-cla-time-attend-table .el-radio-button--mini .el-radio-button__inner {
    padding: 7px;
  }
</style>
