import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { defineStore } from "pinia";
import { getRandomStr } from "@/utils";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { teamStore } from "@/store/team";
import { storeToRefs } from "pinia";
const { currentTeamId, currentTeamName } = storeToRefs(teamStore());
import { executeManagementPlan, getPlanTask, stopManagementPlan, getMemberManagementPlan, updateMemberMangePlanStatus } from "@/api/managementPlan";
export const memberMangePlanStore = defineStore("memberMangePlan", () => {
  const planForm = ref({
    planExecutionTime: "",
    planName: "",
    planExecutStaus: "untreated",
    planId: "",
  });
  const taskList = ref([]);
  const taskLoading = ref(false);
  const isAddCustomerTask = ref(false);
  const visible = ref(false);
  const customer = ref({});
  const team = ref({});
  function initPlan() {
    planForm.value = {
      planExecutionTime: "",
      planName: "",
      planExecutStaus: "untreated",
      planId: "",
    };
    taskList.value = [];
  }
  // 执行计划
  async function executPlan(callBack) {
    const { planExecutionTime, planId, planName, executorUserId, changedStatus = "" } = planForm.value;
    const { _id: customerId, name: customerName, externalUserId: customerUserId } = customer.value;
    if (!planName) {
      ElMessage.warning("请输入计划名称!");
      return;
    }
    if (!planExecutionTime) {
      ElMessage.warning("请选择计划执行时间!");
      return;
    }
    if (!executorUserId) {
      ElMessage.warning("请选择计划跟踪人!");
      return;
    }
    if (taskList.value.length === 0) {
      ElMessage.warning("执行任务不能为空!");
      return;
    }
    const params = {
      corpId: sessionStorage.getItem("corpId"),
      customerId,
      planId,
      planName,
      changedStatus,
      planExecutStaus: "executing", //  计划状态为执行中
      customerName,
      planExecutionTime: dayjs(planExecutionTime).format("YYYY-MM-DD"),
      customerUserId,
      executorUserId: executorUserId,
      executeTeamId: currentTeamId.value,
      executeTeamName: currentTeamName.value,
      memberPlanId: getRandomStr(),
      taskList: taskList.value,
    };
    if (isAddCustomerTask.value) {
      params["planId"] = getRandomStr();
      isAddCustomerTask.value = false;
    }
    const { success, message } = await executeManagementPlan(params);
    if (success) {
      getMemberManagementPlanFnc();
      if (callBack && typeof callBack === "function") callBack();
      ElMessage.success("执行成功!");
    } else {
      ElMessage.error(message);
    }
  }

  async function stopPlan() {
    await ElMessageBox.confirm("计划终止后，关联的待办单全部取消！是否终止回访计划？", "提示");
    const { planId, _id: memberPlanId } = planForm.value;
    if (!memberPlanId) return;
    const { success, message } = await stopManagementPlan(customer.value._id, planId, memberPlanId);
    if (success) {
      planForm.value.planExecutStaus = "closed";
      getMemberManagementPlanFnc();
      ElMessage.success("计划终止成功!");
    } else {
      ElMessage.error(message);
    }
  }
  async function getMemberManagementPlanFnc() {
    if (!customer.value._id) return;
    const { data, success, message } = await getMemberManagementPlan(customer.value._id, currentTeamId.value);
    if (success) {
      const plan = data.data;
      if (plan && plan.planId) {
        planForm.value = plan;
        getPlanTaskFnc();
      } else {
        initPlan();
      }
    } else {
      ElMessage.error(message);
    }
  }
  async function getPlanTaskFnc() {
    const { planId, _id: memberPlanId } = planForm.value;
    // 回访计划状态为已变更
    if (!memberPlanId) return;
    taskLoading.value = true;
    const { success, message, data } = await getPlanTask(customer.value._id, planId, memberPlanId);
    if (success) {
      taskList.value = data.data;
      taskLoading.value = false;
    } else {
      ElMessage.error(message);
    }
  }
  function onEditTaskSuccess(type) {
    planForm.value.changedStatus = "isChanged";
    updateMemberMangePlanStatusFnc();
    getPlanTaskFnc();
    if (type === "remove") getMemberManagementPlanFnc();
  }
  // 更新客户回访计划状态
  async function updateMemberMangePlanStatusFnc() {
    const { _id } = planForm.value;
    if (!_id) return;
    const params = {
      changedStatus: "isChanged",
    };
    const { success, message } = await updateMemberMangePlanStatus(_id, params);
    if (!success) {
      ElMessage.error(message);
    }
  }

  const taskShowList = computed(() => {
    if (!Array.isArray(taskList.value)) return [];
    const categorizedTasks = Object.entries(
      // 按照任务时间分类
      taskList.value.reduce((acc, task) => {
        let { taskTime, timeType } = task;
        let time = taskTime;
        if (timeType === "week") time = taskTime * 7;
        if (timeType === "month") time = taskTime * 30;
        if (timeType === "year") time = taskTime * 365;
        if (!acc[time]) {
          acc[time] = [];
        }
        acc[time].push(task);
        return acc;
      }, {})
    ).map(([key, value]) => ({
      key: `计划开始后: ${(!value.timeType || value.timeType == "day") && value[0].taskTime == 0 ? "当天" : value[0].taskTime + timeTypeTransform(value[0].timeType)} ${planForm.value.planExecutionTime ? "(" + dayTransform(value, planForm.value.planExecutionTime) + ")" : ""}`,
      list: value,
    }));
    console.log(categorizedTasks);
    return categorizedTasks || [];
  });

  function timeTypeTransform(timeType) {
    if (!timeType) return "天";
    if (timeType === "day") return "天";
    if (timeType === "week") return "周";
    if (timeType === "month") return "月";
    if (timeType === "year") return "年";
  }

  function dayTransform(value, time) {
    const { taskTime, timeType } = value[0];
    if (!timeType) {
      return dayjs(time).add(taskTime, "day").format("YYYY-MM-DD");
    } else {
      return dayjs(time).add(taskTime, timeType).format("YYYY-MM-DD");
    }
  }

  return {
    planForm,
    taskShowList,
    taskList,
    taskLoading,
    isAddCustomerTask,
    visible,
    customer,
    team,
    initPlan,
    executPlan,
    stopPlan,
    getMemberManagementPlanFnc,
    onEditTaskSuccess,
    getPlanTaskFnc,
    updateMemberMangePlanStatusFnc,
  };
});
