import { ref } from "vue";
import { defineStore, storeToRefs } from "pinia";
import dayjs from "dayjs";
import { getCustomerType } from "@/api/member";
import { memberStore } from "./member";
import validate from "@/utils/validate";
import { referenceType } from "@/baseData";
import { ElMessage } from "element-plus";
import { getGroups as getGroupsUrl } from "@/api/group";
import { teamStore } from "@/store/team";
import { getCorpTags } from "@/api/corp";

export const configStore = defineStore("globalConfig", () => {
  const stageList = ref([]);
  const stageMap = ref({});
  const groups = ref([]);
  const tags = ref([]);
  const tagsLoading = ref(false);
  const { customerSourceList, intentedProjectList } = storeToRefs(memberStore());
  const { currentTeam } = storeToRefs(teamStore());
  const customerField = ref({
    allergy: { canEidt: true, type: "textarea", maxlength: 300 },
    assistantByMobile: {
      canEidt: true,
      type: "mobileGroup",
      valueType: "Array",
      maxlength: 3,
      validate: checkMobileGroup,
      getValue: (val) => {
        return Array.isArray(val) ? val.filter((i) => i.mobile || i.note) : [];
      },
    },
    birthday: { canEidt: true, type: "datepicker", validate: checkDate },
    cardType: {
      canEidt: false,
      type: "input",
      inputType: "text",
      maxlength: 20,
    },
    creator: { canEidt: false, type: "wwuser" },
    createTime: {
      canEidt: false,
      type: "date",
      format: (e) => (e && dayjs(e).isValid() ? dayjs(e).format("YYYY-MM-DD HH:mm") : ""),
    },
    customerSource: {
      canEidt: true,
      type: "cascader",
      range: customerSourceList,
      format: (e) => (Array.isArray(e) ? e.join("、") : ""),
    },
    customerStage: {
      canEidt: true,
      type: "select",
      mode: "selector",
      range: stageList,
      format: (e) => {
        const item = stageList.value.find((i) => i.value === e);
        return item ? item.label : "";
      },
      validate: (val) => {
        if (!val) {
          ElMessage.info("请选择客户阶段");
          return false;
        }
        const res = stageList.value.some((i) => i.value === val);
        if (res) return res;
        else {
          ElMessage.info("所选客户阶段无效, 请重新选择");
          return false;
        }
      },
    },
    disease: {
      canEidt: true,
      type: "remoteSelect",
      valueKey: "pastMedicalHistory",
      valueType: "Array",
      format: (e) => (Array.isArray(e) ? e.join("、") : ""),
    },
    idCard: {
      canEidt: true,
      type: "input",
      inputType: "text",
      validate: checkIdNo,
      maxlength: 20,
    },
    intentedProject: {
      canEidt: true,
      type: "select",
      mode: "selector",
      range: intentedProjectList,
      format: (e) => {
        const item = intentedProjectList.value.find((i) => i.value === e);
        return item ? item.label : "";
      },
    },
    myRecommend: { canEidt: false, type: "input", valueKey: "referenceCount" },
    mobile: {
      canEidt: false,
      type: "input",
      inputType: "number",
      validate: validate.isMobile,
      maxlength: 20,
    },
    notes: { canEidt: true, hidden: true, type: "textarea", maxlength: 500 },
    name: {
      canEidt: true,
      type: "input",
      inputType: "text",
      maxlength: 20,
      validate: (val) => {
        if (typeof val !== "string" || val.trim() === "") {
          ElMessage.info("请输入客户姓名");
          return false;
        }
        return true;
      },
    },
    sex: {
      canEidt: true,
      type: "radio",
      range: ["男", "女"],
      validate: (val) => {
        if (["男", "女"].includes(val)) return true;
        else {
          ElMessage.info("所选性别无效, 请重新选择");
          return false;
        }
      },
    },
    tagList: {
      canEidt: true,
      hidden: true,
      type: "tagList",
      valueKey: "tagIds",
    },
    reference: {
      canEidt: true,
      type: "input",
      inputType: "text",
      maxlength: 20,
      appendList: referenceType,
      appendRangeKey: "value",
      appendKey: "referenceType",
    },
    relationship: {
      canEidt: false,
      required: false,
      type: "input",
      inputType: "text",
      maxlength: 20,
    },
  });

  function checkDate(date) {
    return Boolean(date) && dayjs(date).isValid();
  }

  function checkIdNo(str) {
    const res = validate.isChinaId(str);
    if (res[0]) return true;
    else {
      ElMessage.info(res[1] || "身份证格式不正确");
      return false;
    }
  }

  function checkMobileGroup(val) {
    if (!Array.isArray(val) || val.length === 0) return true;
    const list = val.filter((i) => i.mobile);
    if (list.length === 0) return true;
    const res = list.find((i) => !validate.isMobile(i.mobile));
    if (res) {
      ElMessage.info(`手机号【${res.mobile}】格式不正确`);
      return false;
    }
    return true;
  }

  async function getStage() {
    const { data } = await getCustomerType();
    const list = data.data && Array.isArray(data.data) ? data.data : [];
    stageList.value = list.map((i) => ({ label: i.name, value: i.type }));
    stageMap.value = list.reduce((val, i) => {
      val[i.type] = i.name;
      return val;
    }, {});
  }

  async function getGroups() {
    let { success, data } = await getGroupsUrl({ page: 1, pageSize: 1000, teamId: currentTeam.value.teamId });
    if (success) {
      groups.value = data.data;
    }
  }

  //获取分组名称
  function getGroupName(list) {
    let groupName = "";
    if (Array.isArray(list) && list.length > 0) {
      list.forEach((item) => {
        const group = groups.value.find((i) => i._id === item);
        groupName += group ? group.groupName + " " : "";
      });
    }
    return groupName;
  }

  async function getGroupTag() {
    if (tagsLoading.value) return;
    tagsLoading.value = true;
    let { success, data } = await getCorpTags();
    if (success) {
      tags.value = data.list;
      //  createType 为corpAsync 排序
      tags.value = tags.value.sort((a, b) => {
        return a.createType === "corpAsync" ? -1 : 1;
      });
    } else {
      tags.value = [];
    }
    tagsLoading.value = false;
  }

  return {
    customerField,
    stageList,
    stageMap,
    tags,
    getGroupTag,
    getStage,
    getGroups,
    groups,
    getGroupName,
  };
});
