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 com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.constant.*;
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.ext.CuMemberRetailSExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
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.*;

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

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

    @DubboReference
    IUserServiceApi iUserServiceApi;
    @DubboReference
    IGradeServiceApi iGradeServiceApi;

    /**
     * 推荐架构网体
     */
    @AccessPermissions("Recommend")
    @GetMapping("/tj-framework")
    public AjaxResult tjFramework(Long memberSettlePeriodId, String memberCode) {
        // 体系
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        List<Integer> vertexIdList = userAuthorityDTO.getVertexIdList();
        List<Long> userVertexList = userAuthorityDTO.getUserVertexList();

        // 要查询的顶点会员
        Long pkMember;
        if (StringUtils.isNotBlank(memberCode)) {
            CuMember member = iCuMemberService.getMember(memberCode);
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
            }
            // 传入会员编号参数不为空，则使用传入的顶点
            pkMember = member.getPkId();
        } else {
            if (userVertexList != null && userVertexList.size() > 0) {
                // 能查询的第一个体系的会员ID
                CuMember member = iCuMemberService.getMember(userVertexList.get(0));
                pkMember = member.getPkId();
            } else {
                // 都没有，默认使用新零售顶点
                CuMember member = iCuMemberService.getMember(SysConstants.RETAIL_TOP_CODE);
                pkMember = member.getPkId();
            }
        }

        // 当前时间
        String time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date());

        Integer period = null;
        Date settleDate = null;
        if (memberSettlePeriodId != null) {
            // 传入期数
            CuMemberSettlePeriod csPeriod = iCuMemberSettlePeriodService.getById(memberSettlePeriodId);
            period = csPeriod.getPkId();
            settleDate = csPeriod.getSettleDate();
        } else {
            // 没有传入期数，按当前时间取期数
            CuMemberSettlePeriod csPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
            if (csPeriod != null) {
                period = csPeriod.getPkId();
                settleDate = csPeriod.getSettleDate();
            }
        }

        if (settleDate != null && DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, settleDate).equals(DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, new Date()))) {
            // 查询当天 (秒结)
            // 会员秒结表
            String settleTableName = TableNameConstants.CU_MEMBER_RETAIL_S + period;
            // 校验秒结表是否存在
            Integer tableNumber = iCuMemberTreeService.queryExistOracleTable(settleTableName);
            if (tableNumber != null && tableNumber == 1) {
                // 表格存在
                List<CuMemberRetailSExt> memberRetailExtList;
                // 查询今日会员表是否有值
                if (iCuMemberTreeService.selectByTreeMemberCount(settleTableName, pkMember) > 0) {
                    // 秒结表存在
                    memberRetailExtList = iCuMemberTreeService.queryCuMemberTreeParentTable(settleTableName, pkMember, vertexIdList);
                } else {
                    // 秒结表不存在，取昨天的结算表
                    DateTime dateTime = DateUtil.offsetDay(DateUtils.currentDate(), -1);
                    time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dateTime);
                    CuMemberSettlePeriod csPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
                    if (csPeriod != null) {
                        period = csPeriod.getPkId();
                    }
                    settleTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
                    memberRetailExtList = iCuMemberTreeService.queryCuMemberTreeParentTable(settleTableName, pkMember, vertexIdList);
                }
                // 查询顶点
                CuMemberRetailSExt cuMemberSettleExt = iCuMemberTreeService.queryCuMemberTreeByPlacePkMemberTable(settleTableName, pkMember);
                if (VertexConstants.GJ30720200CODE.equals(cuMemberSettleExt.getParentMemberCode())) {
                    cuMemberSettleExt.setParentMemberCode(cuMemberSettleExt.getMemberCode());
                }
                cuMemberSettleExt.setLevel(0);
                // 添加自身
                memberRetailExtList.add(cuMemberSettleExt);

                // 安置架构 无点位 追加空点位
                return AjaxResult.success(iCuMemberService.systemListTree(memberRetailExtList, cuMemberSettleExt, settleTableName));
            } else {
                // 没有秒结表
                if (tableNumber == null) {
                    settleTableName = null;
                }
                //查询下级
                List<CuMemberRetailSExt> memberRetailExtList = iCuMemberTreeService.queryCuMemberTreeParentTable(settleTableName, pkMember, vertexIdList);

                // 查询顶点
                CuMemberRetailSExt cuMemberSettleExt = iCuMemberTreeService.queryCuMemberTreeByPlacePkMemberTable(settleTableName, pkMember);
                if (VertexConstants.GJ30720200CODE.equals(cuMemberSettleExt.getParentMemberCode())) {
                    cuMemberSettleExt.setParentMemberCode(cuMemberSettleExt.getMemberCode());
                }
                cuMemberSettleExt.setLevel(0);
                // 无法查询到自身 所有单独查询自身并且添加
                memberRetailExtList.add(cuMemberSettleExt);

                // 安置架构 无点位 追加空点位
                return AjaxResult.success(iCuMemberService.systemListTree(memberRetailExtList, cuMemberSettleExt, settleTableName));
            }
        } else {
            DateTime dateTime = DateUtil.offsetDay(DateUtils.currentDate(), -1);
            time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dateTime);
            CuMemberSettlePeriod csPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
            if (csPeriod != null) {
                period = csPeriod.getPkId();
            }
            // 查询 历史
            String settleTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
            Integer tableNumber = iCuMemberTreeService.queryExistOracleTable(settleTableName);

            if (tableNumber == null) {
                // 表示表格存在
                settleTableName = null;
            }

            // 查询下级
            List<CuMemberRetailSExt> memberRetailExtList = iCuMemberTreeService.queryCuMemberTreeParentTable(settleTableName, pkMember, vertexIdList);

            // 查询顶点
            CuMemberRetailSExt cuMemberSettleExt = iCuMemberTreeService.queryCuMemberTreeByPlacePkMemberTable(settleTableName, pkMember);
            if (StringUtils.isNotBlank(cuMemberSettleExt.getParentMemberCode()) && VertexConstants.GJ30720200CODE.equals(cuMemberSettleExt.getParentMemberCode())) {
                cuMemberSettleExt.setParentMemberCode(cuMemberSettleExt.getMemberCode());
            }
            cuMemberSettleExt.setLevel(0);
            // 无法查询到自身 所有单独查询自身并且添加
            memberRetailExtList.add(cuMemberSettleExt);

            // 安置架构 无点位 追加空点位
            return AjaxResult.success(iCuMemberService.systemListTree(memberRetailExtList, cuMemberSettleExt, settleTableName));
        }
    }

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

}
