<template>
  <view class="task_item_page" :style="{ 'padding-bottom': pageType === 2 ? '202rpx' : '30rpx' }">
    <BackBar :title="pageType === 1 ? '查看任务' : '新增任务'" />
    <view class="task_form">
      <view class="form_item">
        <view class="form_item_label"> <text class="must">*</text>任务名称 </view>
        <template v-if="pageType === 1">
          <view class="input_bg show">
            {{ formData.title }}
          </view>
        </template>
        <template v-else>
          <view class="form_item_con" @click="chooseInputValue(1)">
            <text v-if="formData.title">{{ formData.title }}</text>
            <text v-else style="color: #a9aab5; font-size: 30rpx">请选择</text>
            <image :src="`${OSS_URL}/iconfont/down_arrow.png`" class="more_down" mode=""></image>
          </view>
          <text v-if="isEmpty.title" class="error">请填写任务名称</text>
        </template>
      </view>

      <view class="form_item">
        <view class="form_item_label"> <text class="must">*</text>任务有效期 </view>
        <view class="date_range">
          <text v-if="pageType === 1"
            >{{ dayjs(formData.startTime).format('YYYY.MM.DD') }}-{{
              dayjs(formData.endTime).format('YYYY.MM.DD')
            }}</text
          >
          <view v-else @click="chooseDateRange">
            <text v-if="formData.startTime && formData.endTime"
              >{{ dayjs(formData.startTime).format('YYYY.MM.DD') }}-{{
                dayjs(formData.endTime).format('YYYY.MM.DD')
              }}</text
            >
            <text v-else style="color: #a9aab5; font-size: 30rpx">请选择</text>
            <image :src="`${OSS_URL}/calendar_icon.png`" class="calendar_icon" mode=""></image>
          </view>
        </view>
        <view v-if="isEmpty.indate" class="error">请选择发送时间</view>
      </view>

      <view class="form_item">
        <view class="form_item_label"> <text class="must">*</text>发送时间 </view>
        <SelectTime
          :isEdit="pageType === 1 ? false : true"
          :time="formData.sendTime"
          @getSendTime="handleGetSendTime"
        />
        <view v-if="isEmpty.sendTime" class="error">请选择定时发送时间</view>
      </view>

      <view class="form_item">
        <view class="form_item_label"><text class="must">*</text>选择奖励</view>
        <SelectedAward
          :list="tempRewardList"
          :maxNum="2"
          :isEdit="pageType === 1 ? false : true"
          @handleConfirmBtn="handleChooseAward"
        />
        <view v-if="isEmpty.rewardList" class="error">请选择奖励</view>
      </view>

      <view class="form_item">
        <view class="form_item_label"> <text class="must">*</text>发送对象 </view>
        <view class="form_item_con" @click="chooseInputValue(2)">
          <template v-if="pageType === 1">
            <text>共计 {{ formData.stuNum }} 人</text>
          </template>
          <template v-if="pageType === 2">
            <text v-if="formData.stuIdList?.length > 0"
              >共计 {{ formData.stuIdList?.length }} 人</text
            >
            <text v-else style="color: #a9aab5; font-size: 30rpx">请选择</text>
          </template>
          <image :src="`${OSS_URL}/iconfont/down_arrow.png`" class="more_down" mode=""></image>
        </view>
        <view v-if="isEmpty.stuIdList" class="error">请选择发送对象</view>
      </view>
    </view>
    <view v-if="pageType === 2" class="footer">
      <button class="btn-primary" @click="submit">发送</button>
    </view>
    <!-- 有效期 -->
    <DatePicker ref="dateRef" v-model="timeArr" @confirm="confirmDateRange" />
  </view>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import DatePicker from '@/pages/mine/Components/DatePicker/index.vue';
import SelectTime from '@/pages/mine/Components/SelectTime/index.vue';
import SelectedAward from './selectedAward.vue';
import dayjs from 'dayjs';
import { addTaskApi } from '@/api';
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const dateRef = ref();
const timeArr = ref([]); // '2024-01-01', '2024-01-31'
const pageType = ref<number>(); // 1查看 2新增
// 内容是否为空
const isEmpty = ref({
  title: false,
  indate: false,
  sendTime: false,
  rewardList: false,
  stuIdList: false,
});

const tempRewardList = ref([]); // 临时存储奖励
const formData = ref({
  id: '',
  title: '',
  taskConfigId: undefined,
  targetNum: undefined,
  startTime: '',
  endTime: '',
  sendType: 1, // 1-立即发送 2-定时发送
  sendTime: '',
  rewardList: [],
  stuIdList: [],
});

// 选中奖励
function handleChooseAward(val) {
  tempRewardList.value = val;
  isEmpty.value.rewardList = tempRewardList.value.length === 0;
}
// 发送时间
function handleGetSendTime(val) {
  formData.value.sendType = val.sendType;
  formData.value.sendTime = val.sendTime;
  isEmpty.value.sendTime = formData.value.sendType === 1 ? false : !formData.value.sendTime;
}

function chooseInputValue(type) {
  switch (type) {
    case 1:
      // 选择任务
      uni.navigateTo({
        url: '/pages/mine/taskManage/taskConfigList',
      });
      break;
    case 2:
      uni.navigateTo({
        url: `/pages/mine/taskManage/patriarchSendObject?pageType=${
          pageType.value
        }&details=${encodeURIComponent(
          JSON.stringify(formData.value),
        )}&checkedList=${JSON.stringify(formData.value.stuIdList)}`,
      });

      break;
  }
}
// 选择有效期
function chooseDateRange() {
  dateRef.value && dateRef.value.open();
}

function confirmDateRange() {
  formData.value.startTime = timeArr.value[0];
  formData.value.endTime = timeArr.value[1];
  isEmpty.value.indate = !formData.value.endTime && !formData.value.startTime;
}
// 提交
async function submit() {
  isEmpty.value = {
    title: !formData.value.title,
    indate: !formData.value.startTime || !formData.value.endTime,
    sendTime: formData.value.sendType === 1 ? false : !formData.value.sendTime,
    rewardList: tempRewardList.value.length === 0,
    stuIdList: formData.value.stuIdList.length === 0,
  };
  if (
    isEmpty.value.title ||
    isEmpty.value.indate ||
    isEmpty.value.sendTime ||
    isEmpty.value.rewardList ||
    isEmpty.value.stuIdList
  )
    return;
  uni.showLoading({
    title: '添加中...',
  });
  formData.value.sendTime = formData.value.sendTime
    ? formData.value.sendTime.replace(/\//g, '-')
    : '';
  if (tempRewardList.value.length > 0) {
    for (let i in tempRewardList.value) {
      formData.value.rewardList[i] = {
        rewardId: tempRewardList.value[i].rewardId,
        rewardNum: tempRewardList.value[i].rewardNum,
      };
    }
  }
  let res = await addTaskApi(formData.value);
  uni.hideLoading();
  if (res.code === 200) {
    uni.navigateTo({
      url: '/pages/mine/taskManage/index',
    });
  }
}

onShow(() => {
  // 监听任务名称
  uni.$on('updateTask', data => {
    let chooseTask = JSON.parse(data.taskData);
    let num = chooseTask.targetNum ? chooseTask.targetNum : '';
    let unit = chooseTask.unit ? (chooseTask.unit === '次数' ? '次' : '分钟') : '';
    formData.value.title = chooseTask.name + num + unit;
    formData.value.taskConfigId = chooseTask.taskConfigId;
    formData.value.targetNum = chooseTask.targetNum ? chooseTask.targetNum : undefined;
    isEmpty.value.title = false;
  });
  // 监听发送对象
  uni.$on('updateTaskSendObject', data => {
    let chooseSendArr = JSON.parse(data.list);
    formData.value.stuIdList = chooseSendArr;
    isEmpty.value.stuIdList = formData.value.stuIdList.length === 0;
  });
});
onLoad(option => {
  pageType.value = Number(option.pageType);
  uni.setNavigationBarTitle({
    title: pageType.value === 1 ? '查看任务' : '新增任务',
  });
  if (pageType.value === 1) {
    // 查看
    formData.value = JSON.parse(decodeURIComponent(option.details));
    tempRewardList.value = formData.value.rewardList;
  }
});
onUnload(() => {
  uni.$off();
});
</script>

<style lang="scss" scoped>
.task_item_page {
  .task_form {
    margin: 30rpx 30rpx 0;
    padding: 30rpx 30rpx 40rpx 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    color: #333;
    background-color: #fff;
    font-size: 30rpx;

    .form_item {
      margin-bottom: 30rpx;

      &_label {
        margin-bottom: 16rpx;
        font-weight: 500;
      }

      .date_range {
        position: relative;
        padding: 24rpx 20rpx;
        box-sizing: border-box;
        height: 90rpx;
        background-color: #f9f9fb;
        border-radius: 16rpx;

        .calendar_icon {
          position: absolute;
          right: 20rpx;
          width: 48rpx;
          height: 48rpx;
        }
      }

      &_con {
        position: relative;
        padding: 24rpx 20rpx;
        box-sizing: border-box;
        height: 90rpx;
        background-color: #f9f9fb;
        border-radius: 16rpx;

        .more_down {
          position: absolute;
          right: 20rpx;
          width: 30rpx;
          height: 30rpx;
          transform: rotate(-90deg);
        }
      }

      .must {
        color: red;
      }

      .input_bg {
        height: 90rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
        background-color: #f9f9fb;
        border-radius: 16rpx;
      }

      .show {
        padding: 24rpx 20rpx;
      }

      .error {
        margin-top: 16rpx;
        font-size: 26rpx;
        color: #ff3d3d;
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: center;
    width: 100%;
    height: 172rpx;
    left: 0;
    box-sizing: border-box;
    background-color: #fff;
    border-top: 1rpx solid #eee;

    button::after {
      border: none;
    }

    .btn-primary {
      margin-top: 16rpx;
      box-sizing: border-box;
      width: 440rpx;
      height: 90rpx;
      background-color: #615dff;
      color: #ffffff;
      border-radius: 20rpx;
      font-size: 30rpx;
      line-height: 90rpx;
    }
  }
}
</style>
