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 com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.achieve.CuMemberTree;
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.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.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.IUserServiceApi;
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.util.*;
import java.util.stream.Collectors;

/**
 * 架构管理
 */
@RestController
@RequestMapping("/manage/member-structure")
public class MemberStructureController extends BaseController {

    @Autowired
    private ICuMemberBaseService iCuMemberBaseService;
    @Autowired
    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;
    @Autowired
    private ICuMemberTreeService iCuMemberTreeService;
    @Autowired
    private ICuMemberService iCuMemberService;

    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    IUserServiceApi iUserServiceApi;
    /**
     * 默认层数
     */
    Integer defaultLevel = 7;

    /**
     * 安置架构网体
     */
    @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();

        if (StringUtils.isEmpty(memberCode)) {
            return AjaxResult.success();
        }
        CuMember member = iCuMemberService.getMemberByCode(memberCode);
        if (null == member) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }
        Long pkMember = member.getPkId();

        if (null != vertexIdList && StringUtils.isNotBlank(memberCode)) {
            // 体系不为空 并且会员编号不为空 只能查询自己伞下以及自己的
            List<CuMemberExt> memberExtList = iCuMemberService.checkMemberVertex(vertexIdList, memberCode);
            if (memberExtList.size() == 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.QUERY_VERTEX_CODE));
            }
        }
        Integer period = null;
        if (memberSettlePeriodId != null) {
            CuMemberSettlePeriod csPeriod = iCuMemberSettlePeriodService.getById(memberSettlePeriodId);
            if (csPeriod != null) {
                period = csPeriod.getPkId();
            }
            // 查询 历史
            String settleTableName = TableNameConstants.CU_MEMBER_SETTLE_D + period;
            Integer tableNumber = iCuMemberTreeService.queryExistOracleTable(settleTableName);
            if (tableNumber == null) {
                // 表示表格存在
                if (DateUtils.getCurrentHour() < 2) {
                    period = iCuMemberBaseService.getPeriod(new Date(), -2);
                } else {
                    period = iCuMemberBaseService.getPeriod(new Date(), -1);
                }
            }
        } else {
            period = iCuMemberBaseService.getPeriod(null);
        }

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

            List<MemberSettleTreeExt> memberSettleList = iCuMemberService.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());
                        }
                    }
                    cuMemberSettleExt.setLevelMemberSettleList(msList);
                    resultList.add(cuMemberSettleExt);
                }
            }
            List<Tree<String>> build = iCuMemberService.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();

        if (StringUtils.isEmpty(memberCode)) {
            return AjaxResult.success();
        }
        CuMember member = iCuMemberService.getMemberByCode(memberCode);
        if (null == member) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }
        Long pkMember = member.getPkId();

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

            if (tableNumber == null) {
                // 表示表格存在
                if (DateUtils.getCurrentHour() < 2) {
                    period = iCuMemberBaseService.getPeriod(new Date(), -2);
                } else {
                    period = iCuMemberBaseService.getPeriod(new Date(), -1);
                }
            }
        } else {
            period = iCuMemberBaseService.getPeriod(null);
        }
        // 查询 历史
        String settleTableName = TableNameConstants.CU_MEMBER_SETTLE_D + period;
        Integer tableNumber = iCuMemberTreeService.queryExistOracleTable(settleTableName);
        if (tableNumber != null && tableNumber == 1) {
            // 查询顶点
            CuMemberSettleExt memberSettleExt = iCuMemberTreeService.queryCuMemberTreeByPkMemberTable(pkMember);
            if (VertexConstants.GJ30720200CODE.equals(memberSettleExt.getParentMemberCode())) {
                memberSettleExt.setParentMemberCode(memberSettleExt.getMemberCode());
            }
            memberSettleExt.setLevel(0);
            //查询下级
            List<CuMemberSettleExt> list = iCuMemberTreeService.queryCuMemberTreePlaceParentHistoryFramework(settleTableName, pkMember, new ArrayList<>(), level);
            // 无法查询到自身 所有单独查询自身并且添加
            list.add(memberSettleExt);
            // 会员主键
            List<Long> pkMemberIds = list.stream().map(CuMemberTree::getPkMember).collect(Collectors.toList());
            // 按照安置部门排序
            Map<Long, List<CuMemberSettleExt>> settleList = list.stream().collect(Collectors.groupingBy(CuMemberSettleExt::getPkPlaceParent));
            List<MemberSettleTreeExt> memberSettleList = iCuMemberService.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 = iCuMemberService.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 = iCuMemberService.systemAzSetFirstListTree(resultList, memberSettleExt);
            // 安置架构 无点位 追加空点位
            return AjaxResult.success(build);
        }
        return AjaxResult.success();
    }

    /**
     * 推荐架构网体
     */
    @GetMapping("/tj-framework")
    public AjaxResult tjFramework(Long memberSettlePeriodId, String memberCode, Integer level) {
        if (StringUtils.isEmpty(memberCode)) {
            return AjaxResult.success();
        }
        CuMember member = iCuMemberService.getMember(memberCode);
        if (member == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }
        Long pkMember = member.getPkId();

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

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

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

        if (tableNumber == null) {
            // 表示表格不存在 取值上一周
            period = iCuMemberBaseService.getPeriod(new Date(), -2);
            settleTableName = TableNameConstants.CU_MEMBER_SETTLE + period;
        }
        // 查询顶点
        CuMemberSettleExt memberSettleExt = iCuMemberTreeService.queryCuMemberTreeByPlacePkMemberTable(settleTableName, pkMember);

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

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

    /**
     * 查询最近一月所有期数
     *
     * @return
     */
    @GetMapping("/get-member-settle-period")
    public AjaxResult getMemberSettlePeriod() {
        // 查询最近一月的数据
        DateTime dateTime = DateUtil.lastMonth();
        LambdaQueryWrapper<CuMemberSettlePeriod> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(CuMemberSettlePeriod::getSettleDate, dateTime, new Date());
        queryWrapper.orderByDesc(CuMemberSettlePeriod::getSettleDate);

        List<CuMemberSettlePeriod> list = iCuMemberSettlePeriodService.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() {
        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 = iGradeServiceApi.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;
    }

}
