<template>
  <div>
    <xy-dialog
      ref="dialog"
      :width="70"
      :is-show.sync="isShow"
      :type="'form'"
      :title="type === 'add' ? '新增日程' : '编辑日程'"
      :form="form"
      :rules="rules"
    >
      <template v-slot:is_publish>
        <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
              filterable
              v-model="form.is_publish"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in [{id:1,value:'是'},{id:0,value:'否'}]"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:type>
        <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
              filterable
              v-model="form.type"
              @change="changeType"
              placeholder="请选择日程类型"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in type_options"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-if="form.type === 1 || form.type === 2" v-slot:course_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
            >课程：
          </div>
          <div class="xy-table-item-content">
            <el-select
              filterable
              v-model="form.course_id"
              :disabled="canSelect"
              @change="changeCourse"
              placeholder="请选择课程"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in course_options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              <div style="display: flex; justify-content: space-between;padding: 0 10px;">
                <span style="color: #999; font-size: 12px;">{{item.type_detail?item.type_detail.name:''}} | {{ item.name }}</span>
                <span style="color: #999; font-size: 12px;">{{ item.is_arrange?'需排课':'无需排课' }}</span>
              </div>
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-if="form.type === 1 || form.type === 2" v-slot:introduce>
        <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.introduce"
              filterable
              allow-create
              default-first-option
              placeholder="请选择或新建模块"
              clearable
              style="width: 100%"
              @change="onModuleChange"
              @create="onCreateModule"
            >
              <el-option
                v-for="item in module_options"
                :key="item.id"
                :label="item.value"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-if="form.type === 2" v-slot:course_content_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
            >课表：
          </div>
          <div class="xy-table-item-content">
            <el-select
              filterable
              v-model="form.course_content_id"
              @change="changeCourseContent"
              placeholder="请选择课表"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in course_content_options"
                :key="item.id"
                :label="item.theme"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-if="form.type === 3" v-slot:course_type_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
            >课程体系：
          </div>
          <div class="xy-table-item-content">
            <el-select
              filterable
              v-model="form.course_type_id"
              placeholder="请选择课程体系"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in courseTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:title>
        <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.title"
              placeholder="请输入标题"
              clearable
              style="width: 100%"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:url>
        <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-if="form.type === 4 || form.type === 1"
              filterable
              remote
              v-model="form.url"
              :remote-method="remoteMethod"
              :loading="loading"
              placeholder="请输入关键词查询资讯"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in zixunList"
                :key="item.id"
                :label="item.title"
                :value="item.titleurl"
              >
              </el-option>
            </el-select>
            <el-input v-else v-model="form.url" placeholder="请输入链接" clearable style="width: 100%;"></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"  style="width: 100%;"
             type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期时间" align="right">
            </el-date-picker>
          </div>
        </div>
      </template> -->
      <template v-slot:start_time>
        <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.start_time"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:end_time>
        <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.end_time"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:days>
        <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-number
              v-model="form.days"
              :min="0"
              :step="0.5"
              style="width: 100%"
            ></el-input-number>
          </div>
        </div>
      </template>
      <template v-slot:address>
        <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.address" placeholder="请输入地址" clearable style="width: 100%;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:color>
        <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-color-picker v-model="form.color"></el-color-picker>
          </div>
        </div>
      </template>
      <template v-slot:is_count_days>
        <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
              filterable
              v-model="form.is_count_days"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in [{id:1,value:'是'},{id:0,value:'否'}]"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-if="form.type === 3" v-slot:is_count_people>
        <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
              filterable
              v-model="form.is_count_people"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in [{id:1,value:'是'},{id:0,value:'否'}]"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-if="form.type === 3 && form.is_count_people === 1" v-slot:history_courses>
        <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">
            <div style="border: 1px solid #dcdfe6; border-radius: 4px; padding: 15px;">
              <div style="display: flex; flex-wrap: wrap; gap: 15px;">
                <div style="flex: 1; min-width: 200px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">课程体系：</div>
                  <el-select
                    filterable
                    v-model="historyCourseForm.type"
                    placeholder="请选择课程体系"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in courseTypeOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </div>
                <div style="flex: 1; min-width: 200px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">课程名称：</div>
                  <el-input
                    v-model="historyCourseForm.course_name"
                    placeholder="请输入课程名称"
                    clearable
                    style="width: 100%"
                  ></el-input>
                </div>
                <div style="flex: 1; min-width: 150px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">培养人次（未去重）：</div>
                  <el-input-number
                    v-model="historyCourseForm.course_type_signs_pass"
                    :min="0"
                    style="width: 100%"
                  ></el-input-number>
                </div>
                <div style="flex: 1; min-width: 150px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">培养人数（去重）：</div>
                  <el-input-number
                    v-model="historyCourseForm.course_type_signs_pass_unique"
                    :min="0"
                    style="width: 100%"
                  ></el-input-number>
                </div>
                <div style="flex: 1; min-width: 150px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">课程培养人数：</div>
                  <el-input-number
                    v-model="historyCourseForm.course_signs_pass"
                    :min="0"
                    style="width: 100%"
                  ></el-input-number>
                </div>
                <div style="flex: 1; min-width: 150px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">开始时间：</div>
                  <el-date-picker
                    v-model="historyCourseForm.start_time"
                    type="date"
                    placeholder="选择开始日期"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </div>
                <div style="flex: 1; min-width: 150px;">
                  <div style="font-weight: bold; margin-bottom: 5px;">结束时间：</div>
                  <el-date-picker
                    v-model="historyCourseForm.end_time"
                    type="date"
                    placeholder="选择结束日期"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:content v-if="form.type === 3">
        <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">
            <my-tinymce
              v-if="showTinymce"
              @input="saveContent"
              :value="form.content"
            ></my-tinymce>
          </div>
        </div>
      </template>
      <template v-slot:footerContent>
        <el-button type="primary" size="small" @click="submit">保存</el-button>
        <!-- <el-popconfirm style="margin:0 10px" @confirm="delCalendar" title="确定删除吗？">
          <el-button type="danger" size="small" v-if="type==='editor'" slot="reference">删除</el-button>
        </el-popconfirm> -->
        <el-popconfirm style="margin:0 10px" @confirm="delCalendar" title="确定删除吗？">
          <el-button type="danger" size="small" slot="reference">删除</el-button>
        </el-popconfirm>
      </template>
    </xy-dialog>
  </div>  
</template>

<script>
import { show, save,destroy } from "@/api/calendars/index.js";
import { index as courseIndex } from "@/api/course/index.js";
import { index as courseTypeIndex } from "@/api/course/courseType.js";
import { index as courseContentIndex } from "@/api/course/courseContent.js";
export default {
  components: {},
  data() {
    return {
      isShow: false,
      type: "add",
      id: "",
      showTinymce: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      type_options: [
        {
          id: 1,
          value: "课程",
        },
        // {
        //   id: 2,
        //   value: '课表'
        // },
        {
          id: 3,
          value: "自定义事件",
        },
        {
          id: 4,
          value: "资讯",
        },
      ],
      course_content_options: [],
      course_options: [],
      courseTypeOptions: [],
      canSelect: false,
      module_options: [
        { id: 1, value: '第一模块' },
        { id: 2, value: '第二模块' },
        { id: 3, value: '第三模块' },
        { id: 4, value: '第四模块' },
        { id: 5, value: '第五模块' },
        { id: 6, value: '第六模块' },
        { id: 7, value: '第七模块' },
        { id: 8, value: '第八模块' },
        { id: 9, value: '第九模块' },
        { id: 10, value: '第十模块' }
      ],
      form: {
        is_publish:1,
        type: "",
        course_type_id: "",
        course_id: "",
        introduce: "",
        course_content_id: "",
        title: "",
        url: "",
        // date: '',
        start_time: "",
        end_time: "",
        days: 0,
        address:'',
        color:'',
        
        is_count_days: 1,
        is_count_people: 1,
        history_courses: [],
        content: "",
      },
      historyCourseForm: {
        type: '',
        course_name: '',
        course_type_signs_pass: 0,
        course_type_signs_pass_unique: 0,
        course_signs_pass: 0,
        start_time: '',
        end_time: ''
      },
      rules: {
        type: [
          {
            required: true,
            message: "请选择日程类型",
            trigger: 'change'
          },
        ],
        course_type_id: [
          {
            required: true,
            message: "请选择课程体系",
            trigger: 'change'
          },
        ],
        title: [
          {
            required: true,
            message: "请输入标题",
          },
        ],
        start_time: [
          {
            required: true,
            message: "请选择开始时间",
          },
        ],
        // end_time: [{
        //   required: true,
        //   message: '请选择结束时间'
        // }],
      },
      historyCourseRules: {
        type: [
          {
            required: true,
            message: "请选择课程体系",
            trigger: 'change'
          },
        ],
        course_name: [
          {
            required: true,
            message: "请输入课程名称",
            trigger: 'blur'
          },
        ],
        course_type_signs_pass: [
          {
            required: true,
            message: "请输入培养人次（未去重）",
            trigger: 'blur'
          },
        ],
        course_type_signs_pass_unique: [
          {
            required: true,
            message: "请输入培养人数（去重）",
            trigger: 'blur'
          },
        ],
        course_signs_pass: [
          {
            required: true,
            message: "请输入课程培养人数",
            trigger: 'blur'
          },
        ],
        start_time: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: 'change'
          },
        ],
        end_time: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: 'change'
          },
        ]
      },
      zixunList: [],
      suppressAutoDays: false,
    };
  },
  created() {
    this.getCourseList();
    this.getZxList();
    this.getCourseTypeList();
  },
  methods: {
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        this.getZxList(query);
      } else {
        this.zixunList = [];
      }
    },
    async getZxList(query) {
      const proUrl = `${process.env.VUE_APP_PRO_API}`;
      var baseUrl = proUrl + "/e/extend/news.php";
      try {
        // 直接调用 axios.get()，传入接口地址和参数
        const response = await axios.get(baseUrl, {
          params: {
            page: 1,
            pagesize: 999,
            keyword: query,
          }, // GET 参数（拼在 URL 后）
          timeout: 5000, // 超时时间（毫秒）
        });
        // 请求成功，存储结果
        if (response.status === 200) {
          this.zixunList = response.data.rows;
        }
        this.loading = false;
        console.log("GET 请求成功：", response);
      } catch (error) {
        // 请求失败，处理错误
        console.error("GET 请求失败：", error);
        alert("请求失败：" + (error.response?.data?.msg || "网络错误"));
      }
    },
    async getCourseList() {
      const res = await courseIndex({
        page: 1,
        page_size: 999,
        sort_name: "id",
        sort_type: "DESC",
        show_relation: ["image", "typeDetail"],
      });
      this.course_options = res.data;
    },
    async getCourseTypeList() {
      try {
        const res = await courseTypeIndex({
          page: 1,
          page_size: 999,
          filter: [{
            key: 'is_history',
            op: 'eq',
            value: 1
          }]
        })
        if (res && res.data) {
          this.courseTypeOptions = res.data
        }
      } catch (error) {
        console.error('获取课程体系列表失败:', error)
      }
    },
    async getCourseContentList(course_id) {
      const res = await courseContentIndex({
        page: 1,
        page_size: 999,
        filter: [
          {
            key: "course_id",
            op: "like",
            value: course_id,
          },
        ],
      });
      if (res.data.length < 1) {
        this.$Message.warning("该课程暂无课表");
        return;
      }
      this.course_content_options = res.data;
    },
    saveContent(e) {
      this.form.content = e;
    },
    changeType(e) {
      console.log("type", e);
    },
    changeIntroduce(e) {
      console.log("e", e);
      if (e) {
        this.form.title = this.form.title + " - " + e;
      }
    },
    changeCourse(e) {
      console.log("course", e);
      // 获取课表
      if (this.form.type == 2) {
        this.form.course_content_id = "";
        this.getCourseContentList(e);
      }
      // 选择课程 自动填充
      if (this.form.type == 1) {
        this.course_options.map((item) => {
          if (item.id === e) {
            this.form.title =
              (item.type_detail ? item.type_detail.name + " - " : "") +
              item.name;
            // 仅新增时自动填充开始/截止时间，编辑时保留原值
            if (this.type === 'add') {
              this.form.start_time = item.start_date
                ? `${item.start_date} 09:00:00`
                : "";
              this.form.end_time = item.end_date
                ? `${item.end_date} 17:00:00`
                : "";
              this.form.date = item.start_date;
            }
            this.form.url = item.url;
            this.form.color = item.type_detail?(item.type_detail.color?item.type_detail.color:''):''
          }
        });
        this.updateDaysFromDates();
      }
    },
    changeCourseContent(e) {
      // 选择课表 自动填充
      if (this.form.type == 2) {
        this.course_content_options.map((item) => {
          if (item.id === e) {
            this.form.title = item.theme;
            // 仅新增时自动填充开始/截止时间，编辑时保留原值
            if (this.type === 'add') {
              this.form.start_time = item.start_date;
              this.form.end_time = item.end_date;
              this.form.date = item.start_date;
            }
          }
        });
        this.updateDaysFromDates();
      }
    },
    onModuleChange(value) {
      // 当选择模块时，自动拼接到标题后面
      if (value && this.form.title) {
        // 先去除标题中可能存在的模块值
        let cleanTitle = this.form.title;
        this.module_options.forEach(module => {
          if (cleanTitle.includes(' - ' + module.value)) {
            cleanTitle = cleanTitle.replace(' - ' + module.value, '');
          }
        });
        // 拼接新的模块值
        this.form.title = cleanTitle + ' - ' + value;
      }
    },
    onCreateModule(value) {
      // 当创建新模块时，添加到选项列表并选中
      const newModule = {
        id: this.module_options.length + 1,
        value: value
      };
      this.module_options.push(newModule);
      this.form.introduce = value;
      // 先去除标题中可能存在的模块值，再拼接新的模块值
      if (this.form.title) {
        let cleanTitle = this.form.title;
        this.module_options.forEach(module => {
          if (cleanTitle.includes(' | ' + module.value)) {
            cleanTitle = cleanTitle.replace(' | ' + module.value, '');
          }
        });
        // 拼接新的模块值
        this.form.title = cleanTitle + ' | ' + value;
      }
    },
    submit() {
      // 手动验证主表单必填字段
      const mainErrors = [];
      if (!this.form.type) mainErrors.push('请选择日程类型');
      if (this.form.type === 3 && !this.form.course_type_id) mainErrors.push('请选择课程体系');
      if (!this.form.title) mainErrors.push('请输入标题');
      if (!this.form.start_time) mainErrors.push('请选择开始时间');
      
      // 如果日程类型是课程，验证课程字段
      if ((this.form.type === 1 || this.form.type === 2) && !this.form.course_id) {
        mainErrors.push('请选择课程');
      }
      
      // 如果日程类型是课表，验证课表字段
      if (this.form.type === 2 && !this.form.course_content_id) {
        mainErrors.push('请选择课表');
      }
      
      if (mainErrors.length > 0) {
        this.$message.error(mainErrors[0]);
        return;
      }
      
      if (this.id) {
        this.form.id = this.id;
      }
      if (this.type == "add") {
        this.form.id = "";
        this.form.title = this.form.introduce
          ? this.form.title + " - " + this.form.introduce
          : this.form.title;
      }
      
      // 处理历史课程数据
      if (this.form.type === 3 && this.form.is_count_people === 1) {
        // 验证历史课程数据
        const errors = [];
        if (!this.historyCourseForm.type) errors.push('请输入课程人数 - 课程体系');
        if (!this.historyCourseForm.course_name) errors.push('请输入课程人数 - 课程名称');
        if (this.historyCourseForm.course_type_signs_pass === null || this.historyCourseForm.course_type_signs_pass === undefined || this.historyCourseForm.course_type_signs_pass === '') errors.push('请输入课程人数 - 培养人次（未去重）');
        if (this.historyCourseForm.course_type_signs_pass_unique === null || this.historyCourseForm.course_type_signs_pass_unique === undefined || this.historyCourseForm.course_type_signs_pass_unique === '') errors.push('请输入课程人数 - 培养人数（去重）');
        if (this.historyCourseForm.course_signs_pass === null || this.historyCourseForm.course_signs_pass === undefined || this.historyCourseForm.course_signs_pass === '') errors.push('请输入课程人数 - 课程培养人数');
        if (!this.historyCourseForm.start_time) errors.push('请输入课程人数 - 开始时间');
        if (!this.historyCourseForm.end_time) errors.push('请输入课程人数 - 结束时间');
        
        if (errors.length > 0) {
          this.$message.error(errors[0]);
          return;
        }
        
        this.form.history_courses = [this.historyCourseForm];
      } else {
        this.form.history_courses = [];
      }
      
      save({
        ...this.form,
      }).then((res) => {
        this.$message({
          type: "success",
          message: this.type === "add" ? "新增成功" : "编辑成功",
        });
        this.isShow = false;
        this.$emit("refresh");
      }).catch((error) => {
        console.error('保存失败:', error);
        this.$message.error('保存失败，请重试');
      });
    },

    getDetail() {
      show({
        id: this.id,
      }).then((res) => {
        this.suppressAutoDays = true;
        this.form = this.base.requestToForm(res, this.form);
        this.form.is_publish = res.is_publish ? res.is_publish : 0;
        this.form.is_count_days = res.is_count_days !== undefined ? res.is_count_days : 1;
        this.form.is_count_people = res.is_count_people !== undefined ? res.is_count_people : 1;
        this.form.days = this.normalizeDaysValue(res.days);
        
        // 处理历史课程数据
        if (res.history_courses && res.history_courses.length > 0) {
          this.historyCourseForm = {
            type: res.history_courses[0].type?parseInt(res.history_courses[0].type) : '',
            course_name: res.history_courses[0].course_name || '',
            course_type_signs_pass: res.history_courses[0].course_type_signs_pass || 0,
            course_type_signs_pass_unique: res.history_courses[0].course_type_signs_pass_unique || 0,
            course_signs_pass: res.history_courses[0].course_signs_pass || 0,
            start_time: res.history_courses[0].start_time || '',
            end_time: res.history_courses[0].end_time || ''
          }
        }
        
        this.showTinymce = true;
        this.$nextTick(() => {
          this.suppressAutoDays = false;
        });
      });
    },
    delCalendar() {
      destroy({
        id: this.id,
      }).then((res) => {
        this.$message({
          type: "success",
          message: "删除成功",
        });
        this.isShow = false;
        this.$emit("refresh");
      });
    },
    getDefaultDateTime(time) {
      const date = new Date();
      const year = date.getFullYear();
      const month = `${date.getMonth() + 1}`.padStart(2, "0");
      const day = `${date.getDate()}`.padStart(2, "0");
      return `${year}-${month}-${day} ${time}`;
    },
    setDefaultTimes() {
      if (this.type === 'editor') {
        return;
      }
      if (!this.form.start_time) {
        this.form.start_time = this.getDefaultDateTime("09:00:00");
      }
      if (!this.form.end_time) {
        this.form.end_time = this.getDefaultDateTime("17:00:00");
      }
      this.updateDaysFromDates();
      this.updateHistoryCourseDefaultDates();
    },
    updateDaysFromDates() {
      if (!this.form.start_time || !this.form.end_time) {
        this.form.days = 0;
        return;
      }
      const startDateStr = this.form.start_time.split(" ")[0];
      const endDateStr = this.form.end_time.split(" ")[0];
      const startDate = new Date(startDateStr.replace(/-/g, "/"));
      const endDate = new Date(endDateStr.replace(/-/g, "/"));
      if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
        return;
      }
      const diff =
        Math.floor(
          (endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000)
        ) + 1;
      this.form.days = this.normalizeDaysValue(diff > 0 ? diff : 0);
    },
    normalizeDaysValue(value) {
      if (value === null || value === undefined || value === "") {
        return 0;
      }
      const num = Number(value);
      if (Number.isNaN(num)) {
        return 0;
      }
      // return Math.max(0, Math.round(num));
      return value
    },
    updateHistoryCourseDefaultDates() {
      if (this.form.type == 3) {
        // 从 form.start_time 和 form.end_time 提取年月日部分，直接赋值（不检查是否为空）
        if (this.form.start_time) {
          this.historyCourseForm.start_time = this.form.start_time.split(' ')[0];
        }
        if (this.form.end_time) {
          this.historyCourseForm.end_time = this.form.end_time.split(' ')[0];
        }
      }
    },
  },
  watch: {
    "form.start_time"() {
      if (this.suppressAutoDays) return;
      this.updateDaysFromDates();
      this.updateHistoryCourseDefaultDates();
    },
    "form.end_time"() {
      if (this.suppressAutoDays) return;
      this.updateDaysFromDates();
      this.updateHistoryCourseDefaultDates();
    },
    "form.is_count_people"(newVal) {
      // 如果选择否，清空课程人数相关字段
      if (newVal === 0) {
        this.historyCourseForm = {
          type: '',
          course_name: '',
          course_type_signs_pass: 0,
          course_type_signs_pass_unique: 0,
          course_signs_pass: 0,
          start_time: '',
          end_time: ''
        };
      }
    },
    isShow(newVal) {
      if (newVal) {
        if (this.type === "editor") {
          console.log("id", this.id);
          this.getDetail();
        } else {
          this.showTinymce = true;
          this.setDefaultTimes();
        }
      } else {
        this.id = "";
        this.showTinymce = false;
        this.form = {
          is_publish: 1,
          type: "",
          course_type_id: "",
          course_id: "",
          introduce: "",
          course_content_id: "",
          title: "",
          url: "",
          date: "",
          start_time: "",
          end_time: "",
          days: 0,
          address:'',
          color:'',
          
          is_count_days: 1,
          is_count_people: 1,
          history_courses: [],
          content: "",
        };
        // 获取当天日期
        const today = new Date();
        const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
        
        this.historyCourseForm = {
          type: '',
          course_name: '',
          course_type_signs_pass: 0,
          course_type_signs_pass_unique: 0,
          course_signs_pass: 0,
          start_time: todayStr+'',
          end_time: todayStr+''
        };
        this.setDefaultTimes();
        // 确保历史课程时间也有默认值
        this.updateHistoryCourseDefaultDates();
        this.$refs["dialog"].reset();
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .content,
::v-deep .history_courses {
  flex-basis: 100%;
}
</style>
