import GOODS_LIST from "@/api/goodsList.mock";
import { getUserInfo, getFamilyList } from "@/api/user";
import { getPolicyList } from "@/api/policy";

const CONSTANT = {
  avatar: {
    man: "../../../assets/images/user/man@2x.png",
    woman: "../../../assets/images/user/woman@2x.png"
  },
  relation: ["本人", "父母", "配偶", "子女"]
};

function getReletion(relation, gender) {
  let result = "";
  if ([1, 3].includes(+relation)) {
    if (+relation === 1) {
      result = +gender ? "父亲" : "母亲";
    } else {
      result = +gender ? "儿子" : "女儿";
    }
  } else {
    result = CONSTANT.relation[+relation];
  }

  return result;
}

export default {
  namespaced: true,
  state: {
    familyList: [],
    userInfo: {
      name: "未登录",
      phoneNoMask: "点击登录",
      avatar: "../../assets/images/user/avatar@2x.png",
      auth: false
    }
  },
  mutations: {
    setFamilyList(state, value) {
      state.familyList = value;
    },
    setUserInfo(state, value) {
      state.userInfo = value;
    }
  },
  actions: {
    async setFamilyList({ commit }) {
      let familyList = await getFamilyList();
      const policyList = await getPolicyList();

      familyList = familyList.concat(familyList);

      // todo 家人保单列表筛选
      const result = familyList.map(family => ({
        ...family,
        avatar: +family.gender === 0 ? CONSTANT.avatar.man : CONSTANT.avatar.woman,
        relation: getReletion(family.relation, family.gender),
        policyList: GOODS_LIST.map(goods => {
          // todo 家人保单列表推荐
          const filterPolicyList = policyList
            .map(policy => {
              const goodsChild = goods.children.find(child => child.id === +policy.productNo) || {};
              return {
                ...policy,
                ...goodsChild
              };
            })
            .filter(policy => policy.insuredUserSecId === family.userInfoSecId && policy.id)
            .sort((a, b) => a.termType > b.termType);

          return filterPolicyList?.[0] || goods.children[0];
        })
      }));
      commit("setFamilyList", result);
    },
    async setUserInfo({ commit }) {
      const userInfo = await getUserInfo();
      commit("setUserInfo", userInfo);
    }
  }
};
