<template>
  <div>
    <el-dialog title="新设课程" :visible.sync="open" width="900px" append-to-body @opened="onDialogOpened">
      <el-form ref="form" v-loading="loadingChange" :model="form" :rules="rules" label-width="120px">
        <div class="title top">
          <div class="title-content">课程基础信息</div>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称:" prop="courseName">
              <el-input v-model="form.courseName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.courseId==undefined">
            <el-form-item label="课程类别:" prop="courseTypeId"  >
              <div class="select-with-btn-container">
                <el-select
                  v-model="form.courseTypeId"
                  placeholder="请选择课程类别"
                  clearable
                  filterable
                  default-first-option
                  :loading="loadingSelect"
                  :disabled="form.courseId!=undefined"
                >
                  <el-option
                    v-for="item in courseTypeOptions"
                    :key="item.courseTypeId"
                    :label="item.courseType"
                    :value="item.courseTypeId"
                  />
                </el-select>
                <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddCourseType" :disabled="form.courseId!=undefined"/>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.courseId==undefined">
            <el-form-item label="上课校区:" prop="courseCampus" class="align-left">
              <el-radio-group v-model="form.courseCampus" >
                <el-radio
                  v-for="item in courseCampus"
                  :key="item.id"
                  :label="item.label"
                  :value="item.label"
                >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上课模式:" prop="teachingMode" class="align-left">
              <el-radio-group v-model="form.teachingMode">
                <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.courseCampus ==='部分校区' && form.courseId==undefined" >
          <el-form-item label="选择校区:" prop="partCampus" class="align-left">
            <el-checkbox-group v-model="form.partCampus" :disabled="form.courseId!=undefined">
              <el-checkbox v-for="(item) in campusOptions" :key="item.id" :label="item.id" name="partCampus">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程价值:" prop="tuitionFee">
              <el-input v-model="form.tuitionFee" placeholder="请输入课程价值(元/节)" />
              <span  style="color: #999; font-size: 12px; "></span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教练课时费:" prop="claFee">
              <el-input v-model="form.claFee" placeholder="请输入课时费金额(元/节)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程难度:" prop="star" >
              <el-rate
                v-model="form.star"
                style="padding-top: 8px;"
                :disabled="false"
                :colors="['#F7BA2A', '#F7BA2A', '#F7BA2A']"
                :void-color="'#C6D1DE'"
                :max="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-form-item label="备注:" prop="courseIntro">
            <el-input v-model="form.courseIntro" type="textarea"  placeholder="请输入课程简介(app不做展示)" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="课程说明（app展示）" prop="remark">
            <div class="editor-container remark-editor">
              <div ref="remarkEditor" style="width: 100%; min-height: 200px;"></div>
            </div>
          </el-form-item>
        </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>
    <add-course-type ref="addCourseType" @success="courseTypeList" />
  </div>
</template>
<script>
import { addCourse, updateCourse } from '@/api/school/sc/course'
import { select as courseTypeSelect } from '@/api/school/sc/course/courseType'
import { campusList, campusSelect } from '@/api/school/system/dept'
import feeModeHour from '@/components/sc/course/feeModeHour'
import feeModeDate from '@/components/sc/course/feeModeDate'
import feeModeCycle from '@/components/sc/course/feeModeCycle'
import addCourseType from '@/components/sc/course/type/addCourseType'
import feeModePrepaid from '@/components/sc/course/feeModePrepaid1.vue'
import WangEditor from "wangeditor";
import axios from "axios";
import {getToken} from "@/utils/auth";

export default {
  components: {
    addCourseType
  },
  data() {
    return {
      // 是否显示弹出层
      open: false,
      loadingChange: false,
      // 表单参数
      form: {
        courseCampus: '全部校区',
        claFee:0.0,
        tuitionFee:0.00,
        teachingMode: '1',
        partCampus: [],
        sale:'1',
        star: 0,
        courseIntro: '',
        remark: ''
      },
      // 富文本编辑器实例
      remarkEditor: null,
      // 表单校验
      rules: {
        courseName: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' }
        ],
        courseTypeId: [
          { required: true, message: '请选择课程类别', trigger: 'change' }
        ],
        teachingMode: [
          { required: true, message: '请选择上课模式', trigger: 'blur' }
        ],
        claFee: [
          { required: true, message: '请输入教练课时费', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入数字，且最多保留2位小数',
            trigger: 'blur'
          },
        ],
        courseCampus: [
          { required: true, message: '请选择上课校区', trigger: 'blur' }
        ],
        courseIntro: [
          {
            pattern: /^[\s\S]{0,100}$/,
            message: '最多输入100个字符',
            trigger: 'blur'
          },
        ],
      },
      // 可选校区类型
      courseCampus: [],
      courseTypeOptions: [],
      campusOptions: [],
      loadingSelect: false
    }
  },
  created() {
  },
  methods: {
    init: function() {

      this.courseTypeList()
      this.campusList()
      this.campusSelect()
      // 富文本回显
      if (this.form.remark){
        this.$nextTick(() => {
          setTimeout(() => {
            if (this.remarkEditor ) {
              const processedHtml = this.form.remark.replace(
                /<img/g,
                '<img style="max-width:100%;height:auto;"'
              );
              this.remarkEditor.txt.html(processedHtml);
            }
          }, 500);
        });
      }

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

          this.form.sale='1'
          if (this.form.courseCampus=='全部校区' || this.form.partCampus.length<1){
               this.form.partCampus=null
          }

          if (this.form.courseId !== undefined) {
            updateCourse(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 {
            addCourse(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
            })
          }
        }
      })
    },
    campusSelect() {
      campusSelect().then(response => {
        this.courseCampus = response.data
      })
    },
    campusList() {
      campusList().then(response => {
        this.campusOptions = response.data
      })
    },
    courseTypeList() {
      courseTypeSelect({}).then(response => {
        this.courseTypeOptions = response.data
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        courseCampus: '全部校区',
        teachingMode: '1',
        partCampus: [],
        star: 0,
        courseIntro: '',
        remark: '',
        claFee:0.0,
        tuitionFee:0.00
      }
      this.resetForm('form')
      // 清空富文本编辑器内容
      if (this.remarkEditor) {
        this.remarkEditor.txt.clear();
      }
    },
    // 新增课程类别
    handleAddCourseType() {
      this.$refs.addCourseType.open = true
    },
    /** 对话框打开后初始化富文本编辑器 */
    onDialogOpened() {
      if (!this.remarkEditor) {
        this.initRemarkEditor();
      }
    },

    /** 初始化富文本编辑器 */
    initRemarkEditor() {

      if (this.$refs.remarkEditor) {
        this.remarkEditor = new WangEditor(this.$refs.remarkEditor);

        // 关闭默认网络图片上传
        this.remarkEditor.config.showLinkImg = false;

        // 内容变化时同步到表单
        this.remarkEditor.config.onchange = (html) => {
          const processedHtml = html.replace(/<img/g, '<img style="max-width:100%;height:auto;"');
          this.form.remark = processedHtml;
        };

        // 配置菜单栏（简化版）
        this.remarkEditor.config.menus = [
          'head', 'bold', 'fontSize', 'foreColor', 'backColor',
          'list', 'justify', 'quote',  'undo', 'redo'
        ];

        // 创建编辑器实例
        this.remarkEditor.create();
      } else {
        setTimeout(() => this.initRemarkEditor(), 100);
      }
    },

  }
}
</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: 15px 0px;
    color: rgba(0,0,0,.85);
    font-weight: 500;
    font-size: 16px;
    display: flex;
    &.top {
      padding-top: 0px;
    }
    .title-content{

      border-left: 3px solid #409EFF;
      padding-left: 10px;
    }
  }
  /* 富文本样式 */
  .editor-container {
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    padding: 5px;
    margin-bottom: 10px;
  }

  .remark-editor {
    min-height: 200px;
  }

  .profile-editor {
    min-height: 300px;
  }

  .editor-container img {
    max-width: 100% !important;
    height: auto !important;
  }
</style>
