<template>
  <view class="object_page" :style="{ 'padding-bottom': pageType === 2 ? '30rpx' : '' }">
    <BackBar :title="pageType === 2 ? '选择发送对象' : '发送对象'" />
    <view class="patriarch">
      <view class="send_object">
        <!-- 任务完成状态过滤 -->
        <view v-if="pageType === 1" class="status_list">
          <view
            v-for="(i, idx) in taskStatusOpt"
            :key="idx"
            :class="{ status_item: true, active_status: i.status === activeStatus }"
            @click="filterStatus(i)"
          >
            <text>{{ i.text }}</text>
          </view>
        </view>
        <Empty v-if="pageStatus === 'empty'" />
        <view v-else :style="{ 'margin-top': pageType === 2 ? '30rpx' : '16rpx' }">
          <view v-for="(i, idx) in childrenList" :key="idx" class="object_item">
            <view class="left">
              <template v-if="pageType === 1">
                <view
                  v-if="i.status === 0 && taskType === 1"
                  class="label"
                  @click="handleSingleCheck(i)"
                >
                  <image
                    v-if="i.checked"
                    class="checked"
                    :src="`${OSS_URL}/iconfont/checked.png`"
                    mode=""
                  >
                  </image>
                  <text v-else class="checkbox"></text>
                </view>
              </template>
              <view v-else class="label" @click="handleSingleCheck(i)">
                <image
                  v-if="i.checked"
                  class="checked"
                  :src="`${OSS_URL}/iconfont/checked.png`"
                  mode=""
                >
                </image>
                <text v-else class="checkbox"></text>
              </view>
              <view class="name">{{ i.childName }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view v-if="pageType === 2" class="footer">
      <button class="cancel" @click="handleCancel">取消</button>
      <button class="confirm" @click="handleConfirm">确认</button>
    </view>
    <CustomPopup
      v-model="showFinishPopup"
      titleText="完成提示"
      @handleConfirmBtn="handleConfirmFinish"
      @handleCancelBtn="handleCancelFinish"
    >
      <view class="popup_box">是否确认完成？</view>
    </CustomPopup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import Empty from '@/components/Empty/index.vue';
import CustomPopup from '@/components/CustomPopup/index.vue';
import { updateTaskStatusApi, getParentBindChildApi, getFamilyTaskStuApi } from '@/api';
import { user } from '@/store';
const { userInfo } = storeToRefs(user());
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const pageStatus = ref('');
const taskType = ref(); // 任务类型 0-系统任务 1-自定义任务
const taskStatusOpt = ref([
  {
    status: 0,
    text: '进行中',
  },
  {
    status: 1,
    text: '已完成',
  },
]);
const activeStatus = ref(0);
const taskStatusInfo = ref({
  taskId: '',
  status: 0,
});
const showFinishPopup = ref(false);

const checkedList = ref([]); // 选中值

const pageType = ref<number>(); // 1查看 2编辑
const childrenList = ref([]); // 家长孩子
const page = ref({
  current: 1,
  size: 10,
});
// 完成状态过滤
function filterStatus(i) {
  taskStatusInfo.value.status = i.status;
  activeStatus.value = i.status;
  fetchStudentTaskStatus();
}
// 单选
function handleSingleCheck(i) {
  let id = i.childId;
  if (pageType.value === 1) {
    taskStatusInfo.value.status = 1;
    showFinishPopup.value = true;
  }
  i.checked = !i.checked;
  if (i.checked) {
    checkedList.value.push(id);
  } else {
    checkedList.value.splice(checkedList.value.indexOf(id), 1);
  }
}

// 确认完成
async function handleConfirmFinish() {
  uni.showLoading({
    title: '正在完成...',
  });
  let res = await updateTaskStatusApi({
    ...taskStatusInfo.value,
    stuIdList: checkedList.value,
  });
  uni.hideLoading();
  if (res.code === 200) {
    uni.showToast({
      icon: 'none',
      title: '已完成',
    });
    taskStatusInfo.value.status = 0;
    fetchStudentTaskStatus();
    showFinishPopup.value = false;
  }
}
// 取消完成
function handleCancelFinish() {
  checkedList.value = [];
  childrenList.value = childrenList.value.map(item => {
    return {
      ...item,
      checked: false,
    };
  });
}

// 获取家长孩子数据
async function fetchChildrenInfo() {
  try {
    uni.showLoading({
      title: '加载中...',
    });
    const { data } = await getParentBindChildApi({
      parentId: userInfo.value.id,
      ...page.value,
    });
    for (let i in data.rows) {
      childrenList.value.push({
        ...data.rows[i],
        checked: checkedList.value.includes(data.rows[i].childId),
      });
    }
    pageStatus.value = childrenList.value.length === 0 ? 'empty' : '';
    uni.hideLoading();
  } catch (err) {
    console.log(err);
    uni.hideLoading();
  }
}
// 学生完成情况
async function fetchStudentTaskStatus() {
  try {
    uni.showLoading({
      title: '加载中...',
    });
    const { data } = await getFamilyTaskStuApi({
      ...taskStatusInfo.value,
    });
    childrenList.value = data;
    pageStatus.value = childrenList.value.length === 0 ? 'empty' : '';
    uni.hideLoading();
  } catch (err) {
    console.log(err);
    uni.hideLoading();
  }
}

// 确认
function handleConfirm() {
  uni.$emit('updateTaskSendObject', {
    list: JSON.stringify(checkedList.value),
  });
  uni.navigateBack();
}
// 取消
function handleCancel() {
  checkedList.value = [];
  uni.navigateBack();
}

onLoad(option => {
  pageType.value = Number(option.pageType);
  uni.setNavigationBarTitle({
    title: pageType.value === 1 ? '发送对象' : '选择发送对象',
  });
  if (pageType.value === 1) {
    // 查看
    let details = JSON.parse(decodeURIComponent(option.details));
    taskType.value = details.customTask;
    taskStatusInfo.value.taskId = details.id;
    fetchStudentTaskStatus();
  } else {
    checkedList.value = JSON.parse(option.checkedList);
    fetchChildrenInfo();
  }
});
</script>

<style lang="scss" scoped>
.object_page {
  .teacher {
    .tab_fixed {
      position: fixed;
      top: 0;
      z-index: 1;
    }

    .more_checked {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx 24rpx 30rpx;
      background-color: #fff;
      box-sizing: border-box;
    }

    .all {
      display: block;
      margin: 0 8rpx 0 0;
      color: #333;
      font-size: 30rpx;
      font-weight: 500;
    }

    .all_checked {
      color: #615dff;
    }

    .filter_box {
      margin-bottom: 16rpx;
    }

    .class_more_checked {
      display: flex;
      align-items: center;
      padding: 30rpx 0 0 0;
    }
  }

  .label {
    width: 30rpx;
    height: 30rpx;
    margin-right: 16rpx;

    .checkbox {
      display: block;
      width: 100%;
      height: 100%;
      border-radius: 6rpx;
      border: 1rpx solid #ddd;
      box-sizing: border-box;
    }

    .checked {
      display: block;
      width: 100%;
      height: 100%;
    }

    .disabled_check {
      background-color: #f9f9fb;
    }
  }

  .send_object {
    .status_list {
      height: 84rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #fff;

      .status_item {
        display: inline-block;
        color: #a9aab5;
        font-size: 28rpx;
        font-weight: 400;
        line-height: 48rpx;

        &:first-child {
          margin-right: 200rpx;
        }
      }

      .active_status {
        position: relative;
        color: #0a1f13;
        font-size: 32rpx;
        font-weight: 500;
        &::after {
          content: '';
          display: block;
          position: absolute;
          bottom: -18rpx;
          left: 50%;
          transform: translateX(-50%);
          background-color: #615dff;
          border-radius: 8rpx;
          width: 30rpx;
          height: 8rpx;
        }
      }
    }

    .tip {
      display: flex;
      justify-content: flex-end;
      padding-top: 30rpx;

      &_icon {
        width: 30rpx;
        height: 30rpx;
      }
    }

    .object_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      padding: 36rpx 30rpx;
      border-bottom: 1rpx solid #eeeeee;
      box-sizing: border-box;
      color: #333;
      font-size: 30rpx;

      &:last-child {
        border-bottom: none;
      }

      .left {
        display: flex;
        align-items: center;
      }

      .right {
        font-size: 30rpx;

        .revocation {
          margin-right: 16rpx;
          color: #ff2828;
        }

        .unread {
          color: #615dff;
        }

        .been {
          color: #a9aab5;
        }
      }

      .name {
        line-height: 42rpx;
      }
    }
  }

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

    button::after {
      border: none;
    }

    .cancel {
      width: 230rpx;
      height: 90rpx;
      color: #615dff;
      background-color: #ececff;
    }

    .confirm {
      margin-left: 20rpx;
      height: 90rpx;
      width: 440rpx;
      color: #fff;
      background-color: #615dff;
    }
  }

  .popup_box {
    margin: 50rpx 0;
    box-sizing: border-box;
  }
}
</style>
