import GOODS_LIST from "@/api/goodsList.mock";
import { getUserInfo, getFamilyList } from "@/api/user";
import { getPolicyList } from "@/api/policy";
import man from "@/assets/images/user/man@2x.png";
import woman from "@/assets/images/user/woman@2x.png";
import avatar from "@/assets/images/user/avatar@2x.png";
import { groupBy, values, mapValues, some, find } from "lodash-es";

const CONSTANT = {
  avatar: {
    man,
    woman
  },
  relation: ["本人", "父母", "配偶", "子女", "未知"]
};

// 0: man; 1: woman
function getReletion(relation, gender) {
  let result = "";
  if ([2, 4].includes(+relation)) {
    if (+relation === 2) {
      result = +gender === 0 ? "母亲" : "父亲";
    } else {
      result = +gender === 0 ? "女儿" : "儿子";
    }
  } else if (+relation === -1) {
    result = CONSTANT.relation[4];
  } else {
    result = CONSTANT.relation[+relation - 1];
  }

  return result;
}

export default {
  namespaced: true,
  state: {
    familyList: [],
    userInfo: {
      name: "未登录",
      phoneNoMask: "点击登录",
      avatar,
      auth: false
    }
  },
  mutations: {
    setFamilyList(state, value) {
      state.familyList = value;
    },
    setUserInfo(state, value) {
      state.userInfo = value;
    }
  },
  actions: {
    async setFamilyList({ commit }, policyList) {
      let familyList = await getFamilyList();
      if (!policyList) {
        policyList = await getPolicyList();
      }
      let goodsMap = groupBy(GOODS_LIST, "itype");

      // todo 家人保单列表筛选
      const result = familyList.map(family => ({
        ...family,
        avatar: +family.gender === 1 ? CONSTANT.avatar.man : CONSTANT.avatar.woman,
        appellation: getReletion(family.relation, family.gender),
        policyList: values(
          mapValues(goodsMap, goodsList => {
            const policyListFilted = policyList
              .filter(
                policy =>
                  some(goodsList, { id: policy.productNo }) &&
                  family.userInfoSecId === policy.insuredUserInfoSecId &&
                  ["6.1", "6.2", "6.3"].includes(policy.policyState)
              )
              .map(policy => ({ ...policy, ...find(goodsList, { id: policy.productNo }) }))
              .sort((a, b) => a.termType > b.termType);

            return policyListFilted?.[0] || goodsList[0];
          })
        )
      }));
      commit("setFamilyList", result);
    },
    async setUserInfo({ commit }) {
      const userInfo = await getUserInfo();
      commit("setUserInfo", { ...{ name: "小芒果", avatar }, ...userInfo });
    }
  }
};
