<template>
  <isp-data-load :loading="loading" :empty="!planList || planList.length === 0">
    <isp-load-more :data="queryResult" @reload="loadMore">
      <wd-collapse v-model="collapseValue" accordion>
        <wd-collapse-item
          v-for="plan in planList"
          :key="plan.id"
          :name="plan.id + ''"
          custom-class="plan-item"
        >
          <template #title="{ expanded }">
            <view class="title-view">
              {{ dayjs(plan.date).format('MM月DD日') }}
            </view>
            <view class="right-icons">
              <view class="operates-view">
                <image src="@/static/svg/edit.svg" @click="editPlan(plan)" />
                <view>|</view>
                <image src="@/static/svg/Delete.svg" @click.stop="deletePlan(plan)" />
              </view>
              <wd-icon v-if="!expanded" name="arrow-down" size="30rpx"></wd-icon>
              <wd-icon v-else name="arrow-up" size="30rpx"></wd-icon>
            </view>
          </template>
          <view style="background-color: #fafcff">
            <isp-data-load :loading="false" :empty="!plan.dataList || plan.dataList.length === 0">
              <isp-plan-item v-for="item in plan.dataList" :key="item" :plan="item" />
            </isp-data-load>
          </view>
        </wd-collapse-item>
      </wd-collapse>
    </isp-load-more>
  </isp-data-load>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { inject, onMounted, type Ref, ref } from 'vue';
import { deletePlanRequest, queryStudyPlanList } from '@/api/inspector/student-detail';
import { formatTaskTypeNotePrefix, TASK_TYPE } from '@/components/inspector/plan-item';
import IspDataLoad from '@/components/inspector/isp-data-load.vue';
import IspLoadMore from '@/components/inspector/isp-load-more.vue';
import { useMessage } from '@/uni_modules/wot-design-uni';

const studentInfo = inject<Ref<any>>('studentInfo');
const routeData = inject<Ref<anyObj>>('routeData');
const collapseValue = ref();
const loading = ref(false);
const { confirm } = useMessage();

const queryResult = ref({});
const planList = ref([]);
const page = ref({
  current: 1,
  total: 0,
});
const loadMore = () => {
  if (Number(page.value.total) > planList.value.length) {
    page.value.current++;
    queryList();
  }
};
const queryList = async () => {
  loading.value = true;
  try {
    const { data } = await queryStudyPlanList({
      current: page.value.current,
      userId: studentInfo.value.userId,
    });
    page.value.total = data.total;

    queryResult.value = data;
    let arr = (data.records ?? []).map(dataItem => {
      return {
        id: dataItem.planId,
        date: dayjs(dataItem.courseDate).format('YYYY-MM-DD'),
        times: '19:00~20:00',
        hasData: dataItem.tasks && dataItem.tasks.length > 0,
        dataList: (dataItem.tasks ?? []).map((task, index) => {
          const taskInfo = JSON.parse(task.taskInfoJson);
          const _type = TASK_TYPE[taskInfo.taskType];
          return {
            order: index + 1,
            finished:
              taskInfo.taskType === 0
                ? Number(taskInfo.progress) > 0.8
                : taskInfo.finishedNum >= taskInfo.num,
            courseName: taskInfo.subjectName,
            label: _type.label,
            bgColor: _type.bgColor,
            progressText:
              taskInfo.taskType === 0
                ? Number(taskInfo.progress) > 0.8
                  ? '1/1'
                  : '0/1'
                : `${taskInfo.finishedNum}/${taskInfo.num}`,
            time: `${dayjs(taskInfo.inspectorTimeStart).format('HH:mm')}-${dayjs(
              taskInfo.inspectorTimeEnd,
            ).format('HH:mm')}`,
            note: formatTaskTypeNotePrefix(_type.notePrefix, taskInfo),
          };
        }),
      };
    });
    planList.value.push(...arr);
  } finally {
    loading.value = false;
  }
};

const deletePlan = (plan: any) => {
  uni.showModal({
    title: '温馨提示',
    content: `确定删除${dayjs(plan.date).format('MM月DD日')}日的学习计划？`,
    success: async res => {
      if (res.confirm) {
        try {
          await deletePlanRequest(plan.id);
          queryList();
        } catch (e) {}
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};

const editPlan = plan => {
  uni.setStorageSync('user', {
    userId: studentInfo.value.userId,
    userName: `${studentInfo.value.name} ${studentInfo.value.gradeName}`,
    gradeId: studentInfo.value.gradeId,
    planId: plan.id,
    orderId: routeData.value.orderId,
    lastDate: routeData.value.courseDate,
    courseDate: plan.date,
  });
  uni.navigateTo({
    url: `/pages/inspector/releasePlan/index?type=1`,
  });
};

onMounted(() => {
  queryList();
});
</script>

<style scoped lang="scss">
.plan-item {
  :deep(.wd-collapse-item__body) {
    padding: 30rpx 0;
    .plan-view-item {
      padding: 20rpx 30rpx;
    }
  }
}

.title-view {
  color: #0a1f13;
  font-size: 30rpx;
  font-style: normal;
  font-weight: 500;
  line-height: normal;
}

.right-icons {
  display: flex;
  gap: 40rpx;
  align-items: center;

  .operates-view {
    display: flex;
    gap: 16rpx;
    color: #dedfe9;
    place-content: center;
    align-items: center;

    & > image {
      width: 30rpx;
      height: 30rpx;
    }
  }
}
</style>
