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 _ from "lodash";

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

// 0: man; 1: woman
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,
      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 &&
                  ["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", userInfo);
    }
  }
};
