<template>
  <div class="container">
    <div class="timer">
      <van-cell title="日志日期" :value="today" @click="calendarShow = true" />
      <!-- <van-calendar
        v-model:show="calendarShow"
        @confirm="onConfirm"
        :min-date="minDate"
        :max-date="maxDate"
      /> -->
    </div>
    <div class="title">今日工作</div>
    <van-field
      v-model="formData.reportContent"
      rows="5"
      autosize
      type="textarea"
      placeholder=""
    />
    <div class="title">
      工作量分配 {{ totalTime ? `（总耗时${totalTime}小时）` : "" }}
    </div>
    <ProjectList type="daily" :onChange="projectChange" />
    <div class="title">接收人</div>
    <SelectUser v-model="formData.receiveUserIds" />
    <div class="blank-line"></div>
    <div class="send-btn-group" v-if="formData.isUpdate">
      <van-button type="primary" block @click="onSubmit(false)"
        >更新</van-button
      >
    </div>
    <div class="send-btn-group" v-else>
      <van-button type="success" block class="send-btn" @click="onSubmit(true)"
        >暂存</van-button
      >
      <van-button type="primary" block class="send-btn" @click="onSubmit(false)"
        >发送</van-button
      >
    </div>
  </div>
</template>
<script lang="ts" setup>
/**
 * @description 日志
 */
import moment from "moment";
import { reactive, watch } from "vue";
import { showSuccessToast, showToast } from "vant";
import SelectUser from "@/components/UserSelect.vue";
import ProjectList from "../components/ProjectList.vue";
import { getUserInfo } from "@/utils/tools";
import { http } from "../http";
import { IReport } from "../interface";
import { onSubmitCheck } from "../service";
import PubsubService from "@/utils/PubsubService";
interface FormData {
  reportContent: string; // 内容
  weeklyWorkloadList: {
    projectId: string;
    workTime: number;
  }[]; // 工作量分配
  receiveUserIds: string[]; // 接收人
  reportYear: string | number; // 年
  reportMonth: string | number; // 月
  reportWeek: string | number; // 周
  reportDay: string | number; // 本周第几天
  isUpdate?: boolean; // 是否是更新
}

// 页面数据
const today = ref(moment().format("YYYY-MM-DD"));
const formData = reactive<FormData>({
  reportContent: "",
  weeklyWorkloadList: [],
  receiveUserIds: [],
  reportYear: moment().format("YYYY"),
  reportMonth: moment().format("MM"),
  reportWeek: 0,
  reportDay: 0,
});

const route = useRoute();
onMounted(async () => {
  // 查看有没有传日期进来
  const query: any = route.query;

  // 查一下有没有传id进来，有的话就是数据回填
  if (query.id && query.detail) {
    const dailyDetail = JSON.parse(route.query.detail as string);
    receiveData(dailyDetail);
    return;
  }

  if (query.date) {
    today.value = moment(query.date).format("YYYY-MM-DD");
  }

  // 检查一下今天是否已经填了
  const fillLog = await isFillLog();
  if (fillLog) return;

  // 回填历史接收人
  const receiveUser = await http.getReceiveUser();
  formData.receiveUserIds = receiveUser;
  // 获取当日详情
  await getIsWorkDays();
});

// 在退出前调用一下暂存（做好实时暂存后就不需要退出暂存了）
// onBeforeRouteLeave((ev: any) => {
//   // 如果是千万详情，则不做处理
//   if (ev.name == "LogsDetail") return;
//   // 如果日志内容不为空则触发暂存，否则直接退出
//   if (formData.reportContent?.length > 0) {
//     onSubmit(true, true);
//   }
// });

// 在改动工作量的时候实时暂存
watch(
  () => formData.reportContent,
  (newData, oldData) => {
    // 如果是更新，则不进行实时暂存
    if (formData.isUpdate) return;
    if (newData?.length > 0 && oldData?.length > 0) {
      onSubmit(true, true);
    }
  }
);

// 回填暂存数据
const receiveData = (dailyDetail: any) => {
  formData.reportContent = dailyDetail.reportContent;
  formData.reportYear = dailyDetail.reportYear;
  formData.reportMonth = dailyDetail.reportMonth;
  formData.reportWeek = dailyDetail.reportWeek;
  if (dailyDetail.isUpdate) {
    formData.isUpdate = dailyDetail.isUpdate;
  }
  today.value = moment(dailyDetail.reportStartDate).format("YYYY-MM-DD");
  // 加个定时器回填接收人和工时
  const timer = setTimeout(() => {
    formData.receiveUserIds = dailyDetail.receiveIds;
    formData.weeklyWorkloadList = dailyDetail.workload.map((work: any) => ({
      projectId: work.projectId,
      workTime: work.workTime,
    }));
    PubsubService.publish(
      "callback-full-project-select",
      formData.weeklyWorkloadList
    );
    clearTimeout(timer);
  }, 1000);
};

// 判断一下今天是否已经填了，如果是填了的就跳转到详情页
const isFillLog = async () => {
  const searchList = await http.getMonthLogList(
    "daily",
    moment(today.value).format("YYYY"),
    moment(today.value).format("M")
  );
  const searchLog = searchList.find(
    (item: any) =>
      moment(item.reportStartDate).format("YYYY-MM-DD") ==
      moment(today.value).format("YYYY-MM-DD")
  );
  if (searchLog) {
    if (searchLog.isTemp) {
      receiveData(searchLog);
      return true;
    } else {
      replace({
        path: "/logsDetail",
        query: {
          id: searchLog.id,
          detail: JSON.stringify({
            ...searchLog,
            comments: [], // 就不传那么多东西过去了，反正详情页面也会查询评论
          }),
        },
      });
    }
  }
  return false;
};

// 日历
const calendarShow = ref(false);
// const onConfirm = async (value: any) => {
//   today.value = moment(value).format("YYYY-MM-DD");
//   calendarShow.value = false;
//   // 获取当日详情
//   await getIsWorkDays();
// };

// 可选择的最小日期，一个月之前，最大日期：今天
// const minDate = moment().subtract(1, "months").toDate();
// const maxDate = moment().toDate();

// 工作量改变
const projectChange = (data: any) => {
  formData.weeklyWorkloadList = data;
  getTotalTime();
};

// 提交
const { replace } = useRouter();
const onSubmit = async (isTemp: boolean, isRouteLeave?: boolean) => {
  const userInfo = getUserInfo();
  const params: IReport = {
    ...formData,
    reportType: "daily",
    userId: userInfo.id ?? "",
    deptId: userInfo.deptId ?? "",
    reportStartDate: moment(today.value).valueOf(),
    reportEndDate: moment(today.value).valueOf(),
    isTemp,
  };
  // 提交前校验
  const submitCheck = onSubmitCheck(params);
  if (!submitCheck.success && !isRouteLeave) {
    showToast({
      message: submitCheck.msg,
      position: "top",
    });
    return;
  }
  const result: any = await http.submitReport(params);
  if (isRouteLeave) return; // 如果是退出，则不提示暂存
  const type = isTemp ? "暂存" : "发送";
  if (result.msg == "success") {
    showSuccessToast(`${type}成功`);
    if (!isTemp) {
      replace({
        path: "/logsDetail",
        query: {
          id: result.data,
        },
      });
    }
  } else {
    showToast(`${type}失败，请稍后重试`);
  }
};

// 获取是否工作日
const getIsWorkDays = async (date?: string) => {
  const searchDate = date ?? today.value;
  const startDate = moment(searchDate).format("YYYY-MM-DD HH:mm:ss");
  const endDate = moment(searchDate).format("YYYY-MM-DD HH:mm:ss");
  const workDays = await http.getWorkDayList(startDate, endDate);
  if (workDays.length > 0) {
    formData.reportYear = workDays[0].year;
    formData.reportMonth = workDays[0].month;
    formData.reportWeek = workDays[0].week;
    formData.reportDay = workDays[0].dayOfWeek;
  }
};

// 计算总耗时
const totalTime = ref(0);
const getTotalTime = () => {
  let total = 0;
  formData.weeklyWorkloadList.forEach((item: any) => {
    total += item.workTime;
  });
  totalTime.value = total;
};
</script>
<style lang="scss" scoped>
@import "../page.scss";
</style>
