<template>
  <div class="new-task">
    <div class="go-back">
      <el-button @click="goBack">
        <div class="go-back-button">
          <svg-icon icon-class="go-back" /><span>{{ $t('Key367') }}</span>
        </div>
      </el-button>
    </div>
    <div class="new-task-container">
      <div class="title">
        {{ $t('Key368') }}
      </div>
      <el-form ref="newTaskForm" :model="form" :rules="rules" label-width="150px" label-position="left">
        <el-form-item :label="$t('Key369')" prop="name">
          <el-input v-model="form.name" maxlength="26" />
        </el-form-item>

        <el-form-item v-if="!is_template" :label="$t('Key343')" prop="teacher_id">
          <el-select v-model="form.teacher_id">
            <el-option
              v-for="item in teacher_list"
              :key="item.teacher_id"
              :label="item.teacher_name"
              :value="item.teacher_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!is_template" :label="$t('Key370')">
          <div class="tag-list">
            <el-popover trigger="click" placement="bottom-start">
              <div class="student-list create-task">
                <ul>
                  <li
                    v-for="({ student_id, student_name, student_image_url }, i) in student_list"
                    :key="student_id"
                    :class="{ selected: custom_student_list.some((item) => item.student_id === student_id) }"
                    @click="selectStudent(i)"
                  >
                    <el-avatar icon="el-icon-user" :src="student_image_url" class="student_image" />
                    <span class="student_name nowrap-ellipsis">{{ student_name }}</span>
                    <svg-icon icon-class="check-mark-currentColor" class="svg-normal" />
                  </li>
                </ul>
              </div>

              <span slot="reference" class="add-button">
                <svg-icon icon-class="plus" />
              </span>
            </el-popover>

            <span
              v-for="{ student_id, student_name, student_image_url } in custom_student_list"
              :key="`tag-${student_id}`"
              class="student-tag"
            >
              <el-avatar :src="student_image_url" :size="32" />
              <span class="tag-name">{{ student_name }}</span>
              <svg-icon icon-class="closed" @click="deleteStudentItem(student_id)" />
            </span>
          </div>
        </el-form-item>

        <el-form-item :label="$t('Key271')">
          <el-date-picker v-model="form.begin_date" type="date" value-format="yyyy-MM-dd" />&nbsp;
          <el-select v-model="form.begin_date_hour" class="date-hour">
            <el-option v-for="item in hourArr" :key="item" :label="item" :value="item" />
          </el-select>
          <span> : </span>
          <el-select v-model="form.begin_date_minute" class="date-minute">
            <el-option v-for="item in minuteArr" :key="item" :label="item" :value="item" />
          </el-select>
          <span> ~ </span>
          <el-date-picker v-model="form.end_date" type="date" value-format="yyyy-MM-dd" />&nbsp;
          <el-select v-model="form.end_date_hour" class="date-hour">
            <el-option v-for="item in hourArr" :key="item" :label="item" :value="item" />
          </el-select>
          <span> : </span>
          <el-select v-model="form.end_date_minute" class="date-minute">
            <el-option v-for="item in minuteArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('Key371')">
          <el-input v-model="form.content" type="textarea" rows="5" maxlength="3000" resize="none" />
        </el-form-item>

        <el-form-item :label="$t('Key372')">
          <el-select v-model="form.teaching_type">
            <el-option v-for="item in type_list" :key="item.type" :label="item.name" :value="item.type" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <!-- 任务模式 直播 -->
          <div v-if="form.teaching_type === 10" class="task-template">
            <el-form :model="liveForm" label-width="100px" label-position="left">
              <el-form-item :label="$t('Key312')">
                <el-button @click="dialogVisible = true"> <i class="el-icon-plus"></i> {{ $t('Key373') }} </el-button>
                <div>
                  <el-tag
                    v-for="(item, i) in liveForm.coursewareInfo"
                    :key="item.courseware_id"
                    color="#fff"
                    closable
                    :title="item.courseware_name"
                    @close="closeCourse(i, 'live')"
                  >
                    <span>{{ item.courseware_name }}</span>
                  </el-tag>
                </div>
              </el-form-item>

              <el-form-item :label="$t('Key374')">
                <el-upload action="no" :http-request="upload" multiple :show-file-list="false" accept="*">
                  <el-button><svg-icon icon-class="upload" /> {{ $t('Key374') }}</el-button>
                </el-upload>
                <el-tag
                  v-for="(item, i) in liveForm.file_info_list"
                  :key="item.file_id"
                  color="#fff"
                  closable
                  :title="item.file_name"
                  @close="closeFile(i, liveForm.file_info_list)"
                >
                  <span>{{ item.file_name }}</span>
                </el-tag>
              </el-form-item>

              <el-form-item :label="$t('Key375')">
                <el-radio v-model="liveForm.courseware_visible_mode" :label="21">
                  {{ $t('Key377') }}
                </el-radio>
                <el-radio v-model="liveForm.courseware_visible_mode" :label="22">
                  {{ $t('Key376') }}
                </el-radio>
              </el-form-item>

              <el-form-item :label="$t('Key378')">
                <el-radio v-model="liveForm.zhibo_record_mode" :label="31">
                  {{ $t('Key380') }}
                </el-radio>
                <el-radio v-model="liveForm.zhibo_record_mode" :label="32">
                  {{ $t('Key379') }}
                </el-radio>
              </el-form-item>
            </el-form>
          </div>
          <!-- 任务模式 课件 -->
          <div v-else-if="form.teaching_type === 11" class="task-template">
            <el-form :model="courseForm" label-width="100px" label-position="left">
              <!-- TODO 多语言 等待翻译 -->
              <el-form-item label="教材任务">
                <el-button @click="dialogVisible = true"> <i class="el-icon-plus"></i> 添加教材 </el-button>
                <div>
                  <el-tag
                    v-for="(item, i) in courseForm.coursewareInfo"
                    :key="item.courseware_id"
                    color="#fff"
                    closable
                    :title="item.courseware_name"
                    @close="closeCourse(i, 'course')"
                  >
                    <span>{{ item.courseware_name }}</span>
                  </el-tag>
                </div>
              </el-form-item>

              <el-form-item :label="$t('Key634')">
                <el-radio v-for="item in mode_list" :key="item.code" v-model="courseForm.task_mode" :label="item.code">
                  {{ item.name }}
                </el-radio>
              </el-form-item>

              <el-form-item :label="$t('Key381')">
                <el-radio v-model="courseForm.is_enable_message" :label="true">
                  {{ $t('Key245') }}
                </el-radio>
                <el-radio v-model="courseForm.is_enable_message" :label="false">
                  {{ $t('Key246') }}
                </el-radio>
              </el-form-item>
            </el-form>
          </div>
          <!-- 任务模式 基础 -->
          <div v-else-if="form.teaching_type === 12" class="task-template">
            <el-form :model="basicForm" label-width="100px" label-position="left">
              <el-form-item :label="$t('Key152')">
                <el-upload action="no" :http-request="upload" multiple :show-file-list="false" accept="*">
                  <el-button><svg-icon icon-class="upload" /> {{ $t('Key152') }}</el-button>
                </el-upload>
                <el-tag
                  v-for="(item, i) in basicForm.file_info_list"
                  :key="item.file_id"
                  color="#fff"
                  closable
                  :title="item.file_name"
                  @close="closeFile(i, basicForm.file_info_list)"
                >
                  <span>{{ item.file_name }}</span>
                </el-tag>
              </el-form-item>

              <el-form-item :label="$t('Key330')">
                <el-radio v-model="basicForm.is_enable_homework" :label="true">
                  {{ $t('Key245') }}
                </el-radio>
                <el-radio v-model="basicForm.is_enable_homework" :label="false">
                  {{ $t('Key246') }}
                </el-radio>
              </el-form-item>

              <el-form-item :label="$t('Key381')">
                <el-radio v-model="basicForm.is_enable_message" :label="true">
                  {{ $t('Key245') }}
                </el-radio>
                <el-radio v-model="basicForm.is_enable_message" :label="false">
                  {{ $t('Key246') }}
                </el-radio>
              </el-form-item>
            </el-form>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button class="done" type="primary" @click="addTaskToCSItem">
            {{ $t('Key94') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--选择课件-->
    <SelectCourse :dialog-visible="dialogVisible" @selectCourse="selectCourse" @dialogClose="dialogClose" />
  </div>
</template>

<script>
import { GetTaskTeachingTypeList, GetTaskModeList, GetTeacherListByCourseID, GetCourseStudentList } from '@/api/select';
import { AddTaskToCSItem, GetTreeNodeInfo_BookChapterStruct, GetTaskInfo, UpdateTask, GetCSItem } from '@/api/course';
import { fileUpload } from '@/api/app';
import { fileTypeSizeLimit } from '@/utils/validate';

import SelectCourse from '@/components/select/SelectCourse.vue';

export default {
  name: 'NewTask',
  components: { SelectCourse },
  provide() {
    return {
      cs_item_id: this.cs_item_id
    };
  },
  data() {
    const validateTeacher = (rule, value, callback) => {
      if (this.form.teaching_type === 10 && !value && !this.is_template) {
        callback(new Error(this.$i18n.t('Key382')));
      } else {
        callback();
      }
    };
    const validateNmae = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error(this.$i18n.t('Key384')));
      } else {
        callback();
      }
    };
    const { params, query } = this.$route;
    const is_template = 'is_template' in query ? JSON.parse(query.is_template) : false;
    return {
      id: params.id,
      task_id: query.task_id,
      time_type: params.time_type,
      cs_item_id: params.curItemID,
      is_template,
      // 任务所属课节
      curItemID: params.curItemID,
      dialogVisible: false,
      cs_item_begin_time: '',
      cs_item_end_time: '',
      type_list: [],
      teacher_list: [],
      mode_list: [],
      student_list: [],
      custom_student_list: [],
      form: {
        name: '',
        teacher_id: '',
        begin_date: '',
        begin_date_hour: '00',
        begin_date_minute: '00',
        end_date: '',
        end_date_hour: '00',
        end_date_minute: '00',
        teaching_type: 12,
        content: ''
      },
      hourArr: [],
      minuteArr: [],
      rules: {
        name: { trigger: 'blur', validator: validateNmae },
        teacher_id: { trigger: 'blur', validator: validateTeacher }
      },
      liveForm: {
        coursewareInfo: [],
        file_info_list: [],
        courseware_visible_mode: 21,
        zhibo_record_mode: 32
      },
      courseForm: {
        coursewareInfo: [],
        task_mode: 'PRACTICE',
        is_enable_message: true
      },
      basicForm: {
        file_info_list: [],
        is_enable_homework: true,
        is_enable_message: true
      }
    };
  },
  created() {
    for (let i = 0; i < 60; i++) {
      let item = String(i);
      if (i < 10) item = `0${item}`;
      if (i < 24) this.hourArr.push(item);
      this.minuteArr.push(item);
    }

    this.init();
    if (this.task_id) {
      this.getTaskInfo();
    }
  },
  methods: {
    init() {
      GetTaskTeachingTypeList().then(({ type_list }) => {
        this.type_list = type_list;
      });
      if (!this.is_template) {
        GetTeacherListByCourseID({ course_id: this.id }).then(({ teacher_list }) => {
          this.teacher_list = teacher_list;
        });
      }
      GetTaskModeList().then(({ mode_list }) => {
        this.mode_list = mode_list;
      });
      GetCSItem({ id: this.cs_item_id }).then(({ begin_time, end_time }) => {
        this.cs_item_begin_time = begin_time;
        this.cs_item_end_time = end_time;
      });
      if (!this.is_template) {
        GetCourseStudentList({ course_id: this.id, audit_status_list: [1], pay_status: 1 }).then(({ student_list }) => {
          this.student_list = student_list;
        });
      }
    },

    addTaskToCSItem() {
      this.$refs.newTaskForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        const teaching_type = this.form.teaching_type;
        const data = {
          cs_item_id: this.cs_item_id,
          name: this.form.name,
          time_type: Number(this.time_type),
          teaching_type,
          begin_time:
            this.form.begin_date.length > 0
              ? `${this.form.begin_date} ${this.form.begin_date_hour}:${this.form.begin_date_minute}`
              : this.cs_item_begin_time,
          end_time:
            this.form.end_date.length > 0
              ? `${this.form.end_date} ${this.form.end_date_hour}:${this.form.end_date_minute}`
              : this.cs_item_end_time,
          teacher_id: this.form.teacher_id,
          content: this.form.content,
          custom_student_id_list: this.custom_student_list.map(({ student_id }) => student_id)
        };

        if (teaching_type === 10) {
          data['courseware_id_list'] = this.liveForm.coursewareInfo.map(({ courseware_id }) => courseware_id);
          data['file_id_list'] = this.liveForm.file_info_list.map(({ file_id }) => file_id);
          data['courseware_visible_mode'] = this.liveForm.courseware_visible_mode;
          data['zhibo_record_mode'] = this.liveForm.zhibo_record_mode;
          data['courseware_group_selected_list'] = this.liveForm.coursewareInfo.map(
            ({ courseware_id, group_id_selected_info }) => {
              return { courseware_id, group_id_selected_info };
            }
          );
        }

        if (teaching_type === 11) {
          data['courseware_id_list'] = this.courseForm.coursewareInfo.map(({ courseware_id }) => courseware_id);
          data['task_mode'] = this.courseForm.task_mode;
          data['is_enable_message'] = this.courseForm.is_enable_message;
          data['courseware_group_selected_list'] = this.courseForm.coursewareInfo.map(
            ({ courseware_id, group_id_selected_info }) => {
              return { courseware_id, group_id_selected_info: group_id_selected_info ?? '[]' };
            }
          );
        }

        if (teaching_type === 12) {
          data['file_id_list'] = this.basicForm.file_info_list.map(({ file_id }) => file_id);
          data['is_enable_homework'] = this.basicForm.is_enable_homework;
          data['is_enable_message'] = this.basicForm.is_enable_message;
        }

        if (this.task_id) {
          data['id'] = this.task_id;
          UpdateTask(data).then(() => {
            this.goBack();
          });
        } else {
          AddTaskToCSItem(data).then(() => {
            this.goBack();
          });
        }
      });
    },

    selectStudent(i) {
      const id = this.student_list[i].student_id;
      const list = this.custom_student_list;
      const index = list.findIndex(({ student_id }) => student_id === id);
      index === -1 ? list.push(this.student_list[i]) : list.splice(index, 1);
    },

    deleteStudentItem(id) {
      this.custom_student_list.splice(
        this.custom_student_list.findIndex(({ student_id }) => student_id === id),
        1
      );
    },

    goBack() {
      this.$router.push({
        path: `/create_course_step_table/old_create_task/${this.id}?is_template=${this.is_template}&curItemID=${this.curItemID}`
      });
    },

    upload(file) {
      if (fileTypeSizeLimit(file.file.name, file.file.size)) {
        return this.$message.warning(`${file.file.name}文件大小超出限制`);
      }

      fileUpload('Open', file).then(({ file_info_list }) => {
        const type = this.form.teaching_type;
        if (type === 10) {
          this.liveForm.file_info_list = this.liveForm.file_info_list.concat(file_info_list);
          return;
        }

        if (type === 12) {
          this.basicForm.file_info_list = this.basicForm.file_info_list.concat(file_info_list);
        }
      });
    },

    closeFile(i, arr) {
      arr.splice(i, 1);
    },

    // 选择课件
    dialogClose() {
      this.dialogVisible = false;
    },

    selectCourse(course_id, previewGroupId) {
      if (course_id.length === 0) {
        this.$message.warning(this.$t('Key385'));
        return;
      }

      const type = this.form.teaching_type;
      if (type === 10) {
        this.getTreeNodeInfo_BookChapterStruct(course_id, 'live', previewGroupId);
      }

      if (type === 11) {
        this.getTreeNodeInfo_BookChapterStruct(course_id, 'course', previewGroupId);
      }
      this.dialogVisible = false;
    },

    getTreeNodeInfo_BookChapterStruct(id, type, previewGroupId) {
      GetTreeNodeInfo_BookChapterStruct({ id }).then(({ name, id }) => {
        if (type === 'live') {
          this.liveForm.coursewareInfo.push({
            courseware_id: id,
            courseware_name: name,
            group_id_selected_info: previewGroupId
          });
        }
        if (type === 'course') {
          this.courseForm.coursewareInfo.push({
            courseware_id: id,
            courseware_name: name,
            group_id_selected_info: previewGroupId
          });
        }
      });
    },

    closeCourse(i, type) {
      const courseInfo = type === 'live' ? this.liveForm.coursewareInfo : this.courseForm.coursewareInfo;
      courseInfo.splice(i, 1);
    },

    getTaskInfo() {
      GetTaskInfo({ id: this.task_id }).then(
        ({
          begin_time,
          end_time,
          time_type,
          teaching_type,
          name,
          teacher_id,
          content,
          courseware_list,
          accessory_list,
          task_mode,
          is_enable_homework,
          is_enable_message,
          courseware_visible_mode,
          zhibo_record_mode,
          cs_item_begin_time,
          cs_item_end_time,
          is_custom_student,
          custom_student_list
        }) => {
          if (begin_time.length > 0) {
            const begin = begin_time.split(' ');
            this.form.begin_date = begin[0];
            const bTime = begin[1].split(':');
            this.form.begin_date_hour = bTime[0];
            this.form.begin_date_minute = bTime[1];
          }
          if (end_time.length > 0) {
            const end = end_time.split(' ');
            this.form.end_date = end[0];
            const eTime = end[1].split(':');
            this.form.end_date_hour = eTime[0];
            this.form.end_date_minute = eTime[1];
          }

          this.cs_item_begin_time = cs_item_begin_time;
          this.cs_item_end_time = cs_item_end_time;
          this.time_type = time_type;
          this.form.teaching_type = teaching_type;
          this.form.name = name;
          this.form.teacher_id = teacher_id;
          this.form.content = content;
          if (teaching_type === 10) {
            this.liveForm.coursewareInfo = courseware_list;
            this.liveForm.file_info_list = accessory_list;
            this.liveForm.courseware_visible_mode = courseware_visible_mode;
            this.liveForm.zhibo_record_mode = zhibo_record_mode;
          }

          if (teaching_type === 11) {
            this.courseForm.coursewareInfo = courseware_list;
            this.courseForm.task_mode = task_mode;
          }

          if (teaching_type === 12) {
            this.basicForm.file_info_list = accessory_list;
            this.basicForm.is_enable_homework = is_enable_homework === 'true';
            this.basicForm.is_enable_message = is_enable_message === 'true';
          }

          if (is_custom_student === 'true') this.custom_student_list = custom_student_list;
        }
      );
    }
  }
};
</script>

<style lang="scss">
@import '~@/styles/mixin';

.new-task {
  @include container;

  .go-back {
    margin-bottom: 16px;

    .el-button {
      padding: 7px 20px;
    }

    &-button {
      display: flex;
      width: 78px;
      font-size: 16px;
      line-height: 24px;
      color: #000;

      .svg-icon {
        width: 20px;
        height: 20px;
        margin-right: 10px;
      }
    }
  }

  &-container {
    width: 100%;
    padding: 24px 32px;
    background-color: #fff;

    .title {
      margin-bottom: 24px;
      font: {
        size: 18px;
        weight: 700;
      }
    }

    .el-form {
      .el-input,
      .el-textarea,
      .task-template {
        width: 640px;
      }

      .date-minute,
      .date-hour {
        width: 78px;

        > .el-input {
          width: 100%;
        }
      }

      .el-date-editor.el-input {
        width: 140px;
      }

      .tag-list {
        display: flex;
        flex-wrap: wrap;

        .add-button {
          display: inline-block;
          width: 40px;
          height: 40px;
          text-align: center;
          cursor: pointer;
          background-color: $basic-color;
          border-radius: 50%;

          .svg-icon {
            position: relative;
            top: -1px;
            width: 24px;
            height: 24px;
            vertical-align: middle;
          }
        }

        .student-tag {
          display: flex;
          align-items: center;
          height: 40px;
          padding: 4px 12px 4px 4px;
          margin: 0 0 8px 16px;
          border: 1px solid $border-color;
          border-radius: 20px;

          .tag-name {
            margin: 0 16px 0 8px;

            + .svg-icon {
              cursor: pointer;
            }
          }
        }
      }

      // 任务模板
      .task-template {
        padding: 24px 32px;
        background-color: #fbfbfb;
        border: 1px solid #d9d9d9;
        border-radius: 8px;

        .el-form-item:not(:first-child, :last-child) {
          margin: 20px 0;
        }

        .el-tag {
          margin-right: 16px;

          > span {
            display: inline-block;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: bottom;
          }
        }
      }

      .el-button.done {
        width: 120px;
      }
    }
  }
}
</style>

<style lang="scss">
.el-popover {
  padding: 8px 0;

  .student-list.create-task {
    width: 330px;
    height: 25vh;
    min-height: 240px;
    overflow: auto;

    ul {
      li {
        padding: 8px 24px;
        cursor: pointer;

        .student_image {
          margin-right: 16px;
          vertical-align: middle;
        }

        .student_name {
          display: inline-block;
          width: 68%;
          vertical-align: middle;
        }

        .svg-icon {
          vertical-align: middle;
          visibility: hidden;
        }

        &.selected {
          background-color: #dbdbdb;

          .svg-icon {
            color: #333;
            visibility: visible;
          }
        }
      }
    }
  }
}
</style>
