package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muchinfo.mtp3century.service.ICommonService;
import com.muchinfo.mtp3century.service.IProfitSharService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.Constants;
import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3century.utils.AjaxResult;
import com.muchinfo.mtp3common.vo.PageResult;
import com.muchinfo.mtp3interface.mapper.*;
import com.muchinfo.mtp3pojos.entity.*;
import com.muchinfo.mtp3pojos.vo.profitshar.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Service
public class ProfitSharServiceImpl implements IProfitSharService {


    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private ICommonService iCommonService;
    @Resource
    private ISubareagroupMapper iSubareagroupMapper;
    @Resource
    private ISubdivideconfigMapper iSubdivideconfigMapper;
    @Resource
    private ISubareagroupdetailMapper iSubareagroupdetailMapper;
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private IEnumdicitemMapper iEnumdicitemMapper;
    @Resource
    private IMarketMapper iMarketMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;

    @Override
    public PageResult<ProfitSharGroupResult> queryPage(String subareagroupname, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        PageResult<ProfitSharGroupResult> result = new PageResult<>();
        List<ProfitSharGroupResult> resultList = new ArrayList<>();
        if (pageNum == null && pageSize == null) {
            //用于分润配置新增获取分组列表
            List<Subareagroup> lg = iSubareagroupMapper.selectList(new QueryWrapper<Subareagroup>().eq("areauserid", systemmanager.getAreauserid()));
            for (Subareagroup subareagroup : lg) {
                ProfitSharGroupResult profitSharGroupResult = new ProfitSharGroupResult();
                profitSharGroupResult.setSubareagroupid(subareagroup.getSubareagroupid());
                profitSharGroupResult.setSubareagroupname(subareagroup.getSubareagroupname());
                resultList.add(profitSharGroupResult);
                result.setData(resultList);
            }
            result.setCode(Constants.Success_Code_Design);
            result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        } else {
            IPage<ProfitSharGroupResult> page = new Page<>(pageNum, pageSize);
            IPage<ProfitSharGroupResult> resultIPage = iSubareagroupMapper.getSubGroupPage(page, subareagroupname, systemmanager.getAreauserid());
            result.setCode(Constants.Success_Code_Design);
            result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
            result.setPages(resultIPage.getPages());
            result.setCurrent(resultIPage.getCurrent());
            result.setTotal(resultIPage.getTotal());
            result.setPageSize(resultIPage.getSize());
            result.setData(resultIPage.getRecords());
        }
        return result;
    }

    @Override
    public AjaxResult dealMessage(ProfitSharParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getSubareagroupid() != null) {
            Subareagroup gvo = iSubareagroupMapper.selectOne(new QueryWrapper<Subareagroup>().eq("subareagroupid", param.getSubareagroupid()));
            gvo.setSubareagroupname(param.getSubareagroupname());
            gvo.setRemark(param.getRemark());
            gvo.setSubareagrouptype(param.getSubareagrouptype());
            iSubareagroupMapper.updateById(gvo);
        } else {
            Subareagroup gvo = new Subareagroup();
            gvo.setSubareagroupname(param.getSubareagroupname());
            gvo.setSubareagrouptype(param.getSubareagrouptype());
            gvo.setRemark(param.getRemark());
            gvo.setAreauserid(systemmanager.getAreauserid());
            gvo.setCreatorid(systemmanager.getAutoid());
            gvo.setCreatetime(new Date());
            iSubareagroupMapper.insert(gvo);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult delete(Long groupId, HttpServletRequest request) {
        List<Subdivideconfig> subdivideconfigList = iSubdivideconfigMapper.selectList(new QueryWrapper<Subdivideconfig>().eq("subareagroupid", groupId));
        if (CollectionUtils.isNotEmpty(subdivideconfigList)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.PROFIT_SHAR_ERROR_CODE_001.getCode(), request.getHeader("Accept-Language"));
        }

        List<Subareagroupdetail> subareagroupdetailList = iSubareagroupdetailMapper.selectList(new QueryWrapper<Subareagroupdetail>().eq("subareagroupid", groupId));
        if (CollectionUtils.isNotEmpty(subareagroupdetailList)) {
            return AjaxResult.error(Constants.Error_Code_Design, MessageType.PROFIT_SHAR_ERROR_CODE_002.getCode(), request.getHeader("Accept-Language"));
        }

        iSubareagroupMapper.deleteById(groupId);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public PageResult<ProfitSharMemberResult> memberQuery(Long subareagroupid, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        IPage<ProfitSharMemberResult> page = new Page<>(pageNum, pageSize);
        IPage<ProfitSharMemberResult> resultIPage = iSubareagroupMapper.getMemberPage(page, subareagroupid);
        PageResult<ProfitSharMemberResult> result = new PageResult<>();
        result.setCode(Constants.Success_Code_Design);
        result.setMessage(AjaxResult.dealMsg(MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language")));
        result.setPages(resultIPage.getPages());
        result.setCurrent(resultIPage.getCurrent());
        result.setTotal(resultIPage.getTotal());
        result.setPageSize(resultIPage.getSize());
        result.setData(resultIPage.getRecords());
        return result;
    }

    @Override
    public AjaxResult<ProfitSharGroupOrganResult> groupOrgan(HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        List<ProfitSharGroupOrganResult> results = iUseraccountMapper.getNoGroupSubOrgan(systemmanager.getAreauserid());
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), results);
    }

    @Override
    public AjaxResult memberAdd(ProfitSharMemberParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        Subareagroupdetail gduser = new Subareagroupdetail();
        gduser.setSubareagroupid(param.getSubareagroupid());
        gduser.setUserid(param.getUserid());
        gduser.setOperatorid(systemmanager.getAutoid());
        gduser.setUpdatetime(new Date());
        iSubareagroupdetailMapper.insert(gduser);
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult deleteMember(Long userid, HttpServletRequest request) {
        iSubareagroupdetailMapper.delete(new QueryWrapper<Subareagroupdetail>().eq("userid", userid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult<ProfitSharInitResult> initProfitShar(HttpServletRequest request) {
        ProfitSharInitResult profitSharInitResult = new ProfitSharInitResult();
        Long uid = null;
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (systemmanager.getReletype() == 3) {
            Useraccount ua = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", systemmanager.getAreauserid()));
            uid = ua.getMemberuserid();
        } else {
            uid = systemmanager.getAreauserid();
        }

        Map<String, Object> map = redisServiceUtil.getCacheMap(Constants.REDIS_HEADER_DICT + "dividefeetype");
        profitSharInitResult.setDividefeetype1name(map.get("1") == null ? "" : String.valueOf(map.get("1")));
        profitSharInitResult.setDividefeetype6name(map.get("6") == null ? "" : String.valueOf(map.get("6")));
        profitSharInitResult.setDividefeetype9name(map.get("9") == null ? "" : String.valueOf(map.get("9")));

        //获取经纪会员的市场
        List<Enumdicitem> enumDicItemList = iEnumdicitemMapper.selectList(new QueryWrapper<Enumdicitem>()
                .eq("enumitemstatus", 1)
                .eq("enumdiccode", "trademode"));
        Map<Integer, Integer> trademodeMap = new HashMap<Integer, Integer>();
        if (CollectionUtils.isNotEmpty(enumDicItemList)) {
            for (Enumdicitem enumDicItem : enumDicItemList) {
                if (enumDicItem.getParam2() != null && enumDicItem.getParam2().trim().equals("1")) {
                    trademodeMap.put(enumDicItem.getEnumitemname(), enumDicItem.getEnumitemname());
                }
            }
        }
        List<Integer> r = new ArrayList<>() ;
        r.add(7);
        List<Market> mks = iMarketMapper.getMarketsNameByUseridAndrole(uid, r,null);
        for (int i = 0; i < mks.size(); i++) {
            if (mks.get(i).getMarketid() < 1000 || !trademodeMap.containsKey(mks.get(i).getTrademode())) {
                mks.remove(i);
                i--;
            }
        }
        profitSharInitResult.setMks(mks);

        //1:交易手续费-投资者会员部分 (201, 202) -- 投资者类 (投资管理系统-101,102)
        //6:交割手续费-投资者会员部分 (20 5,206) -- 投资者类
        //9:递延费2(投资者-会员部分) (211,212) -- 投资者类
        Map<String, Object> dt = redisServiceUtil.getCacheMap(Constants.REDIS_HEADER_DICT + "dividefeetype");
        for (Map.Entry<String, Object> entry : dt.entrySet()) {
            if ("1".equals(entry.getKey())) {
                profitSharInitResult.setDividefeetype1(1);
            } else if ("6".equals(entry.getKey())) {
                profitSharInitResult.setDividefeetype6(1);
            } else if ("9".equals(entry.getKey())) {
                profitSharInitResult.setDividefeetype9(1);
            }
        }

        //交易、交割、递延
        List<ProfitSharInitConfigResult> list = iSubareagroupMapper.getDivideConfigPage(systemmanager.getAreauserid());
        if (CollectionUtils.isNotEmpty(list)) {
            Map<Long, List<ProfitSharInitConfigResult>> ft1 = new HashMap<>();
            List<ProfitSharInitConfigResult> ft2 = new ArrayList<>();
            Map<Long, List<ProfitSharInitConfigResult>> ft3 = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getDividefeetype() == 1) {
                    if (ft1.containsKey(list.get(i).getMarketid())) {
                        ft1.get(list.get(i).getMarketid()).add(list.get(i));
                    } else {
                        List<ProfitSharInitConfigResult> ft1_ = new ArrayList<>();
                        ft1_.add(list.get(i));
                        ft1.put(list.get(i).getMarketid(), ft1_);
                    }
                } else if (list.get(i).getDividefeetype() == 6) {
                    ft2.add(list.get(i));
                } else if (list.get(i).getDividefeetype() == 9) {
                    if (ft3.containsKey(list.get(i).getMarketid())) {
                        ft3.get(list.get(i).getMarketid()).add(list.get(i));
                    } else {
                        List<ProfitSharInitConfigResult> ft3_ = new ArrayList<>();
                        ft3_.add(list.get(i));
                        ft3.put(list.get(i).getMarketid(), ft3_);
                    }
                }
            }
            //交易
            profitSharInitResult.setFt1(ft1);
            //交割
            profitSharInitResult.setFt2(ft2);
            //递延
            profitSharInitResult.setFt3(ft3);
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"), profitSharInitResult);
    }

    @Override
    public AjaxResult delSOrganSec(ProfitSharSorgansecParam param, HttpServletRequest request) {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", iCommonService.getUserLoginCode(request)));
        if (param.getIsedit() == 0) {
            List<Subdivideconfig> list = iSubdivideconfigMapper.selectList(new QueryWrapper<Subdivideconfig>()
                    .eq("dividefeetype", param.getDividefeetype())
                    .eq("subareagroupid", param.getSubareagroupid())
                    .eq("marketid", param.getMarketid()));
            if (CollectionUtils.isNotEmpty(list)) {
                return AjaxResult.error(Constants.Error_Code_Design, MessageType.PROFIT_SHAR_ERROR_CODE_003.getCode(), request.getHeader("Accept-Language"));
            }
            Subdivideconfig config = getSubdivideconfig(param, systemmanager);
            iSubdivideconfigMapper.insert(config);
        } else {
            Subdivideconfig sd = iSubdivideconfigMapper.selectOne(new QueryWrapper<Subdivideconfig>()
                    .eq("dividefeetype", param.getDividefeetype())
                    .eq("subareagroupid", param.getSubareagroupid())
                    .eq("marketid", param.getMarketid())
                    .eq("goodsid", 0L));
            sd.setDividemode(param.getDividemode());
            sd.setDividetype(param.getDividetype());
            if (param.getDividetype() == 1) {
                BigDecimal bw = new BigDecimal(100);
                sd.setDividevalue(param.getDividevalue().divide(bw));
            } else {
                sd.setDividevalue(param.getDividevalue());
            }
            iSubdivideconfigMapper.update(sd, new QueryWrapper<Subdivideconfig>().eq("subareagroupid", sd.getSubareagroupid()));
        }
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    @Override
    public AjaxResult deleteSOrganSec(Integer dividefeetype, Long marketid, Long subareagroupid, HttpServletRequest request) {
        iSubdivideconfigMapper.delete(new QueryWrapper<Subdivideconfig>()
                .eq("dividefeetype", dividefeetype)
                .eq("subareagroupid", subareagroupid)
                .eq("marketid", marketid));
        return AjaxResult.success(Constants.Success_Code_Design, MessageType.MESSAGE_CODE_SYSTEM001.getCode(), request.getHeader("Accept-Language"));
    }

    private Subdivideconfig getSubdivideconfig(ProfitSharSorgansecParam param, Systemmanager systemmanager) {
        Subdivideconfig config = new Subdivideconfig();
        config.setDividevalue(param.getDividevalue());
        config.setDividefeetype(param.getDividefeetype());
        config.setMarketid(param.getMarketid());
        config.setSubareagroupid(param.getSubareagroupid());
        config.setDividetype(param.getDividetype());
        config.setDividemode(param.getDividemode());
        config.setCreatetime(new Date());
        config.setCreatorid(systemmanager.getAutoid());
        config.setGoodsid(0L);
        if (param.getDividetype() == 1) {
            BigDecimal bw = new BigDecimal(100);
            config.setDividevalue(param.getDividevalue().divide(bw));
        }
        return config;
    }
}
