package com.hzs.member.structure.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.MemberFrameworkConstants;
import com.hzs.common.core.constant.TableNameConstants;

import com.hzs.common.core.constant.VertexConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EPlaceDept;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.sign.Base64Util;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.member.ext.CuMemberSettleExt;
import com.hzs.common.domain.member.ext.MemberSettleTreeExt;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.achieve.service.ICuMemberTreeService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.structure.controller.vo.CuMemberSettlePeriodVo;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.LoginUser;
import com.hzs.system.sys.dto.UserAuthorityDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 架构管理
 * @Author: yuhui
 * @Time: 2023/2/2 11:32
 * @Classname: MemberStructureController
 * @PackageName: com.hzs.member.memberStructure
 */
@RestController
@RequestMapping("/manage/member-structure")
public class MemberStructureController extends BaseController {
    @Autowired
    private ICuMemberBaseService memberBaseService;
    @DubboReference
    private IGradeServiceApi gradeServiceApi;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberSettlePeriodService memberSettlePeriodService;
    @DubboReference
    private ICurrencyServiceApi currencyServiceApi;
    @Autowired
    private ICuMemberTreeService memberTreeService;
    @Autowired
    private ICuMemberService memberService;
    @DubboReference
    private ICountryServiceApi countryServiceApi;
    @DubboReference
    private ITransactionServiceApi transactionServiceApi;
    @DubboReference
    private IUserServiceApi iUserServiceApi;
    /**
     * 默认层数
     */
    Integer defaultLevel = 7;

    /**
     * 多哥顶点编号
     */
    private String DgCode = "NG30720201";
    /**
     * 国际201 顶点
     */
    private String GJParentCode = "GJ30720201";

    /**
     * 安置架构网体
     */
    @GetMapping("az-framework")
    public AjaxResult azFramework(Long memberSettlePeriodId, String memberCode, Integer level, Integer type) {
        if (level == null) {
            level = 7;
        }

        // 体系
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        List<Integer> vertexIdList = userAuthorityDTO.getVertexIdList();
   //     List<Long> userVertexList = userAuthorityDTO.getUserVertexList();
        Date date = new Date();

        Long pkMember = null;
        if (StringUtils.isNotBlank(memberCode)) {
            CuMember member = memberService.getMemberByCode(memberCode);
            if (member == null){
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
            }
//            if (!member.getPkSettleCountry().equals(SecurityUtils.getPkCountry())){
//                return AjaxResult.success();
//            }
            pkMember = member.getPkId();
        } else {
            return AjaxResult.success();
        }

        if (vertexIdList != null && StringUtils.isNotBlank(memberCode)){
            // 体系不为空 并且会员编号不为空 只能查询自己伞下以及自己的
            List<CuMemberExt> memberExtList = memberService.checkMemberVertex(vertexIdList,memberCode);
            if (memberExtList.size() == 0){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.QUERY_VERTEX_CODE));
            }
        }
        Integer period = null;
        if (memberSettlePeriodId != null) {
            CuMemberSettlePeriod csPeriod = memberSettlePeriodService.getById(memberSettlePeriodId);
            if (csPeriod != null){
                period = csPeriod.getPkId();
            }
            // 查询 历史

            String settleTableName = TableNameConstants.CU_MEMBER_SETTLE_D + period;
            Integer tableNumber = memberTreeService.queryExistOracleTable(settleTableName);

            if (tableNumber == null) {
                // 表示表格存在
                if(DateUtils.getCurrentHour() < 2){
                    period = memberBaseService.getPeriod(new Date(),-2);
                }else {
                    period = memberBaseService.getPeriod(new Date(),-1);
                }
            }
        } else {
            //period = memberBaseService.getPeriod(null);
            period = memberBaseService.getPeriod(null);
        }

        // 查询 历史
        String settleTableName = TableNameConstants.CU_MEMBER_SETTLE_D + period;
        Integer tableNumber = memberTreeService.queryExistOracleTable(settleTableName);
        if (tableNumber != null && tableNumber == 1) {
            // 表示表格存在
            // 查询顶点
            CuMemberSettleExt memberSettleExt = memberTreeService.queryCuMemberTreeByPkMemberTable(pkMember);
            if (VertexConstants.GJ30720200CODE.equals(memberSettleExt.getParentMemberCode())) {
                memberSettleExt.setParentMemberCode(memberSettleExt.getMemberCode());
            }
            memberSettleExt.setLevel(0);
            //查询下级
            //  List<CuMemberSettleExt> list = memberTreeService.queryCuMemberTreePlaceParentHistoryTable(settleTableName, pkMember, new ArrayList<>(),level);
            List<CuMemberSettleExt> list = memberTreeService.queryCuMemberTreePlaceParentHistoryFramework(settleTableName, pkMember, new ArrayList<>(), level);
            // 无法查询到自身 所有单独查询自身并且添加
            list.add(memberSettleExt);
            // 会员主键
            List<Long> pkMemberIds = list.stream().map(a -> {
                return a.getPkMember();
            }).collect(Collectors.toList());
            // 按照安置部门排序
            Map<Long, List<CuMemberSettleExt>> settleList = list.stream().collect(Collectors.groupingBy(CuMemberSettleExt::getPkPlaceParent));

            List<MemberSettleTreeExt> memberSettleList = memberService.queryMemberSettle(settleTableName, pkMemberIds, 20);

            List<CuMemberSettleExt> resultList = new ArrayList<>();
            for (Map.Entry<Long, List<CuMemberSettleExt>> listEntry : settleList.entrySet()) {
                for (CuMemberSettleExt cuMemberSettleExt : listEntry.getValue()) {
                    List<MemberSettleTreeExt> msList = new ArrayList<>();
                    // 查询会员所有团队业绩
                    for (MemberSettleTreeExt mt : memberSettleList) {
                        if (cuMemberSettleExt.getPkMember().equals(mt.getPkMember())){
                            msList.add(mt);
                        }
                        if (cuMemberSettleExt.getPkMember().equals(mt.getPkMember())){
                            cuMemberSettleExt.setNewPv(mt.getNewPv());
                        }
                    }
                  //  msList.stream().sorted(Comparator.comparing(MemberSettleTreeExt::getPlaceDept).reversed()).collect(Collectors.toList());
                    cuMemberSettleExt.setLevelMemberSettleList(msList);
                    resultList.add(cuMemberSettleExt);
                }
            }

            List<Tree<String>> build = memberService.systemAzSetListTree(resultList, memberSettleExt);
            // 安置架构 无点位 追加空点位
            return AjaxResult.success(build);
        }


        return AjaxResult.success();
    }

    /**
     * 安置架构网体（安置架构一（新））
     */
    @GetMapping("az-framework-first")
    public AjaxResult azFrameworkFirst(Long memberSettlePeriodId, String memberCode, Integer level, Integer type) {
        if (level == null) {
            level = 7;
        }
        // 体系
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        List<Integer> vertexIdList = userAuthorityDTO.getVertexIdList();
        Long pkMember = null;
        if (StringUtils.isNotBlank(memberCode)) {
            CuMember member = memberService.getMemberByCode(memberCode);
            if (member == null){
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
            }
//            if (!member.getPkSettleCountry().equals(SecurityUtils.getPkCountry())){
//                return AjaxResult.success();
//            }
            pkMember = member.getPkId();
        } else {
            return AjaxResult.success();
        }
        if (vertexIdList != null && StringUtils.isNotBlank(memberCode)){
            // 体系不为空 并且会员编号不为空 只能查询自己伞下以及自己的
            List<CuMemberExt> memberExtList = memberService.checkMemberVertex(vertexIdList,memberCode);
            if (memberExtList.size() == 0){
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.QUERY_VERTEX_CODE));
            }
        }
        Integer period = null;
        if (memberSettlePeriodId != null) {
            CuMemberSettlePeriod csPeriod = memberSettlePeriodService.getById(memberSettlePeriodId);
            if (csPeriod != null){
                period = csPeriod.getPkId();
            }
            // 查询 历史
            String settleTableName = TableNameConstants.CU_MEMBER_SETTLE_D + period;
            Integer tableNumber = memberTreeService.queryExistOracleTable(settleTableName);

            if (tableNumber == null) {
                // 表示表格存在
                if(DateUtils.getCurrentHour() < 2){
                    period = memberBaseService.getPeriod(new Date(),-2);
                }else {
                    period = memberBaseService.getPeriod(new Date(),-1);
                }
            }
        } else {
            period = memberBaseService.getPeriod(null);
        }
        // 查询 历史
        String settleTableName = TableNameConstants.CU_MEMBER_SETTLE_D + period;
        Integer tableNumber = memberTreeService.queryExistOracleTable(settleTableName);
        if (tableNumber != null && tableNumber == 1) {
            // 查询顶点
            CuMemberSettleExt memberSettleExt = memberTreeService.queryCuMemberTreeByPkMemberTable(pkMember);
            if (VertexConstants.GJ30720200CODE.equals(memberSettleExt.getParentMemberCode())) {
                memberSettleExt.setParentMemberCode(memberSettleExt.getMemberCode());
            }
            memberSettleExt.setLevel(0);
            //查询下级
            List<CuMemberSettleExt> list = memberTreeService.queryCuMemberTreePlaceParentHistoryFramework(settleTableName, pkMember, new ArrayList<>(), level);
            // 无法查询到自身 所有单独查询自身并且添加
            list.add(memberSettleExt);
            // 会员主键
            List<Long> pkMemberIds = list.stream().map(a -> {
                return a.getPkMember();
            }).collect(Collectors.toList());
            // 按照安置部门排序
            Map<Long, List<CuMemberSettleExt>> settleList = list.stream().collect(Collectors.groupingBy(CuMemberSettleExt::getPkPlaceParent));
            List<MemberSettleTreeExt> memberSettleList = memberService.queryMemberSettle(settleTableName, pkMemberIds, 20);
            List<CuMemberSettleExt> resultList = new ArrayList<>();
            for (Map.Entry<Long, List<CuMemberSettleExt>> listEntry : settleList.entrySet()) {
                for (CuMemberSettleExt cuMemberSettleExt : listEntry.getValue()) {
                    List<MemberSettleTreeExt> msList = new ArrayList<>();
                    // 查询会员所有团队业绩
                    for (MemberSettleTreeExt mt : memberSettleList) {
                        if (cuMemberSettleExt.getPkMember().equals(mt.getPkMember())){
                            Long sParentCount = memberService.selectByQuerySparentMemberCount(mt.getPkMember());
                            mt.setSParentCount(sParentCount);
                            cuMemberSettleExt.setSParentCount(sParentCount);
                            cuMemberSettleExt.setNewPv(mt.getNewPv());
                            msList.add(mt);
                        }

                    }
                    cuMemberSettleExt.setLevelMemberSettleList(msList);
                    resultList.add(cuMemberSettleExt);
                }
            }

            List<Tree<String>> build = memberService.systemAzSetFirstListTree(resultList, memberSettleExt);
            // 安置架构 无点位 追加空点位
            return AjaxResult.success(build);
        }


        return AjaxResult.success();
    }
    /**
     * @param build
     * @return
     */

    // 设置虚拟节点
    public List<Tree<String>> setTreeList(List<Tree<String>> build, Integer numberOfPlies) {
        R<Map<Integer, BdCountry>> allCountryMap = countryServiceApi.getAllCountryMap();
        Map<Integer, BdCountry> allCountryData = allCountryMap.getData();
        Integer pkCountry = SecurityUtils.getPkCountry();
        String nationalFlag1 = allCountryData.get(pkCountry).getNationalFlag1();
        String nationalFlag2 = allCountryData.get(pkCountry).getNationalFlag2();
        for (Tree<String> stringTree : build) {
            Integer level = (Integer) stringTree.get("level");
            Integer placeDept = (Integer) stringTree.get("placeDept");
            if (level < (numberOfPlies - 1)) {
                if (stringTree.getChildren() != null) {
                    if (stringTree.getChildren().size() == 0) {
                        Tree<String> emptyNode1 = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
                        emptyNode1.putExtra("placeDept", EPlaceDept.LEFT_DEPT.getValue());
                        emptyNode1.putExtra("level", level + 1);
                        emptyNode1.putExtra("memberCode", "");
                        emptyNode1.setName("-");
                        emptyNode1.setParentId(stringTree.getId());
                        emptyNode1.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
                        emptyNode1.setId(RandomUtil.randomNumbers(3));
                        emptyNode1.putExtra("settleCountryUrl", nationalFlag1);
                        emptyNode1.putExtra("settleCountryUrl2", nationalFlag2);
                        emptyNode1.putExtra("countryUrl", nationalFlag1);
                        emptyNode1.putExtra("countryUrl2", nationalFlag2);
                        //                    emptyNode1.setChildren(setChildren(level,emptyNode1.getId()));
                        stringTree.getChildren().add(emptyNode1);
                        setTreeList(stringTree.getChildren(), numberOfPlies);

                        Tree<String> emptyNode2 = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
                        emptyNode2.putExtra("placeDept", EPlaceDept.RIGHT_DEPT.getValue());
                        emptyNode2.putExtra("level", level + 1);
                        emptyNode2.putExtra("memberCode", "");
                        emptyNode2.setName("-");
                        emptyNode2.setParentId(stringTree.getId());
                        emptyNode2.putExtra("settleCountryUrl", nationalFlag1);
                        emptyNode2.putExtra("settleCountryUrl2", nationalFlag2);
                        emptyNode2.putExtra("countryUrl", nationalFlag1);
                        emptyNode2.putExtra("countryUrl2", nationalFlag2);
                        emptyNode2.setId(RandomUtil.randomNumbers(3));
                        emptyNode2.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
                        //         emptyNode2.setChildren(setChildren(level,emptyNode2.getId()));
                        stringTree.getChildren().add(emptyNode2);
                        setTreeList(stringTree.getChildren(), numberOfPlies);
                    } else if (stringTree.getChildren().size() == 1) {
                        List<Tree<String>> cli = stringTree.getChildren();
                        Integer pd = (Integer) cli.get(0).get("placeDept");
                        Tree<String> emptyNode = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
                        if (pd.equals(EPlaceDept.LEFT_DEPT.getValue())) {
                            emptyNode.putExtra("placeDept", EPlaceDept.RIGHT_DEPT.getValue());
                            emptyNode.putExtra("level", level + 1);
                            emptyNode.putExtra("memberCode", "");
                            emptyNode.setName("-");
                            emptyNode.setParentId(stringTree.getId());
                            emptyNode.setId(RandomUtil.randomNumbers(3));
                            emptyNode.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
                            emptyNode.putExtra("settleCountryUrl", nationalFlag1);
                            emptyNode.putExtra("settleCountryUrl2", nationalFlag2);
                            emptyNode.putExtra("countryUrl", nationalFlag1);
                            emptyNode.putExtra("countryUrl2", nationalFlag2);
                            //     emptyNode.setChildren(setChildren(level,emptyNode.getId()));
                            stringTree.getChildren().add(emptyNode);
                            setTreeList(stringTree.getChildren(), numberOfPlies);

                        } else {
                            emptyNode.putExtra("placeDept", EPlaceDept.LEFT_DEPT.getValue());
                            emptyNode.putExtra("level", level + 1);
                            emptyNode.putExtra("memberCode", "");
                            emptyNode.setName("-");
                            emptyNode.setParentId(stringTree.getId());
                            emptyNode.setId(RandomUtil.randomNumbers(3));
                            emptyNode.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
                            emptyNode.putExtra("settleCountryUrl", nationalFlag1);
                            emptyNode.putExtra("settleCountryUrl2", nationalFlag2);
                            emptyNode.putExtra("countryUrl", nationalFlag1);
                            emptyNode.putExtra("countryUrl2", nationalFlag2);
                            //       emptyNode.setChildren(setChildren(level,emptyNode.getId()));
                            stringTree.getChildren().add(emptyNode);
                            List<Tree<String>> strTree = stringTree.getChildren();
                            List<Tree<String>> sortChildren = new ArrayList<>();
                            sortChildren.add(strTree.get(1));
                            sortChildren.add(strTree.get(0));
                            stringTree.setChildren(sortChildren);
                            setTreeList(sortChildren, numberOfPlies);

                        }
                    } else {
                        List<Tree<String>> children = stringTree.getChildren();
                        List<Tree<String>> sortChildren = new ArrayList<>();
                        Integer pd = Integer.parseInt(children.get(0).get("placeDept").toString());
                        if (pd == 1) {
                            sortChildren.add(children.get(0));
                            sortChildren.add(children.get(1));
                        } else {
                            sortChildren.add(children.get(1));
                            sortChildren.add(children.get(0));
                        }
                        stringTree.setChildren(sortChildren);
                        setTreeList(stringTree.getChildren(), numberOfPlies);
                    }
                } else {
                    // 等于空
                    List<Tree<String>> children = new ArrayList<>();
                    children = new ArrayList<>();
                    Tree<String> emptyNode1 = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
                    emptyNode1.putExtra("placeDept", EPlaceDept.LEFT_DEPT.getValue());
                    emptyNode1.putExtra("level", level + 1);
                    emptyNode1.putExtra("memberCode", "");
                    emptyNode1.setName("-");
                    emptyNode1.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
                    emptyNode1.putExtra("settleCountryUrl", nationalFlag1);
                    emptyNode1.putExtra("settleCountryUrl2", nationalFlag2);
                    emptyNode1.putExtra("countryUrl", nationalFlag1);
                    emptyNode1.putExtra("countryUrl2", nationalFlag2);
                    emptyNode1.setParentId(stringTree.getId());
                    emptyNode1.setId(RandomUtil.randomNumbers(3));
                    //   emptyNode1.setChildren(setChildren(level+1,emptyNode1.getId()));
                    children.add(emptyNode1);


                    Tree<String> emptyNode2 = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
                    emptyNode2.putExtra("placeDept", EPlaceDept.RIGHT_DEPT.getValue());
                    emptyNode2.putExtra("level", level + 1);
                    emptyNode2.putExtra("memberCode", "");
                    emptyNode2.setName("-");
                    emptyNode2.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
                    emptyNode2.setParentId(stringTree.getId());
                    emptyNode2.putExtra("settleCountryUrl", nationalFlag1);
                    emptyNode2.putExtra("settleCountryUrl2", nationalFlag2);
                    emptyNode2.putExtra("countryUrl", nationalFlag1);
                    emptyNode2.putExtra("countryUrl2", nationalFlag2);
                    emptyNode2.setId(RandomUtil.randomNumbers(3));
                    //    emptyNode2.setChildren(setChildren( level+1,emptyNode2.getId()));
                    children.add(emptyNode2);

                    stringTree.setChildren(children);
                    setTreeList(children, numberOfPlies);

                }
            }
        }


        return build;
    }


    public List<Tree<String>> setChildren(Integer level, String parentId) {
        List<Tree<String>> list = new ArrayList<>();
        Tree<String> emptyNode1 = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
        emptyNode1.putExtra("placeDept", EPlaceDept.LEFT_DEPT.getValue());
        emptyNode1.putExtra("level", level + 1);
        emptyNode1.putExtra("memberCode", "");
        emptyNode1.setName("-");
        emptyNode1.setParentId(parentId);
        emptyNode1.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
        emptyNode1.setId(RandomUtil.randomNumbers(3));

        list.add(emptyNode1);
        Tree<String> emptyNode2 = TreeUtil.createEmptyNode(RandomUtil.randomNumbers(5));
        emptyNode2.putExtra("placeDept", EPlaceDept.RIGHT_DEPT.getValue());
        emptyNode2.putExtra("level", level + 1);
        emptyNode2.putExtra("memberCode", "");
        emptyNode2.setName("-");
        emptyNode2.putExtra("avatarUrl", MemberFrameworkConstants.xuni);
        emptyNode2.setParentId(parentId);
        emptyNode2.setId(RandomUtil.randomNumbers(3));

        list.add(emptyNode2);
        return list;
    }

    /**
     * 推荐架构网体
     */
    @GetMapping("tj-framework")
    public AjaxResult tjFramework(Long memberSettlePeriodId, String memberCode, Integer level) {

        Long pkMember = null;
        if (StringUtils.isNotBlank(memberCode)) {
            CuMember member = memberService.getMember(memberCode);
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
            }
//            if (!member.getPkSettleCountry().equals(SecurityUtils.getPkCountry())){
//                return AjaxResult.success();
//            }
            pkMember = member.getPkId();
        } else {
            return AjaxResult.success();
//            R<Map<Integer, BdCountry>> allCountryMap = countryServiceApi.getAllCountryMap();
//            for (Map.Entry<Integer, BdCountry> be : allCountryMap.getData().entrySet()) {
//                if (be.getKey().equals(SecurityUtils.getPkCountry())) {
//                    // 106 为多哥
//                    if (be.getKey().equals(106)) {
//                        memberCode = DgCode;
//                        CuMember member = memberService.getMember(memberCode);
//                        pkMember = member.getPkId();
//                    } else {
//
//                        memberCode =  GJParentCode;
//                        CuMember member = memberService.getMemberParentByCodeAndPkCountry(memberCode,SecurityUtils.getPkCountry());
//                        pkMember = member.getPkId();
//                    }
//
//                }
//            }
        }

        Integer period = null;
        if (memberSettlePeriodId != null) {
            CuMemberSettlePeriod csPeriod = memberSettlePeriodService.getById(memberSettlePeriodId);
            period = csPeriod.getPkId();
            // 查询 历史
            String settleTableName = TableNameConstants.CU_MEMBER_SETTLE + period;
            Integer tableNumber = memberTreeService.queryExistOracleTable(settleTableName);

            if (tableNumber == null) {
                // 表示表格存在
                //period = memberBaseService.getPeriod(null);
                if(DateUtils.getCurrentHour() < 2){
                    period = memberBaseService.getPeriod(new Date(),-2);
                }else {
                    period = memberBaseService.getPeriod(new Date(),-1);
                }
            }
        } else {
            period = memberBaseService.getPeriod(null);
        }

        if (level == null) {
            level = defaultLevel;
        }
        // 查询 历史
        String settleTableName = TableNameConstants.CU_MEMBER_SETTLE + period;
        Integer tableNumber = memberTreeService.queryExistOracleTable(settleTableName);

        if (tableNumber == null) {
            // 表示表格不存在 取值上一周
       //     settleTableName = null;
        //    String time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtil.offsetDay(new Date(),-7));
            period = memberBaseService.getPeriod(new Date(),-2);
            settleTableName = TableNameConstants.CU_MEMBER_SETTLE + period;
        }
        // 查询顶点
        CuMemberSettleExt memberSettleExt = memberTreeService.queryCuMemberTreeByPlacePkMemberTable(settleTableName, pkMember);

        if (StringUtils.isNotBlank(memberSettleExt.getParentMemberCode()) && VertexConstants.GJ30720200CODE.equals(memberSettleExt.getParentMemberCode())) {
            memberSettleExt.setParentMemberCode(memberSettleExt.getMemberCode());
        }
        memberSettleExt.setLevel(0);
        //查询下级
        //    List<CuMemberSettleExt> list = memberTreeService.queryCuMemberTreeParentTable(settleTableName, pkMember,level);
        List<CuMemberSettleExt> list = memberTreeService.queryCuMemberTreeParentTable(settleTableName, pkMember, level);
        // 无法查询到自身 所有单独查询自身并且添加
        list.add(memberSettleExt);

        List<Tree<String>> build = memberService.systemTjSetListTree(list, memberSettleExt, settleTableName, false);
        // 安置架构 无点位 追加空点位
        return AjaxResult.success(build);


    }

    /**
     * 查询最近一月所有期数
     *
     * @return
     */
    @GetMapping("get-member-settle-period")
    public AjaxResult getMemberSettlePeriod() {
        // 查询最近一月的数据
        DateTime dateTime = DateUtil.lastMonth();
        QueryWrapper<CuMemberSettlePeriod> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("SETTLE_DATE");
        queryWrapper.between("SETTLE_DATE", dateTime, new Date());
        List<CuMemberSettlePeriod> list = memberSettlePeriodService.list(queryWrapper);
        List<CuMemberSettlePeriodVo> resultList = new ArrayList<>();
        for (CuMemberSettlePeriod cuMemberSettlePeriod : list) {
            CuMemberSettlePeriodVo cuMemberSettlePeriodVo = BeanUtil.copyProperties(cuMemberSettlePeriod, CuMemberSettlePeriodVo.class);
            if (DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, cuMemberSettlePeriod.getSettleDate()).equals(DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, DateUtils.currentDate()))) {
                cuMemberSettlePeriodVo.setIsThisDay(EYesNo.YES.getIntValue());
            } else {
                cuMemberSettlePeriodVo.setIsThisDay(EYesNo.NO.getIntValue());
            }
            resultList.add(cuMemberSettlePeriodVo);
        }
        return AjaxResult.success(resultList);
    }


    /**
     * 获取头像信息
     *
     * @return
     */
    @GetMapping("get-avatar-info")
    public AjaxResult getAvatarUrl() {
        LoginUser user = userTokenService.getLoginUser();
        //R<List<GradeDTO>> list = gradeServiceApi.queryGradeConfigByCondition(user.getDataCountry());
        JSONArray array = new JSONArray();
        // 虚拟
        JSONObject other = new JSONObject();
        other.put("name", "虚拟");
        other.put("value", MemberFrameworkConstants.xuni);
        array.add(other);
        // 已注销
        JSONObject zxOther = new JSONObject();
        zxOther.put("name", "已注销");
        zxOther.put("value", MemberFrameworkConstants.LOG_OFF);
        array.add(zxOther);
        // 待激活  非中国
        if (SecurityUtils.getPkCountry() != CountryConstants.CHINA_COUNTRY) {
            JSONObject djhOther = new JSONObject();
            djhOther.put("name", "待激活");
            djhOther.put("value", MemberFrameworkConstants.toBeActivated);
            array.add(djhOther);
        }
        R<List<GradeDTO>> list = gradeServiceApi.selectGradeAll(SecurityUtils.getPkCountry());

        for (GradeDTO date : list.getData()) {
            JSONObject js = new JSONObject();
            js.put("name", date.getGradeName());
            js.put("value", date.getIcon());
            array.add(js);
        }


        return AjaxResult.success(array);
    }

    /**
     * 图片转base64
     *
     * @return
     */
    @PostMapping("get-url-base64")
    public Map<String, String> getUrlBase64(@RequestBody Map<String, String> urlMap) {
        Map<String, String> resultMap = new HashMap<>();
        for (Map.Entry<String, String> ss : urlMap.entrySet()) {
            String base64Url = Base64Util.toUrlBase64(ss.getValue());
            resultMap.put(ss.getKey() + "Base64", base64Url);
        }
        return resultMap;
    }

}
