formPage.vue 36.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
<!--
 * @Author: hookehuyr hookehuyr@gmail.com
 * @Date: 2025-01-20 10:00:00
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-10-28 10:15:33
 * @FilePath: /mlaj/src/views/teacher/formPage.vue
 * @Description: 教师作业新增表单页面
-->
<template>
  <AppLayout>
    <div class="bg-gradient-to-br from-green-50 via-green-100/30 to-blue-50/30 min-h-screen">
      <div class="px-4 py-6">
        <FrostedGlass class="rounded-xl overflow-hidden">
          <div class="p-6">
            <van-form @submit="handleSubmit">
              <!-- 作业名称输入框 -->
              <div class="mb-6">
                <van-field
                  v-model="formData.title"
                  name="title"
                  :placeholder="`请输入${pageTitle === '设置作业' ? '作业' : '打卡'}名称(必填)`"
                  required
                  :border="false"
                  class="homework-name-field"
                />
              </div>

              <!-- 作业要求说明 -->
              <div class="mb-6">
                <van-field
                  v-model="formData.note"
                  name="note"
                  type="textarea"
                  :placeholder="`请输入${pageTitle === '设置作业' ? '作业' : '打卡'}要求和说明`"
                  :border="false"
                  rows="4"
                  class="description-field"
                />
              </div>

              <!-- 作业设置 -->
              <div class="mb-6">
                <h3 class="section-title">{{ pageTitle }}</h3>

                <!-- 作品类型选择 - 只在设置作业时显示 -->
                <div v-if="$route.query.type === 'homework'" class="mb-4">
                  <label class="setting-label">作业类型 (可多选)</label>
                  <van-checkbox-group v-model="formData.attachment_type" direction="horizontal" checked-color="#4caf50" icon-size="1.05rem">
                    <van-checkbox
                      v-for="option in attachmentTypeOptions"
                      :key="option.name"
                      :name="option.name"
                      shape="square"
                    >
                      <span style="font-size: 1rem;">{{ option.text }}</span>
                    </van-checkbox>
                  </van-checkbox-group>
                </div>

                <!-- 作业频次和每周期提交数量 -->
                <van-row gutter="10" class="mb-4">
                  <van-col span="12">
                    <label class="setting-label">{{ pageTitle === '设置作业' ? '作业' : '打卡' }}频次</label>
                    <van-field
                      v-model="formData.cycle_text"
                      is-link
                      readonly
                      name="cycle_text"
                      placeholder="请选择周期"
                      :border="false"
                      @click="showCyclePicker = true"
                      class="cycle-field"
                    />
                  </van-col>
                  <van-col span="12">
                    <label class="setting-label">每周期提交数量</label>
                    <div class="target-count-container">
                      <van-stepper
                        v-model="formData.frequency"
                        min="0"
                        max="100"
                        integer
                        button-size="24px"
                        input-width="50%"
                      />
                      <span class="target-unit">次</span>
                    </div>
                  </van-col>
                </van-row>

                <!-- 目标总数 -->
                <van-row gutter="10" class="mb-4">
                  <van-col span="24">
                    <label class="setting-label">目标总数</label>
                    <div class="target-count-container">
                      <van-stepper
                        v-model="formData.target_number"
                        min="0"
                        max="100"
                        integer
                        button-size="24px"
                        input-width="80%"
                      />
                      <span class="target-unit">次</span>
                    </div>
                  </van-col>
                </van-row>
              </div>

              <!-- 时间设置 -->
              <div class="mb-6">
                <div class="time-row">
                  <div class="time-item">
                    <van-icon name="calendar-o" class="time-icon" />
                    <span class="time-label">开始日期:</span>
                    <span class="time-value" @click="openStartTimePicker">
                      {{ startTimeDisplay || '2025-05-13' }}
                    </span>
                    <van-icon name="arrow" class="arrow-icon" />
                  </div>
                </div>
                <div class="time-row">
                  <div class="time-item">
                    <van-icon name="calendar-o" class="time-icon" />
                    <span class="time-label">结束日期:</span>
                    <span class="time-value" @click="openEndTimePicker">
                      {{ endTimeDisplay || '2025-06-13' }}
                    </span>
                    <van-icon name="arrow" class="arrow-icon" />
                  </div>
                </div>
              </div>

              <!-- 选择项目 -->
              <div class="mb-6">
                <div class="select-row">
                  <div class="select-item">
                    <van-icon name="friends-o" class="select-icon" />
                    <span class="select-label">所在年级:</span>
                    <span class="select-value" @click="showGradePicker = true">{{ formData.grade || '请选择年级' }}</span>
                    <van-icon name="arrow" class="arrow-icon" @click="showGradePicker = true" />
                  </div>
                </div>
                <div class="select-row">
                  <div class="select-item">
                    <van-icon name="friends-o" class="select-icon" />
                    <span class="select-label">所在班级:</span>
                    <span class="select-value" @click="showClassPicker = true">{{ formData.class_name || '请选择班级' }}</span>
                    <van-icon name="arrow" class="arrow-icon" @click="showClassPicker = true" />
                  </div>
                </div>
                <div class="select-row">
                  <div class="select-item">
                    <van-icon name="friends-o" class="select-icon" />
                    <span class="select-label">所在课程:</span>
                    <span class="select-value" @click="showCoursePicker = true">{{ formData.course || '请选择课程' }}</span>
                    <van-icon name="arrow" class="arrow-icon" @click="showCoursePicker = true" />
                  </div>
                </div>
                <div class="select-row" v-if="courseChapters[formData.course]?.length">
                  <div class="select-item">
                    <van-icon name="bookmark-o" class="select-icon" />
                    <span class="select-label">课程章节:</span>
                    <span class="select-value" @click="showChapterPicker = true">
                      {{ selectedChaptersDisplay || '请选择章节' }}
                    </span>
                    <van-icon name="arrow" class="arrow-icon" @click="showChapterPicker = true" />
                  </div>
                </div>
                <!-- <div class="select-row">
                  <div class="select-item">
                    <van-icon name="fire-o" class="select-icon" />
                    <span class="select-label">所在活动:</span>
                    <span class="select-value" @click="showActivityPicker = true">{{ formData.activity || '请选择活动' }}</span>
                    <van-icon name="arrow" class="arrow-icon" @click="showActivityPicker = true" />
                  </div>
                </div>
                <div class="select-row">
                  <div class="select-item">
                    <van-icon name="friends-o" class="select-icon" />
                    <span class="select-label">所在小组:</span>
                    <span class="select-value" @click="showGroupPicker = true">{{ formData.group_name || '请选择小组' }}</span>
                    <van-icon name="arrow" class="arrow-icon" @click="showGroupPicker = true" />
                  </div>
                </div> -->
              </div>

              <!-- 提交按钮 -->
              <div class="submit-container">
                <van-button
                  native-type="submit"
                  type="primary"
                  block
                  round
                  :loading="loading"
                  class="submit-btn"
                >
                  确认发布
                </van-button>
              </div>
            </van-form>
          </div>
        </FrostedGlass>
        <div style="height: 4rem;"></div>
      </div>
    </div>

    <!-- 周期选择器 -->
    <van-popup v-model:show="showCyclePicker" position="bottom">
      <van-picker :columns="cycleOptions" @confirm="onCycleConfirm" @cancel="showCyclePicker = false" />
    </van-popup>

    <!-- 开始时间选择器 -->
    <van-popup v-model:show="showStartTimePicker" position="bottom">
      <van-picker-group
        title="选择开始时间"
        :tabs="['选择日期', '选择时间']"
        next-step-text="下一步"
        @confirm="onStartTimeConfirm"
        @cancel="showStartTimePicker = false"
      >
        <van-date-picker
          v-model="startDate"
          :min-date="minDate"
          :max-date="maxDate"
        />
        <van-time-picker
          v-model="startTime"
          :columns-type="['hour', 'minute', 'second']"
        />
      </van-picker-group>
    </van-popup>

    <!-- 结束时间选择器 -->
    <van-popup v-model:show="showEndTimePicker" position="bottom">
      <van-picker-group
        title="选择结束时间"
        :tabs="['选择日期', '选择时间']"
        next-step-text="下一步"
        @confirm="onEndTimeConfirm"
        @cancel="showEndTimePicker = false"
      >
        <van-date-picker
          v-model="endDate"
          :min-date="minDate"
          :max-date="maxDate"
        />
        <van-time-picker
          v-model="endTime"
          :columns-type="['hour', 'minute', 'second']"
        />
      </van-picker-group>
    </van-popup>

    <!-- 课程选择器 -->
    <van-popup v-model:show="showCoursePicker" position="bottom">
      <div class="p-4">
        <van-search v-model="courseSearchValue" placeholder="搜索课程" @search="searchCourse" />
        <van-list>
          <van-cell v-for="course in filteredCourses" :key="course.id" :title="course.name" is-link :border="false"
            @click="onCourseSelect(course)" />
        </van-list>
      </div>
    </van-popup>

    <!-- 课程章节选择器 -->
    <van-popup v-model:show="showChapterPicker" position="bottom" class="chapter-picker-popup">
      <div class="chapter-picker-container">
        <div class="picker-header">
          <h3>批量设置课程章节</h3>
          <van-search v-model="chapterSearchValue" placeholder="搜索章节" @search="searchChapter" />
        </div>

        <div class="chapter-list">
          <div v-for="chapter in filteredAvailableChapters" :key="chapter.id" class="chapter-item">
            <van-checkbox
              v-model="chapter.selected"
              @change="onChapterToggle(chapter)"
              class="chapter-checkbox"
            >
              {{ chapter.name }}
            </van-checkbox>

            <!-- 时间设置区域 -->
            <div v-if="chapter.selected" class="time-settings">
              <div class="time-row">
                <span class="time-label">开始时间:</span>
                <van-field
                  v-model="chapter.startTime"
                  readonly
                  placeholder="请选择开始时间"
                  @click="openTimePicker(chapter, 'start')"
                  class="time-field"
                />
              </div>
              <div class="time-row">
                <span class="time-label">结束时间:</span>
                <van-field
                  v-model="chapter.endTime"
                  readonly
                  placeholder="请选择结束时间"
                  @click="openTimePicker(chapter, 'end')"
                  class="time-field"
                />
              </div>
            </div>
          </div>
        </div>

        <div class="picker-footer">
          <van-button @click="cancelChapterSelection" class="cancel-btn">取消</van-button>
          <van-button type="primary" @click="confirmChapterSelection" class="confirm-btn">
            确认选择 ({{ selectedChaptersCount }}个章节)
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 时间选择器 -->
    <van-popup v-model:show="showChapterTimePicker" position="bottom">
      <van-date-picker
        v-model="currentChapterTime"
        title="选择时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onChapterTimeConfirm"
        @cancel="showChapterTimePicker = false"
      />
    </van-popup>

    <!-- 活动选择器 -->
    <!-- <van-popup v-model:show="showActivityPicker" position="bottom">
      <div class="p-4">
        <van-search v-model="activitySearchValue" placeholder="搜索活动" @search="searchActivity" />
        <van-list>
          <van-cell v-for="activity in filteredActivities" :key="activity.id" :title="activity.name" is-link
            :border="false" @click="onActivitySelect(activity)" />
        </van-list>
      </div>
    </van-popup> -->

    <!-- 年级选择器 -->
    <van-popup v-model:show="showGradePicker" position="bottom">
      <div class="p-4">
        <van-search v-model="gradeSearchValue" placeholder="搜索年级" @search="searchGrade" />
        <van-list>
          <van-cell v-for="grade in filteredGrades" :key="grade.id" :title="grade.name" is-link :border="false"
            @click="onGradeSelect(grade)" />
        </van-list>
      </div>
    </van-popup>

    <!-- 班级选择器 -->
    <van-popup v-model:show="showClassPicker" position="bottom">
      <div class="p-4">
        <van-search v-model="classSearchValue" placeholder="搜索班级" @search="searchClass" />
        <van-list>
          <van-cell v-for="classItem in filteredClasses" :key="classItem.id" :title="classItem.name" is-link
            :border="false" @click="onClassSelect(classItem)" />
        </van-list>
      </div>
    </van-popup>

    <!-- 小组选择器 -->
    <!-- <van-popup v-model:show="showGroupPicker" position="bottom">
      <div class="p-4">
        <van-search v-model="groupSearchValue" placeholder="搜索小组" @search="searchGroup" />
        <van-list>
          <van-cell v-for="group in filteredGroups" :key="group.id" :title="group.name" is-link :border="false"
            @click="onGroupSelect(group)" />
        </van-list>
      </div>
    </van-popup> -->
  </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, DatePicker, Popup } from 'vant';
import AppLayout from '@/components/layout/AppLayout.vue';
import FrostedGlass from '@/components/ui/FrostedGlass.vue';
import { useTitle } from '@vueuse/core';

import { getTeacherFindSettingsAPI, setTeacherTaskAPI } from "@/api/teacher";

const $route = useRoute();
const $router = useRouter();

const pageTitle = computed(() => {
  return $route.query.type === 'homework' ? '设置作业' : '安排打卡';
});

useTitle(pageTitle);

// 表单数据
const formData = ref({
  title: '',
  note: '',
  task_type: $route.query.type === 'homework' ? 'upload' : 'checkin',
  cycle_text: '',
  cycle: '',
  target_number: 1,
  start_time: new Date(),
  end_time: new Date(),
  course: '',
  lesson_id: '',
  chapter: '',
  // activity: '',
  grade: '',
  grade_id: '',
  class_name: '',
  class_id: '',
  // group_name: ''
  attachment_type: [], // 作品类型数组,用于设置作业时的多选
  frequency: 1 // 每周期提交数量
});

// 加载状态
const loading = ref(false);

// 弹窗显示状态
const showCyclePicker = ref(false);
const showStartTimePicker = ref(false);
const showEndTimePicker = ref(false);
const showCoursePicker = ref(false);
const showChapterPicker = ref(false);
const showChapterTimePicker = ref(false);
// const showActivityPicker = ref(false);
const showGradePicker = ref(false);
const showClassPicker = ref(false);
// const showGroupPicker = ref(false);

// 日期选择器相关
const startDate = ref(['2024', '01', '01']);
const endDate = ref(['2024', '12', '31']);
const startTime = ref(['00', '00', '00']);
const endTime = ref(['23', '59', '59']);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2035, 11, 31);

const cycleOptions = ref([]);

// 作品类型选项 - 从接口获取
const attachmentTypeOptions = ref([]);

// 搜索值
const courseSearchValue = ref('');
const chapterSearchValue = ref('');
// const activitySearchValue = ref('');
const gradeSearchValue = ref('');
const classSearchValue = ref('');
// const groupSearchValue = ref('');

// 数据列表
const courses = ref([]);

// 章节数据 - 根据课程动态变化
const chapters = ref([]);

// 各课程对应的章节数据
const courseChapters = ref({});

// 已选择的章节列表
const selectedChapters = ref([]);

// 当前时间选择相关
const currentChapterTime = ref(['2024', '01', '01']);
const currentChapter = ref(null);
const currentTimeType = ref(''); // 'start' or 'end'

// const activities = ref([
//   { id: 1, name: '春游活动' },
//   { id: 2, name: '运动会' },
//   { id: 3, name: '文艺汇演' },
//   { id: 4, name: '科技节' }
// ]);

const grades = ref([]);

const classes = ref([]);

// const groups = ref([
//   { id: 1, name: '第一小组' },
//   { id: 2, name: '第二小组' },
//   { id: 3, name: '第三小组' },
//   { id: 4, name: '第四小组' }
// ]);

// 计算属性 - 时间显示格式
const startTimeDisplay = computed(() => {
  if (!formData.value.start_time) return '';
  return formatDateTime(formData.value.start_time);
});

const endTimeDisplay = computed(() => {
  if (!formData.value.end_time) return '';
  return formatDateTime(formData.value.end_time);
});

// 过滤后的数据
const filteredCourses = computed(() => {
  if (!courseSearchValue.value) return courses.value;
  return courses.value.filter(course =>
    course.name.toLowerCase().includes(courseSearchValue.value.toLowerCase())
  );
});

const filteredChapters = computed(() => {
  if (!chapterSearchValue.value) return chapters.value;
  return chapters.value.filter(chapter =>
    chapter.name.toLowerCase().includes(chapterSearchValue.value.toLowerCase())
  );
});

// 可选择的章节列表(根据当前课程)
const filteredAvailableChapters = computed(() => {
  if (!chapterSearchValue.value) return chapters.value;
  return chapters.value.filter(chapter =>
    chapter.name.toLowerCase().includes(chapterSearchValue.value.toLowerCase())
  );
});

// 已选择章节的显示文本
const selectedChaptersDisplay = computed(() => {
  const count = selectedChapters.value.length;
  if (count === 0) return '';
  if (count === 1) return selectedChapters.value[0].name;
  return `已选择 ${count} 个章节`;
});

// 已选择章节数量
const selectedChaptersCount = computed(() => {
  return chapters.value.filter(chapter => chapter.selected).length;
});

// const filteredActivities = computed(() => {
//   if (!activitySearchValue.value) return activities.value;
//   return activities.value.filter(activity =>
//     activity.name.toLowerCase().includes(activitySearchValue.value.toLowerCase())
//   );
// });

const filteredGrades = computed(() => {
  if (!gradeSearchValue.value) return grades.value;
  return grades.value.filter(grade =>
    grade.name.toLowerCase().includes(gradeSearchValue.value.toLowerCase())
  );
});

const filteredClasses = computed(() => {
  if (!classSearchValue.value) return classes.value;
  return classes.value.filter(classItem =>
    classItem.name.toLowerCase().includes(classSearchValue.value.toLowerCase())
  );
});

// const filteredGroups = computed(() => {
//   if (!groupSearchValue.value) return groups.value;
//   return groups.value.filter(group =>
//     group.name.toLowerCase().includes(groupSearchValue.value.toLowerCase())
//   );
// });

/**
 * 格式化日期时间
 * @param {Date} date - 日期对象
 * @returns {string} 格式化后的日期时间字符串
 */
const formatDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hour = String(d.getHours()).padStart(2, '0');
  const minute = String(d.getMinutes()).padStart(2, '0');
  const second = String(d.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

/**
 * 周期选择确认
 * @param {Object} option - 选中的选项
 */
const onCycleConfirm = (option) => {
  formData.value.cycle_text = option.selectedOptions[0].text;
  formData.value.cycle = option.selectedOptions[0].value;
  showCyclePicker.value = false;
};

/**
 * 打开开始时间选择器
 */
const openStartTimePicker = () => {
  // 同步当前的开始时间到选择器
  if (formData.value.start_time) {
    const date = new Date(formData.value.start_time);
    startDate.value = [
      date.getFullYear().toString(),
      (date.getMonth() + 1).toString().padStart(2, '0'),
      date.getDate().toString().padStart(2, '0')
    ];
    startTime.value = [
      date.getHours().toString().padStart(2, '0'),
      date.getMinutes().toString().padStart(2, '0'),
      date.getSeconds().toString().padStart(2, '0')
    ];
  }
  showStartTimePicker.value = true;
};

/**
 * 开始时间确认
 */
const onStartTimeConfirm = () => {
  const [year, month, day] = startDate.value;
  const [hour, minute, second] = startTime.value;
  formData.value.start_time = new Date(
    parseInt(year),
    parseInt(month) - 1,
    parseInt(day),
    parseInt(hour),
    parseInt(minute),
    parseInt(second)
  );
  showStartTimePicker.value = false;
};

/**
 * 打开结束时间选择器
 */
const openEndTimePicker = () => {
  // 同步当前的结束时间到选择器
  if (formData.value.end_time) {
    const date = new Date(formData.value.end_time);
    endDate.value = [
      date.getFullYear().toString(),
      (date.getMonth() + 1).toString().padStart(2, '0'),
      date.getDate().toString().padStart(2, '0')
    ];
    endTime.value = [
      date.getHours().toString().padStart(2, '0'),
      date.getMinutes().toString().padStart(2, '0'),
      date.getSeconds().toString().padStart(2, '0')
    ];
  }
  showEndTimePicker.value = true;
};

/**
 * 结束时间确认
 */
const onEndTimeConfirm = () => {
  const [year, month, day] = endDate.value;
  const [hour, minute, second] = endTime.value;
  formData.value.end_time = new Date(
    parseInt(year),
    parseInt(month) - 1,
    parseInt(day),
    parseInt(hour),
    parseInt(minute),
    parseInt(second)
  );
  showEndTimePicker.value = false;
};

/**
 * 课程选择
 * @param {Object} course - 选中的课程
 */
const onCourseSelect = (course) => {
  formData.value.course = course.name;
  formData.value.lesson_id = course.id;
  // 清空之前选择的章节
  selectedChapters.value = [];
  // 根据选择的课程更新章节数据
  chapters.value = courseChapters.value[course.name] ? JSON.parse(JSON.stringify(courseChapters.value[course.name])) : [];
  showCoursePicker.value = false;
  courseSearchValue.value = '';
};

/**
 * 章节切换选择状态
 * @param {Object} chapter - 章节对象
 */
const onChapterToggle = (chapter) => {
  // 切换选择状态的逻辑已经由 v-model 处理
  console.log('章节选择状态变更:', chapter.name, chapter.selected);
};

/**
 * 打开时间选择器
 * @param {Object} chapter - 章节对象
 * @param {string} type - 时间类型 'start' 或 'end'
 */
const openTimePicker = (chapter, type) => {
  currentChapter.value = chapter;
  currentTimeType.value = type;

  // 设置当前时间
  const timeValue = type === 'start' ? chapter.startTime : chapter.endTime;
  if (timeValue) {
    const date = new Date(timeValue);
    currentChapterTime.value = [
      date.getFullYear().toString(),
      (date.getMonth() + 1).toString().padStart(2, '0'),
      date.getDate().toString().padStart(2, '0')
    ];
  } else {
    // 使用当前日期作为默认值
    const today = new Date();
    currentChapterTime.value = [
      today.getFullYear().toString(),
      (today.getMonth() + 1).toString().padStart(2, '0'),
      today.getDate().toString().padStart(2, '0')
    ];
  }

  showChapterTimePicker.value = true;
};

/**
 * 确认章节时间选择
 */
const onChapterTimeConfirm = () => {
  const [year, month, day] = currentChapterTime.value;
  const dateStr = `${year}-${month}-${day}`;

  if (currentChapter.value && currentTimeType.value) {
    // 时间验证逻辑
    if (currentTimeType.value === 'start') {
      // 设置开始时间时,检查是否晚于结束时间
      if (currentChapter.value.endTime && dateStr > currentChapter.value.endTime) {
        showToast('开始时间不能晚于结束时间');
        return;
      }
      currentChapter.value.startTime = dateStr;
    } else {
      // 设置结束时间时,检查是否早于开始时间
      if (currentChapter.value.startTime && dateStr < currentChapter.value.startTime) {
        showToast('结束时间不能早于开始时间');
        return;
      }
      currentChapter.value.endTime = dateStr;
    }
  }

  showChapterTimePicker.value = false;
  currentChapter.value = null;
  currentTimeType.value = '';
};

/**
 * 取消章节选择
 */
const cancelChapterSelection = () => {
  // 重置所有章节的选择状态
  chapters.value.forEach(chapter => {
    chapter.selected = false;
    chapter.startTime = '';
    chapter.endTime = '';
  });
  showChapterPicker.value = false;
  chapterSearchValue.value = '';
};

/**
 * 确认章节选择
 */
const confirmChapterSelection = () => {
  // 更新已选择的章节列表
  selectedChapters.value = chapters.value.filter(chapter => chapter.selected);

  // 验证已选择章节的时间设置
  const invalidChapters = selectedChapters.value.filter(chapter => !chapter.startTime || !chapter.endTime);
  if (invalidChapters.length > 0) {
    showToast('请为所有选中的章节设置开始和结束时间');
    selectedChapters.value = '';
    return;
  }

  // 验证时间逻辑:结束时间不能早于开始时间
  const timeInvalidChapters = selectedChapters.value.filter(chapter =>
    chapter.startTime && chapter.endTime && chapter.endTime < chapter.startTime
  );
  if (timeInvalidChapters.length > 0) {
    showToast('存在结束时间早于开始时间的章节,请重新设置');
    selectedChapters.value = '';
    return;
  }

  showChapterPicker.value = false;
  chapterSearchValue.value = '';
  showToast(`已选择 ${selectedChapters.value.length} 个章节`);
};

/**
 * 活动选择
 * @param {Object} activity - 选中的活动
 */
// const onActivitySelect = (activity) => {
//   formData.value.activity = activity.name;
//   showActivityPicker.value = false;
//   activitySearchValue.value = '';
// };

/**
 * 年级选择
 * @param {Object} grade - 选中的年级
 */
const onGradeSelect = (grade) => {
  formData.value.grade = grade.name;
  formData.value.grade_id = grade.id;
  showGradePicker.value = false;
  gradeSearchValue.value = '';
};

/**
 * 班级选择
 * @param {Object} classItem - 选中的班级
 */
const onClassSelect = (classItem) => {
  formData.value.class_name = classItem.name;
  formData.value.class_id = classItem.id;
  showClassPicker.value = false;
  classSearchValue.value = '';
};

/**
 * 小组选择
 * @param {Object} group - 选中的小组
 */
// const onGroupSelect = (group) => {
//   formData.value.group_name = group.name;
//   showGroupPicker.value = false;
//   groupSearchValue.value = '';
// };

/**
 * 搜索课程
 * @param {string} value - 搜索值
 */
const searchCourse = (value) => {
  courseSearchValue.value = value;
};

/**
 * 搜索章节
 * @param {string} value - 搜索值
 */
const searchChapter = (value) => {
  chapterSearchValue.value = value;
};

/**
 * 搜索活动
 * @param {string} value - 搜索值
 */
// const searchActivity = (value) => {
//   activitySearchValue.value = value;
// };

/**
 * 搜索年级
 * @param {string} value - 搜索值
 */
const searchGrade = (value) => {
  gradeSearchValue.value = value;
};

/**
 * 搜索班级
 * @param {string} value - 搜索值
 */
const searchClass = (value) => {
  classSearchValue.value = value;
};

/**
 * 搜索小组
 * @param {string} value - 搜索值
 */
// const searchGroup = (value) => {
//   groupSearchValue.value = value;
// };

/**
 * 表单提交处理
 * @param {Object} values - 表单值
 */
const handleSubmit = async (values) => {
  try {
    loading.value = true;

    // 验证必填项
    if (!formData.value.title) {
      showToast('请输入作业名称');
      return;
    }

    // 准备提交的数据,包含课程章节选择和格式化的日期
    const submitData = {
      ...formData.value,
      // 格式化日期为YYYY-MM-DD格式
      begin_date: formatDateTime(formData.value.start_time),
      end_date: formatDateTime(formData.value.end_time),
      // 处理每周期提交数量和目标总数,当值为0时转换为空值
      frequency: formData.value.frequency === 0 ? null : formData.value.frequency,
      target_number: formData.value.target_number === 0 ? null : formData.value.target_number,
      // 添加课程章节选择数据
      schedule: selectedChapters.value.map(chapter => ({
        id: chapter.id,
        name: chapter.name,
        begin_date: formatDateTime(chapter.startTime),
        end_date: formatDateTime(chapter.endTime)
      }))
    };

    // 这里可以调用API提交数据
    console.log('提交的表单数据:', submitData);
    const { code, data } = await setTeacherTaskAPI(submitData);
    if (code) {
      showToast('保存成功');
      $router.back();
    }

  } catch (error) {
    console.error('提交失败:', error);
    showToast('保存失败,请重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 组件挂载时初始化数据
 */
onMounted(async () => {
  // 这里可以调用API获取课程、活动、年级、班级、小组等数据
  const { code, data } = await getTeacherFindSettingsAPI();
  if (code) {
    cycleOptions.value = Object.entries(data.task_cycle).map(([value, text]) => ({
      text,
      value: String(value) // 确保值为字符串类型
    }));

    // 初始化周期选择
    formData.value.cycle_text = cycleOptions.value[0].text;
    formData.value.cycle = cycleOptions.value[0].value;

    // 处理作业类型数据
    if (data.task_attachment_type) {
      attachmentTypeOptions.value = Object.entries(data.task_attachment_type).map(([key, value]) => ({
        name: key, // 提交给后台的值
        text: value // 显示的文本
      }));
    }

    grades.value = data.grade_list.map(grade => ({
      name: grade.grade_name,
      id: String(grade.id)
    }));
    classes.value = data.class_list.map(classItem => ({
      name: classItem.class_name,
      id: String(classItem.id)
    }));
    courses.value = data.group_list.map(course => ({
      name: course.title,
      id: String(course.id),
      schedule_list: course.schedule_list
    }));
    data.group_list.forEach(course => {
      courseChapters.value[course.title] = course.schedule_list.map(chapter => ({
        id: chapter.id,
        name: chapter.title,
        selected: false,
        startTime: '',
        endTime: ''
      }));
    });
  }
});
</script>

<style scoped>
/* 自定义样式 */

/* 作业名称输入框 */
.homework-name-field {
  background: #f5f5f5;
  border-radius: 12px;
  padding: 0.5rem;
}

:deep(.homework-name-field .van-field__control) {
  font-size: 16px;
  font-weight: 500;
  padding: 12px 16px;
}

/* 作业要求说明 */
.description-field {
  background: #f5f5f5;
  border-radius: 12px;
  padding: 4px 0;
}

:deep(.description-field .van-field__control) {
  padding: 12px 16px;
  min-height: 100px;
}

/* 作业设置标题 */
.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

/* 设置行 */
.setting-row {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.setting-item {
  flex: 1;
}

.setting-label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

/* 周期选择 */
.cycle-field {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 0.3rem;
}

:deep(.cycle-field .van-field__control) {
  /* padding: 2px; */
  text-align: center;
}

/* 目标总数容器 */
.target-count-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.target-unit {
  font-size: 14px;
  color: #666;
  flex-shrink: 0;
}

:deep(.van-stepper) {
  background: #f5f5f5;
  border-radius: 8px;
  flex: 1;
  padding: 0.25rem;
}

/* 时间设置 */
.time-row {
  margin-bottom: 12px;
}

.time-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
}

.time-icon {
  color: #666;
  margin-right: 12px;
}

.time-label {
  font-size: 14px;
  color: #333;
  margin-right: auto;
}

.time-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.arrow-icon {
  color: #999;
  margin-left: 8px;
  cursor: pointer;
}

/* 选择项目 */
.select-row {
  margin-bottom: 12px;
}

.select-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
}

.select-icon {
  color: #666;
  margin-right: 12px;
}

.select-label {
  font-size: 14px;
  color: #333;
  margin-right: 12px;
  min-width: 80px;
}

.select-value {
  font-size: 14px;
  color: #666;
  margin-right: auto;
  flex: 1;
  text-align: right;
}

/* 提交按钮 */
.submit-container {
  margin-top: 32px;
}

.submit-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

:deep(.submit-btn.van-button--primary) {
  background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.3);
}

/* 通用样式 */
:deep(.van-field__label) {
  color: #333;
  font-weight: 500;
}

:deep(.van-field--required .van-field__label::before) {
  color: #ee0a24;
}

:deep(.van-popup) {
  border-radius: 16px 16px 0 0;
}

:deep(.van-picker__toolbar) {
  border-radius: 16px 16px 0 0;
}

/* 章节选择器样式 */
/* .chapter-picker-popup {
  :deep(.van-popup) {
    max-height: 80vh;
  }
} */

.chapter-picker-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  background: white;
}

.picker-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.picker-header h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.chapter-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.chapter-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.chapter-checkbox {
  margin-bottom: 8px;
}

:deep(.chapter-checkbox .van-checkbox__label) {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.time-settings {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #dee2e6;
}

.time-settings .time-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.time-settings .time-label {
  font-size: 14px;
  color: #666;
  margin-right: 12px;
  min-width: 80px;
}

.time-field {
  flex: 1;
  background: white;
  border-radius: 6px;
}

:deep(.time-field .van-field__control) {
  padding: 8px 12px;
  font-size: 14px;
}

.picker-footer {
  display: flex;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #eee;
  background: #f8f9fa;
}

.cancel-btn {
  flex: 1;
  height: 44px;
  border: 1px solid #ddd;
  background: white;
  color: #666;
}

.confirm-btn {
  flex: 2;
  height: 44px;
  background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
  border: none;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .setting-row {
    flex-direction: column;
    gap: 16px;
  }

  .time-item,
  .select-item {
    padding: 10px 12px;
  }

  .chapter-picker-container {
    height: 85vh;
  }

  .time-settings .time-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .time-settings .time-label {
    min-width: auto;
  }
}
</style>