<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div>
        <el-card shadow="never">
          <template #header>
            <el-page-header @back="Cancel">
              <template #content>
                <span class="text-large font-600 mr-3"> 新增学习计划 </span>
              </template>
            </el-page-header>
          </template>
          <el-form ref="form" :model="planDialog.form" :rules="planDialog.rules" label-width="170px">
            <el-form-item label="计划名称：" prop="planName">
              <el-input v-model="planDialog.form.planName" placeholder="请输入计划名称"></el-input>
            </el-form-item>
            <el-form-item label="计划执行时间：" prop="date">
              <el-date-picker
                v-model="planDialog.form.date"
                :disabled-date="disabledDate"
                end-placeholder="结束日期"
                placeholder="选择日期时间"
                range-separator="至"
                start-placeholder="开始日期"
                style="flex: 1"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="学习目标：" prop="studyTarget">
              <el-input v-model="planDialog.form.studyTarget" cl placeholder="请输入学习目标"></el-input>
            </el-form-item>
            <el-form-item :rules="{required: true}" label="学习内容：">
              <div class="content-main">
                <div v-for="(item, index) in planDialog.form.content" :key="index" class="content-list">
                  <el-form-item :prop="`content[${index}][classify]`" :rules="planDialog.rules.classify" label=""
                                label-width="0">
                    <el-select v-model="item.classify" @change="getCourseList(item.classify, index)" placeholder="请选择课程分类">
                      <el-option v-for="e in classIfyLists" :label="e.label" :value="e.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item :prop="`content[${index}][courseName]`" :rules="planDialog.rules.courseName" label=""
                                label-width="0">
                    <el-select v-model="item.courseName" placeholder="请选择课程">
                      <el-option v-for="e in item.courseLists" :label="e.label" :value="e.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <div class="list-btn">
                    <el-icon size="32px" @click="plus(index)">
                      <CirclePlus />
                    </el-icon>
                    <el-icon v-show="planDialog.form.content.length > 1" size="32px" @click="minus(index)">
                      <Remove />
                    </el-icon>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>

          <div style="text-align: right">
            <el-button @click="Cancel">取消</el-button>
            <el-button type="primary" @click="ConfirmLeave">确认</el-button>
          </div>
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { PlanSubmit } from '@/api/study/studyPlan';
import { StateData } from '@/api/study/studyPlan/types';
import { listLearningCourse } from '@/api/study/lesson';

const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { course_type } = toRefs<any>(proxy?.useDict('course_type'));

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};
const emit = defineEmits(['update']);
const planDialog = ref<StateData>({
  form: {
    planName: '',
    date: [],
    studyTarget: '',
    content: [
      {
        classify: '',
        courseName: '',
        courseLists: []
      }
    ]
  },
  rules: {
    planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    date: [{ required: true, message: '请选择计划执行时间', trigger: 'change' }],
    studyTarget: [{ required: true, message: '请输入计划目标', trigger: 'blur' }],
    classify: [{ required: true, message: '请选择课程分类', trigger: 'change' }],
    courseName: [{ required: true, message: '请选择课程名称', trigger: 'change' }]
  }
});
const form = ref<ElFormInstance>(null);
const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace({
      path: '/study/studyPlan',
    });
  });
};
const ConfirmLeave = () => {
  form.value.validate(async (valid) => {
    if (!valid) return;
    const params: any = {
      ...planDialog.value.form,
      startTime: planDialog.value.form.date?.[0],
      endTime: planDialog.value.form.date?.[1],
      courseIds: planDialog.value.form.content.map(e => e.courseName)
    };
    delete params.date
    delete params.content
    let res = await PlanSubmit(params);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }
    ElNotification({
      title: '提示',
      message: `学习计划添加成功！`,
      type: 'success'
    });
    Cancel();
  });
};
const plus = (index: number) => {
  planDialog.value.form.content.splice(index + 1, 0, {
    classify: '',
    courseName: '',
    courseLists: []
  });
};
const minus = (index: number) => {
  planDialog.value.form.content.splice(index, 1);
};

const classIfyLists = computed(() => course_type.value);

const getCourseList = async (classifyId: any, index: number) => {
  planDialog.value.form.content[index].courseName = '';
  planDialog.value.form.content[index].courseLists = [];
  const res = await listLearningCourse({ pageNum: 1, pageSize: 10000000, status: '2', courseClassify: classifyId });
  planDialog.value.form.content[index].courseLists = res.rows.map(item => {
    return {
      label: item.courseName,
      value: item.id
    };
  });
};
</script>

<style lang="scss" scoped>
.el-form {
  max-width: 800px;
  width: 100%;
  padding-right: 68px;
}

.content-main {
  flex: 1;
  margin-right: -68px;

  .content-list {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 10px;

    &:not(:first-child) {
      margin-top: 10px;
    }

    :deep(.el-form-item) {
      flex: 1;
    }

    .list-btn {
      display: flex;
      align-items: center;
      gap: 10px;
      width: 58px;

      .el-icon {
        cursor: pointer;
      }
    }
  }
}
</style>
