<template>
  <div>
    <el-dialog title="新设会员卡" :visible.sync="open" width="700px">
      <el-form ref="form" v-loading="loadingChange" :model="form" :rules="rules" label-width="120px">
        <div class="title top" >
          <div class="title-content">会员卡基础信息</div>
          <div style="padding-left: 10px;">
           <span  style="color: #999; font-size: 12px;">
               * 说明：卡项按充值/扣费方式可分为周期卡项、次数卡项、储值卡项，三种方式可同时存在，<br>
               为会员办理会员卡（左侧菜单【办理入会->业务办理->报名】）时，需选择其中一项作为充值/扣费方式；<br>
               1.周期卡：填写【总天数/有效期】后，可作为周期卡项使用<br>
               2.周期卡：填写【总课程次数】后，可作为次数卡项使用<br>
               3.储值卡：所有卡项均可作为储值卡项使用<br>
           </span>
          </div>
        </div>

        <el-row>
          <el-col :span="12">
            <el-form-item label="会员卡名称:" prop="cardName">
              <el-input v-model="form.cardName" placeholder="请输入会员卡名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程类别:" prop="courseTypes">
              <el-checkbox-group v-model="form.courseTypes" @change="changecourseTypes">
                <el-checkbox v-for="(item) in courseTypeOptions" :key="item.id" :label="item.id" name="courseTypes">{{ item.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="10" >
            <el-form-item label="总天数/有效期:" prop="days">
                <el-input v-model="form.days" placeholder="选填" />
            </el-form-item>
          </el-col>
          <el-col :span="14" style="height: 35px;" >
            <div style="margin-top: 10px;margin-left: 2px">
              天 <span style="color: #999; font-size: 12px;">(填写后可作为周期卡项使用，用于开周期卡时自动填写对应时长)</span>
            </div>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="10" >
            <el-form-item label="总课程次数:" prop="count">
              <el-input v-model="form.count" placeholder="选填" />
            </el-form-item>
          </el-col>
          <el-col :span="14" style="height: 35px;" >
            <div style="margin-top: 10px;margin-left: 2px">
              次 <span style="color: #999; font-size: 12px;">(填写后可作为次数卡项使用，用于开次数卡时自动填写对应次数)</span>
            </div>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="12" >
            <el-form-item label="应付金额:" prop="totalFee">
              <el-input v-model="form.totalFee" placeholder="选填" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="height: 35px;" >
            <div style="margin-top: 10px;margin-left: 2px">
              元 <span style="color: #999; font-size: 12px;">（开卡时会自动填写对应金额）</span>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="限制教练:" prop="restrictedTeacher" class="align-left">
              <el-radio-group v-model="form.restrictedTeacher" @change="changeRestrictedTeacher">
                <el-radio label="1">全部允许</el-radio>
                <el-radio  label="2">部分允许</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        <el-row v-if="form.restrictedTeacher === '2'">
          <el-col :span="24">
            <el-form-item prop="teacherList">
              <el-checkbox-group v-model="form.teacherList">
                <el-checkbox v-for="(item) in teacherOptions" :key="item.id" :label="item.id" name="teacherList">{{ item.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
          <el-col :span="24">
            <el-form-item label="限制课程:" prop="restrictedCourses" class="align-left">
              <el-radio-group v-model="form.restrictedCourses" @change="changeRestrictedCourses">
                <el-radio label="1">全部允许</el-radio>
                <el-radio  label="2">部分允许</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.restrictedCourses === '2'" >
          <el-col :span="24" >
            <el-form-item prop="courseListInType">
              <!-- 按课程类型分块展示课程复选框 -->
              <div  class="course-group-container">
                <div
                  v-for="group in chooseCourseTypes"
                  :key="group.id"
                  class="course-group-item"
                >
                  <!-- 课程类型标题 -->
                  <div class="course-group-title">{{ group.label }}</div>
                  <!-- 该类型下的课程复选框 -->
                  <el-checkbox-group v-model="getCourseTypeItem(group.id).selectedCourses">
                    <el-checkbox v-for="(item) in group.courseList" :key="item.id" :label="item.id" name="courses">{{ item.label }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="限制约课次数:" prop="restrictedNum" class="align-left">
              <el-radio-group v-model="form.restrictedNum" >
                <el-radio label="1">不限次数</el-radio>
                <el-radio  label="2">限制约课次数</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.restrictedNum === '2'">
          <el-col :span="10">
            <el-form-item  prop="restrictedNum" >
              <el-select v-model="form.bookTime" placeholder="" style="width: 100px">
                <el-option
                  v-for="item in timeOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col >
          <el-col :span="14" >
            <el-form-item prop="bookNum" label="内，只能使用:" >
              <el-input v-model="form.bookNum" placeholder="" style="width: 80px" /> &nbsp;次
            </el-form-item>
            <el-form-item></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程扣次或费用:" prop="chargeType" class="align-left">
              <el-radio-group v-model="form.chargeType">
                <el-radio
                  v-for="item in chargeTypeOptions"
                  :key="item.chargeType"
                  :label="item.chargeType"
                  :value="item.chargeType"
                >{{ item.chargeTypeName }}</el-radio>
              </el-radio-group>
<!--              <span style="color: #999; font-size: 12px; margin-left: 20px">（ 默认扣1次或118元）</span>-->
            </el-form-item>

          </el-col>
        </el-row>
        <el-row v-if="form.chargeType === 'default'">
          <el-col :span="10"  >
            <el-form-item  prop="defaultNum" >
              扣卡次数
              <el-input v-model="form.defaultNum" placeholder="" style="width: 60px" /> 次,
            </el-form-item>
          </el-col>
          <el-col :span="14"  >
            <el-form-item  prop="defaultFee" label=" 或扣费金额(每节)">
              <el-input v-model="form.defaultFee" placeholder="" style="width: 80px;" /> 元
            </el-form-item>
            <el-form-item></el-form-item>
          </el-col>

        </el-row>
        <el-row v-if="form.chargeType === 'customize'">
          <fee-mode-hour ref="feeModeHour" :course-type-options="courseTypeOptions" :had-choose-type="form.courseTypes" />
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员卡简介:" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入会员卡简介" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员卡条款:" prop="conditions">
              <el-input v-model="form.conditions" type="textarea" placeholder="请输入会员卡条款" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loadingChange" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addMemberCard, updateMemberCard } from '@/api/school/sc/memberCardType'
import { selectForCheckbox,selectByTypeIds } from '@/api/school/sc/course/courseType'
import { teacherSelect} from "@/api/columns/teacher";
import feeModeHour from '@/components/sc/course/feeModeHour'
export default {
  components: {
    feeModeHour
  },
  data() {
    return {
      // 是否显示弹出层
      open: false,
      loadingChange: false,
      // 表单参数
      form: {
        chargeType:'default',
        defaultNum:1,
        defaultFee:200,
        courseTypes:[],
        restrictedCourses:'1',
        courseListInType:[],
        partTypes:[],
        sale:'1',
        restrictedNum:'1',
        bookTime:'每天',
        bookNum:1,
        restrictedTeacher:'1',
        teacherList:[]
      },
      timeOptions:[{id:'每天',label:'每天'},
                  {id:'每周',label:'每周'},
                  {id:'每月',label:'每月'},
                ],
      // 表单校验
      rules: {
        cardName: [
          { required: true, message: '会员卡名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
        ],
        courseTypes: [
          { required: true, message: '请选择卡项包含的课程类别', trigger: 'change' },
        ],
        days: [
          {
            pattern: /^[0-9]\d*$/,
            message: '天数必须为正整数',
            trigger: 'blur'
          },
        ],
        count: [
          {
            pattern: /^\d+(\.\d{1})?$/,
            message: '请输入数字，且最多保留1位小数',
            trigger: 'blur'
          },
        ],
        totalFee: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入数字，且最多保留2位小数',
            trigger: 'blur'
          },
        ],
        teacherList: [
          {
            validator: (rule, value, callback) => {
              if (this.form.restrictedTeacher === '2') {
                if (!value || value.length<1) {
                  callback(new Error('请选择教练'));
                }  else {
                  callback();
                }
              } else {
                callback(); // 其他情况不验证
              }
            },
            trigger: ['change']// 输入框用 blur 触发
          },
        ],
        courseListInType: [
          {
            validator: (rule, value, callback) => {
              if (this.form.restrictedCourses === '2') {
                value.forEach(item => {
                  if (!item.selectedCourses || item.selectedCourses.length<1) {
                    callback(new Error('请选择课程,'));
                  }
                 })
                callback();

              }else {
                callback(); // 其他情况不验证
              }
            },
            trigger: 'change'
          },
        ],
        bookNum: [
          {
            pattern: /^[1-9]\d*$/,
            message: '请输入正整数',//
            trigger: 'blur'
          },
        ],
        defaultNum: [
          {
            pattern: /^\d+(\.\d{1})?$/,
            message: '请输入数字，且最多保留1位小数',
            trigger: 'blur'
          },
        ],
        defaultFee: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入数字，且最多保留2位小数',
            trigger: 'blur'
          },
        ],
      },
      // 扣费模式
      chargeTypeOptions: [{
        chargeType: 'default',
        chargeTypeName: '所有课程默认'
      }, {
        chargeType: 'customize',
        chargeTypeName: '自定义每节课扣次或费用'
      }],
      // 可选课程类型
      courseTypeOptions: [],
      teacherOptions: [],
      loadingSelect: false,
      chooseCourseTypes:[],
    }
  },

  created() {
  },
  methods: {
    init: function() {
      this.selectForCheckbox()
    },

    // 初始化资费配置
    initFeeModeDate(data) {
      this.$nextTick(() => {
        this.$refs.feeModeHour.feeModeTableData = []
        this.$refs.feeModeHour.feeModeTableData = data.feeModeHourList
      })
      this.changeRestrictedCourses(data.restrictedCourses)
    },
    /**
     * 核心方法：根据课程类型ID获取form.courseTypes中的对应项
     * @param {Number} typeId 课程类型ID
     * @returns {Object} {courseType: xx, selectedCourses: []}
     */
    getCourseTypeItem(typeId) {
      if (typeId){
        let item = this.form.courseListInType.find(item => item.id === typeId);
        // 若不存在则自动创建（避免undefined）
        if (!item) {
          item = { id: typeId, selectedCourses: [] };
          this.form.courseListInType.push(item);
        }
        return item;
      }
    },
    /**
     * 课程类别下的课程
     * @param data
     */
    changeRestrictedCourses(data){
      if (data==='2' && this.form.courseTypes.length>0){
        // this.chooseCourseTypes=this.courseTypeOptions.filter(item => this.form.courseTypes.includes(item.id));

          selectByTypeIds({typeIds:this.form.courseTypes}).then(response => {
            this.loadingChange = false
            this.chooseCourseTypes=response.data
          }).catch(() => {
            this.loadingChange = false
          })


      }else {
        this.chooseCourseTypes=[]
        this.form.courseListInType=[]
      }
    },
    changecourseTypes(){
      this.changeRestrictedCourses(this.form.restrictedCourses)
    },
    changeRestrictedTeacher(){
      if (this.form.restrictedTeacher==='1'){
        this.form.teacherList=[]
      }
    },

    submitForm: function() {
      console.log(1)
      this.$refs['form'].validate(valid => {
        console.log(valid)
        if (valid) {
          this.loadingChange = true

          if (this.form.chargeType=='customize'){
            this.form.feeModeHourList = this.$refs.feeModeHour.feeModeTableData
            if (this.form.courseTypes.length!==this.form.feeModeHourList.length){
              this.$modal.msgError("课程扣次或费用设置的数据项，与所勾选的课程类别数量不一致！");
              this.loadingChange =false;
              return;
            }
          }

          if (this.form.cardTypeId !== undefined) {
            updateMemberCard(this.form).then(response => {
              this.loadingChange = false
              if (response.respCode === '0000') {
                this.msgSuccess('修改成功')
                this.open = false
                this.$emit('success')
              } else {
                this.msgError(response.respMsg)
              }
            }).catch(() => {
              this.loadingChange = false
            })
          } else {
            addMemberCard(this.form).then(response => {
              this.loadingChange = false
              if (response.respCode === '0000') {
                this.msgSuccess('新增成功')
                this.open = false
                this.$emit('success')
              } else {
                this.msgError(response.respMsg)
              }
            }).catch(() => {
              this.loadingChange = false
            })
          }
        }
      })
    },
    selectForCheckbox() {
      selectForCheckbox().then(response => {
        this.courseTypeOptions = response.data
      })
      teacherSelect().then(response => {
        this.teacherOptions = response.data.map(item => ({
          label: item.nickName,
          value: item.userId,
          id: item.userId
        }));
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        chargeType:'default',
        defaultNum:1,
        defaultFee:200,
        restrictedCourses:'1',
        courseTypes:[],
        courseListInType:[],
        partTypes:[],
        sale:'1',
        restrictedNum:'1',
        bookTime:'每天',
        bookNum:1,
        restrictedTeacher:'1',
        teacherList:[]
      }
      this.resetForm('form')
    },
    // 新增会员卡类别
    handleAddCourseType() {
      this.$refs.addCourseType.open = true
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
  .align-left {
    text-align: left;
  }
  .second-title{
    text-align: left;
    padding-left: 15px;
  }
  .none-margin-bottom{
    margin-bottom: 0px;
  }
  .margin-top-20{
    margin-top: 20px;
  }
  .header-need-input:before{
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }
  .fee-table{
    width: calc(100% - 25px);
    margin-left: 25px;
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .title {
    padding: 0px 0px;
    color: rgba(0,0,0,.85);
    font-weight: 500;
    font-size: 16px;
    display: flex;
    &.top {
      padding-top: 0px;
      display: inline-block;
      text-align: left;
    }
    .title-content{
      border-left: 3px solid #409EFF;
      padding-left: 10px;
    }
  }

</style>
<style>
/* 课程分组容器 */
.course-group-container {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 分组之间的间距 */
  padding: 5px 0;
}

/* 单个课程分组项 */
.course-group-item {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 课程类型标题 */
.course-group-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e6e6e6;
}
</style>
