<template>
  <view class="page">
    <view class="back_bar"> <BackBar :title="pageTitle" custom @back="back" /></view>
    <view class="card">
      <wd-form :model="form">
        <wd-cell-group border>
          <wd-input
            v-model="user.userName"
            label="发送对象:"
            label-width="100px"
            readonly
            placeholder="请选择发送对象"
            required
          >
            <template #suffix>
              <wd-icon name="arrow-right" size="30rpx" color="#A9AAB5"></wd-icon>
            </template>
          </wd-input>
          <wd-input
            v-model="form.date"
            label="督学日期:"
            label-width="100px"
            prop="date"
            required
            readonly
            placeholder="请选择督学日期"
            @click="select('date')"
          >
            <template #suffix>
              <wd-icon name="arrow-right" size="30rpx" color="#A9AAB5"></wd-icon>
            </template>
          </wd-input>
        </wd-cell-group>
      </wd-form>
    </view>
    <view class="cell">
      <text class="cell-title">学习任务</text>
      <button class="add-btn" @click="addPlan">+添加</button>
    </view>
    <view v-for="(item, index) of planList" :key="index" class="card">
      <view v-if="planList.length > 1 || index > 0" class="delete-thin">
        <wd-icon
          name="delete-thin"
          size="30rpx"
          color="#A9AAB5"
          @click="removePlan(index)"
        ></wd-icon>
      </view>
      <wd-form :model="item">
        <wd-cell-group border>
          <wd-cell title="督学时段" center title-width="100px" required>
            <template #default>
              <view class="input-row">
                <wd-input
                  v-model="item.inspectorTimeStart"
                  readonly
                  placeholder="开始时间"
                  no-border
                  style="width: 110rpx"
                  @click="select('rangeDate', index, 'start')"
                />
                <text class="separator">-</text>
                <wd-input
                  v-model="item.inspectorTimeEnd"
                  readonly
                  no-border
                  placeholder="结束时间"
                  style="width: 110rpx"
                  @click="select('rangeDate', index, 'end')"
                />
                <wd-icon
                  class="right-arrow"
                  name="arrow-right"
                  size="30rpx"
                  color="#A9AAB5"
                ></wd-icon>
              </view>
            </template>
          </wd-cell>
          <wd-cell title="计划任务:" title-width="100px" required center>
            <template #default>
              <view class="plan-row" @click="select('plan', index)">
                <view v-if="!item.subjectName" class="placeholder">请选择</view>
                <view v-else class="sub-detail">
                  <text class="subject-name">{{ item.subjectName }}</text>
                  <text :class="['tag', tagClass[item.taskType]]">{{
                    tagName[item.taskType]
                  }}</text>
                  <text v-if="item.taskType === 0" class="subject-detail"
                    >观看学习视频：《{{ item.chapterName }}》<text v-if="item.courseTimeName"
                      >《{{ item.courseTimeName }}》的视频</text
                    >
                  </text>
                  <text v-if="item.taskType === 1" class="subject-detail"
                    >完成章节练习{{ item.num }}次
                  </text>
                  <text v-if="item.taskType === 2" class="subject-detail"
                    >AI精准学{{ item.num }}次
                  </text>
                  <text v-if="item.taskType === 3" class="subject-detail"
                    >语感训练{{ item.num }}次
                  </text>
                </view>
                <wd-icon
                  class="right-arrow"
                  name="arrow-right"
                  size="30rpx"
                  color="#A9AAB5"
                ></wd-icon>
              </view>
            </template>
          </wd-cell>
        </wd-cell-group>
      </wd-form>
    </view>
    <view class="footer">
      <button class="footer-btn" @click="submitPublish">发布</button>
    </view>
    <Picker
      v-model="showStuPopup"
      :pickList="columns"
      title="选择学科"
      :pickVal="[
        columns.findIndex(e => e.value === +plan?.row?.subjectId) !== -1
          ? columns.findIndex(e => e.value === +plan?.row?.subjectId)
          : 0,
      ]"
      @confirm="confirmSelect"
    />
    <DatePicker
      v-model="showDatePicker"
      :canlender="canlenderList"
      :currentDay="form.date"
      @handleConfirmBtn="handleConfirm"
    >
    </DatePicker>
    <DateTimePicker
      v-model="showDateTimePicker"
      :titleText="titleText"
      :minHour="minHour"
      :minMinute="minMinute"
      :maxMinute="maxMinute"
      :maxHour="maxHour"
      :rangeType="rangeType"
      @handleConfirmBtn="confirmDateTime"
    />
    <CustomPopup
      v-model="showRemovePopup"
      titleText="温馨提示"
      cancelBtnText="取消"
      @handleConfirmBtn="removeConfirm"
    >
      <view class="tips-content">确定删除该任务?</view>
    </CustomPopup>
  </view>
</template>
<script setup lang="ts">
import { onLaunch, onShow, onHide, onLoad } from '@dcloudio/uni-app'
import { onMounted, reactive, ref, computed } from 'vue'
import Picker from './components/picker.vue'
import DatePicker from './components/datePicker.vue'
import DateTimePicker from './components/dateTimePicker.vue'
import CustomPopup from '@/components/CustomPopup/index.vue'
import { getCourseData, getSubject, publishPlan, getStuPlan } from '@/api/modules/inspector'
import dayjs from 'dayjs'
import { getCache } from '@/utils'
import db from '@/utils/db'
const pageTitle = ref('')
const minHour = ref<number>(0)
const minMinute = ref<number>(0)
const maxHour = ref<number>(23)
const maxMinute = ref<number>(59)
const form = ref<any>({})
const plan = ref<any>({})
const user = ref<any>({})
const showStuPopup = ref(false)
const showDatePicker = ref(false)
const showRemovePopup = ref(false)
const showDateTimePicker = ref(false)
const studyPlanIndex = ref(0) // 记录选中的任务序号
const currentType = ref('') // 当前选项类型
const canlenderList = ref<any[]>([])
const subjectData = ref<any[]>([])
const titleText = ref('')
const rangeType = ref('start')
const tagClass = {
  0: 'yellow',
  1: 'yellow',
  2: 'blue',
  3: 'red',
}
const tagName = {
  0: '自由学',
  1: '自由学',
  2: '精准学',
  3: '语感训练',
}
// 选中计划任务
const planList = ref<any[]>([])
const stuList = ref([])
const columns = computed(() => {
  return currentType.value === 'plan' ? subjectData.value : []
})

// 选择对象
function select(type: string, index?: number, dateType?: string) {
  currentType.value = type
  studyPlanIndex.value = index
  switch (type) {
    case 'stundent':
      showStuPopup.value = true
      break
    case 'plan':
      showStuPopup.value = true
      break
    case 'date':
      if (!user.value.courseDate) {
        showDatePicker.value = true
      }
      break
    case 'rangeDate':
      if (dateType === 'start') {
        titleText.value = '开始时间'
        rangeType.value = 'start'
        setRange()
      } else {
        titleText.value = '结束时间'
        rangeType.value = 'end'
        setRange()
      }
      showDateTimePicker.value = true
      break
  }
}
function setRange() {
  let minute = 0
  let hour = 0

  const key = rangeType.value === 'start' ? 'inspectorTimeEnd' : 'inspectorTimeStart'
  const time = planList.value[studyPlanIndex.value]?.[key].split(':') || []
  minute = Number(time?.[1] || 0)
  hour = Number(time?.[0] || 0)

  if (rangeType.value === 'start') {
    if (time.length === 2) {
      minute = minute - 1 > 0 ? minute - 1 : 1
    } else {
      hour = 23
      minute = 58
    }
    maxHour.value = hour
    maxMinute.value = minute
  } else {
    minute = minute + 1
    minHour.value = hour
    minMinute.value = minute
    maxHour.value = 23
    maxMinute.value = 59
  }
}
// 选择确认
function confirmSelect(val: any) {
  let row = planList.value[studyPlanIndex.value]
  if (currentType.value === 'plan') {
    row.subjectId = val.value
    row.subjectName = val.name
    row.gradeId = user.value.gradeId
    row.subjectId = val.value
    uni.setStorageSync('plan', {
      planList: planList.value,
      userId: user.value.userId,
      index: studyPlanIndex.value,
      row: row,
      date: form.value.date,
      courseId: form.value.courseId,
    })
    uni.navigateTo({ url: '/pages/inspector/releasePlan/selectPlan' })
  }
  showStuPopup.value = false
}
function addPlan() {
  planList.value.push({})
}
function removePlan(index: number) {
  showRemovePopup.value = true
  studyPlanIndex.value = index
}
// 日期确认
function handleConfirm(row: any) {
  form.value.date = row.courseDate
  form.value.courseId = row.courseId

  //
}
// 时间确认
function confirmDateTime(date: string) {
  let row = planList.value[studyPlanIndex.value]
  if (rangeType.value === 'start') {
    row.inspectorTimeStart = date
  } else if (rangeType.value === 'end') {
    row.inspectorTimeEnd = date
  }
}
function removeConfirm() {
  planList.value.splice(studyPlanIndex.value, 1)
  showRemovePopup.value = false
}
// 获取课表日历
async function getDate() {
  const { code, data } = await getCourseData({ id: user.value.userId })
  if (code === 200) {
    canlenderList.value = data || []
  }
}
// 获取学科
async function getSubjectList() {
  const { code, data } = await getSubject({ gradeId: user.value.gradeId })
  if (code === 200) {
    subjectData.value = data.map((item: any) => {
      return {
        name: item.subject,
        value: item.subjectId,
      }
    })
  }
}
// 获取计划
async function getStuPlanData() {
  try {
    uni.showLoading({ title: '加载中...' })
    const { code, data } = await getStuPlan({
      userId: user.value.userId,
      courseDate: user.value.courseDate ?? '',
    })
    uni.hideLoading()
    if (code === 200) {
      form.value.courseId = data.courseId ? data.courseId : plan.value.courseId
      form.value.date = data.courseDate
        ? dayjs(data.courseDate).format('YYYY-MM-DD')
        : plan.value.date

      if (data.tasks && Object.keys(plan.value).length === 0) {
        planList.value = data.tasks.map(item => {
          const taskInfo = JSON.parse(item.taskInfoJson)
          return {
            ...taskInfo,
            ...item,
            id: item.id,
            inspectorTimeStart: dayjs(item.inspectorTimeStart).format('HH:mm'),
            inspectorTimeEnd: dayjs(item.inspectorTimeEnd).format('HH:mm'),
          }
        })
        const storegePlan = {
          index: 0,
          date: form.value.date,
          courseId: form.value.courseId,
          planList: planList.value,
          row: planList.value[0],
        }
        plan.value = storegePlan
        uni.setStorageSync('plan', storegePlan)
      } else {
        uni.removeStorageSync('plan')
      }
    }
  } catch (error) {
    uni.hideLoading()
  }
}
// 确认发布
async function submitPublish() {
  const fields = ['chapterId', 'bookId', 'courseTimeId', 'inspectorTimeStart', 'inspectorTimeEnd']
  let valid = true
  const tasks = planList.value.map(item => {
    if (item.taskType >= 0) {
      if ([0, 1].includes(item.taskType)) {
        fields.forEach(field => {
          if (!item[field]) valid = false
        })
      }
    } else {
      valid = false
    }

    return {
      ...item,
      inspectorTimeEnd: item.inspectorTimeEnd
        ? form.value.date + ' ' + item.inspectorTimeEnd + ':00'
        : undefined,
      inspectorTimeStart: item.inspectorTimeStart
        ? form.value.date + ' ' + item.inspectorTimeStart + ':00'
        : undefined,
    }
  })

  if (!valid) {
    return uni.showToast({
      title: '请确认学习任务中的教材/章节/知识点/督学时段是否完整',
      icon: 'none',
    })
  }
  try {
    uni.showLoading({ title: '发布中...' })
    const params = {
      courseId: form.value.courseId,
      tasks: tasks,
    }
    const { code } = await publishPlan(params)
    uni.hideLoading()
    if (code === 200) {
      uni.showToast({
        title: '发布成功',
      })
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/inspector/student-detail/index?orderId=${user.value.orderId}&courseDate=${form.value.date}`,
        })
      }, 1500)
      reload()
    }
  } catch (error) {
    uni.hideLoading()
  }
}
function reload() {
  uni.removeStorageSync('plan')
  uni.removeStorageSync('user')
}
const studentDetail = ref()
const back = () => {
  uni.navigateTo({
    url: `/pages/inspector/student-detail/index?orderId=${studentDetail.value.orderId}&courseDate=${studentDetail.value.courseDate}`,
  })
  reload()
}
window.addEventListener('popstate', event => {
  reload()
})
onMounted(() => {
  user.value = uni.getStorageSync('user') || {}
  getStuPlanData()
  getSubjectList()
  getDate()
})
onShow(() => {
  studentDetail.value = db.get('student_detail')
  plan.value = uni.getStorageSync('plan') || {}
  planList.value = plan.value.planList || [{}]
  plan.value.date && (form.value.date = plan.value.date)
})
onLoad(option => {
  pageTitle.value = Number(option.type) === 1 ? '修改计划' : '发布计划'
  uni.setNavigationBarTitle({
    title: Number(option.type) === 1 ? '修改计划' : '发布计划',
  })
})
</script>
<style lang="scss" scoped>
.page {
  padding: 0 30rpx 102rpx 30rpx;
  box-sizing: border-box;
  .back_bar {
    margin-bottom: 30rpx;
  }
}
.delete-thin {
  text-align: right;
  padding-bottom: 20rpx;
  box-sizing: border-box;
  margin-right: 30rpx;
  border-bottom: 1rpx solid #f6f6f6;
}
.card {
  border-radius: 20rpx;
  background: #fff;
  padding: 10rpx 0;
  box-sizing: border-box;
  margin-bottom: 30rpx;
  .is-cell {
    padding: 27rpx 30rpx;
  }
  :deep(.wd-input__label) {
    font-size: 30rpx;
    font-weight: 500;
  }
}
.cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 40rpx 0 10rpx 0;
  .cell-title {
    font-size: 30rpx;
    color: #333;
    line-height: 45rpx;
  }
  .add-btn {
    height: 54rpx;
    background: #615dff;
    border-radius: 20rpx;
    color: #fff;
    font-size: 30rpx;
    line-height: 54rpx;
    margin: 0;
    padding: 0 28rpx;
  }
}
.footer {
  position: fixed;
  bottom: 0;
  height: 122rpx;
  width: 100vw;
  left: 0;
  padding-top: 16rpx;
  box-sizing: border-box;
  background: #fff;
  border-top: 1rpx solid #f6f6f6;
  .footer-btn {
    margin: auto;
    width: 440rpx;
    height: 90rpx;
    background: #615dff;
    font-size: 30rpx;
    line-height: 90rpx;
    color: #fff;
    font-weight: 600;
    display: block;
  }
}
.tips-content {
  color: #0a1f13;
  font-size: 32rpx;
  margin: 50rpx 0;
}
.input-row {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
  .right-arrow {
    position: absolute;
    right: 0;
  }
  .separator {
    margin: 0 20rpx 0 10rpx;
  }
}
.plan-row {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
  .right-arrow {
    position: absolute;
    right: 0;
  }
  .sub-detail {
    width: 90%;
    text-align: left;
    .subject-name {
      font-size: 30rpx;
      font-weight: 500;
      color: #0a1f13;
      margin-right: 8rpx;
    }
    .tag {
      padding: 0 10rpx;
      font-size: 22rpx;
      line-height: 30rpx;
      border-radius: 6rpx;
      color: #fff;
      margin: 0 8rpx;
    }
    .yellow {
      background: #ffa65d;
    }
    .blue {
      background: #4fd6ee;
    }
    .red {
      background: #ff91a1;
    }
    .subject-detail {
      word-break: break-all;
    }
  }
}
.placeholder {
  color: #bfbfbf;
}
</style>
