<template>
  <div class="container">
    <div class="timer">
      <van-cell
        title="周报时间"
        :value="thisWeek"
        @click="calendarShow = true"
      />
      <!-- <van-calendar
        v-model:show="calendarShow"
        @confirm="onConfirm"
        type="range"
        :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="weekly" :onChange="projectChange" />
    <div class="title">接收人</div>
    <SelectUser v-model="formData.receiveUserIds" />
    <div class="blank-line"></div>
    <van-button round type="primary" block class="send-btn" @click="onSubmit"
      >发送</van-button
    >
  </div>
</template>
<script lang="ts" setup>
/**
 * @description 周报
 */
import moment from "moment";
import { reactive } 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";

interface FormData {
  reportContent: string; // 内容
  weeklyWorkloadList: {
    projectId: string;
    workTime: number;
  }[]; // 工作量分配
  receiveUserIds: string[]; // 接收人
  reportYear: string | number; // 年
  reportMonth: string | number; // 月
  reportWeek: string | number; // 周
}

// 页面数据
const thisWeek = ref(
  `${moment().startOf("week").add(1, "day").format("YYYY/MM/DD")} ~ ${moment()
    .endOf("week")
    .add(1, "day")
    .format("YYYY/MM/DD")}`
);
const formData = reactive<FormData>({
  reportContent: "",
  weeklyWorkloadList: [],
  receiveUserIds: [],
  reportYear: moment().format("YYYY"),
  reportMonth: moment().format("MM"),
  reportWeek: 0,
});

const route = useRoute();
onMounted(async () => {
  // 查看有没有传日期进来
  const query: any = route.query;
  if (query.startDate && query.endDate) {
    thisWeek.value = `${moment(query.startDate).format(
      "YYYY/MM/DD"
    )} ~ ${moment(query.endDate).format("YYYY/MM/DD")}`;
  }

  // 检查一下今天是否已经填了
  await isFillLog();

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

// 判断一下本周是否已经填了，如果是填了的就跳转到详情页
const isFillLog = async () => {
  const date = thisWeek.value.split(" ~ ");
  const searchList = await http.getMonthLogList(
    "weekly",
    moment(date[1]).format("YYYY"),
    moment(date[1]).format("M")
  );
  const searchLog = searchList.find(
    (item: any) => item.reportEndDate == moment(date[1]).format("YYYY-MM-DD")
  );

  if (searchLog) {
    push(`/logsDetail?id=${searchLog.id}`);
  }
};

// 日历
const calendarShow = ref(false);
// const onConfirm = async (values: any) => {
//   const [start, end] = values;
//   thisWeek.value = `${moment(start).format("YYYY/MM/DD")} ~ ${moment(
//     end
//   ).format("YYYY/MM/DD")}`;
//   calendarShow.value = false;
//   // 获取当日详情
//   await getIsWorkDays();
// };

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

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

// 提交
const { push } = useRouter();
const onSubmit = async () => {
  const date = thisWeek.value.split(" ~ ");
  const userInfo = getUserInfo();
  const params: IReport = {
    ...formData,
    reportType: "weekly",
    userId: userInfo.id ?? "",
    deptId: userInfo.deptId ?? "",
    reportStartDate: moment(date[0]).valueOf(),
    reportEndDate: moment(date[1]).valueOf(),
    isTemp: false,
  };
  const submitCheck = onSubmitCheck(params);
  if (!submitCheck.success) {
    showToast({
      message: submitCheck.msg,
      position: "top",
    });
    return;
  }
  const result: any = await http.submitReport(params);
  if (result.msg == "success") {
    showSuccessToast("发送成功");
    push(`/logsDetail?id=${result.data}`);
  }
};
// 获取是否工作日
const getIsWorkDays = async (date?: string) => {
  const searchDate = date?.split(" ~ ") ?? thisWeek.value.split(" ~ ");
  const startDate = moment(searchDate[1]).format("YYYY-MM-DD HH:mm:ss");
  const endDate = moment(searchDate[1]).format("YYYY-MM-DD HH:mm:ss");
  const workDays = await http.getWorkDayList(startDate, endDate);
  formData.reportYear = workDays[0].year;
  formData.reportMonth = workDays[0].month;
  formData.reportWeek = workDays[0].week;
  // return workDays[0];
};

// 计算总耗时
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>
