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

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 }, 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 === 0 ? 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.insuredUserSecId
              )
              .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", userInfo);
    }
  }
};
