import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { memberStore } from "@/store/member";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { getManagementPlan as getManagementPlanUrl, updateManagementPlan as updateManagementPlanUrl, getManagementPlanById as getManagementPlanByIdUrl, createManagementPlan as createManagementPlanUrl, executeManagementPlan as executeManagementPlanUrl } from "@/api/managementPlan";
export const managePlanStore = defineStore("managePlan", () => {
  let list = ref([]);
  let total = ref(0);
  let pageSize = ref(10);
  let currentPage = ref(1);
  let loading = ref(false);
  async function getManagementPlan(teamId) {
    let { data } = await getManagementPlanUrl(currentPage.value, pageSize.value, teamId);
    list.value = Array.isArray(data.data) ? data.data.map((i) => ({
      ...i,
      timeStr: i.createTime ? dayjs(i.createTime).format("YYYY-MM-DD HH:mm") : "",
    })) : [];
    total.value = data.total;
  }
  async function updateManagementPlan(id, data, reloadList = true) {
    const { success, message } = await updateManagementPlanUrl(id, data);
    if (!success) {
      ElMessage.error(message);
      return;
    } else {
      if (reloadList) {
        await getManagementPlan()
      };
      return true;
    }
  }
  async function stopPlan(id, reloadList = true) {
    await ElMessageBox.confirm("确定停用该回访计划？", "提示", { type: 'warning' });
    const params = {
      planStatus: false,
    };
    return updateManagementPlan(id, params, reloadList);
  }
  // 启用
  async function enablePlan(id, reloadList = true) {
    await ElMessageBox.confirm("确定启用该回访计划？", "提示", { type: 'warning' });
    const params = {
      planStatus: true,
    };
    return updateManagementPlan(id, params, reloadList);
  }

  async function createManagementPlan(params) {
    const { success, message } = await createManagementPlanUrl(params);
    if (!success) {
      ElMessage.error(message);
    } else {
      return true;
    }
  }

  async function getManagementPlanById(planId) {
    let {
      data: { data: plan },
    } = await getManagementPlanByIdUrl(planId);
    return plan;
  }
  async function executeManagementPlan(params) {
    console.log("执行回访计划");
    const { success, message } = await executeManagementPlan(params);
    if (success) {
      return true;
    } else {
      ElMessage.error(message);
    }
  }
  return {
    list,
    total,
    pageSize,
    currentPage,
    loading,
    getManagementPlan,
    updateManagementPlan,
    stopPlan,
    enablePlan,
    createManagementPlan,
    getManagementPlanById,
    executeManagementPlan,
  };
});
