package com.bonus.canteen.core.reportforms.service.impl;

import com.bonus.canteen.core.reportforms.beans.CanteenOrg;
import com.bonus.canteen.core.reportforms.beans.CanteenRecord;
import com.bonus.canteen.core.reportforms.beans.OrgConsume;
import com.bonus.canteen.core.reportforms.mapper.OrgConsumeMapper;
import com.bonus.canteen.core.reportforms.service.reportformsService;
import com.bonus.common.houqin.utils.SM4EncryptUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class reportformsServiceImpl implements reportformsService {
    @Resource
    private OrgConsumeMapper mapper;
    @Override
    public List<OrgConsume> getOrgConsumeList(OrgConsume orgConsume) {
            // 查询食堂、超市的所有数据信息
            List<Map<String, Object>> consumeRecords = mapper.selectConsumeRecords(orgConsume);
            //查询预订的订单信息
            List<Map<String, Object>> reserveRecords = mapper.selectReserveRecords(orgConsume);
            //查询区域关联的字段信息
            List<Map<String, String>> areaOrgMaps = mapper.selectAreaOrgMap();

            // area -> org 映射
            Map<String, String> areaToOrg = new HashMap<>();
            for (Map<String, String> map : areaOrgMaps) {
                areaToOrg.put(map.get("area_name"), map.get("org_name"));
            }

            // 初始化结果
            Map<String, OrgConsume> resultMap = new HashMap<>();
            for (Map<String, Object> r : reserveRecords) {
                String orgName = (String) r.get("orgName");
                BigDecimal reserveAmount = (r.get("reserveAmount") != null) ?
                        new BigDecimal(r.get("reserveAmount").toString()) : BigDecimal.ZERO;

                OrgConsume oc = new OrgConsume();
                oc.setOrgName(orgName);
                oc.setReserveAmount(reserveAmount);
                resultMap.put(orgName, oc);
            }
            // 合并消费记录
            for (Map<String, Object> c : consumeRecords) {
                String areaName = (String) c.get("areaName");
                String conSource = (String) c.get("conSource");
                BigDecimal amount = (c.get("amount") != null) ?
                        new BigDecimal(c.get("amount").toString()).abs() : BigDecimal.ZERO;
                String orgName = areaToOrg.get(areaName);
                if (orgName == null) {
                    continue; // 没有映射关系，跳过
                }
                OrgConsume oc = resultMap.getOrDefault(orgName, new OrgConsume());
                oc.setOrgName(orgName);

                if ("canteen".equals(conSource)) {
                    oc.setCanteenAmount(oc.getCanteenAmount().add(amount));
                } else if ("super".equals(conSource)) {
                    oc.setSuperAmount(oc.getSuperAmount().add(amount));
                }else if("station".equals(conSource)){
                    //
                    //驿站支付sql查询无法达到目标，从子表重新查询
                   // oc.setH5Amount(oc.getH5Amount().add(amount));
                    OrgConsume neworgConsume = new OrgConsume();
                    neworgConsume.setStartPayTime(orgConsume.getStartPayTime());
                    neworgConsume.setEndPayTime(orgConsume.getEndPayTime());
                    neworgConsume.setOrgName(orgName.replace("食堂", ""));
                    List<OrgConsume> orgConsumes = getlistByOtherlist(neworgConsume);
                    BigDecimal othersum = orgConsumes.stream().map(OrgConsume::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    oc.setH5Amount(othersum);
                }else if("deduction".equals(conSource)){
                    oc.setDeductionAmount(oc.getDeductionAmount().add(amount));
                }
                resultMap.put(orgName, oc);
            }
            //处理驿站退款情况逻辑
           //  int yzsum = mapper.yzSumMoney(orgConsume);

            return new ArrayList<>(resultMap.values());
    }

    @Override
    public List<OrgConsume> getlistByArealist(OrgConsume orgConsume) {
        List<OrgConsume> orgConsumes = mapper.getlistByArealist(orgConsume)
                .stream()
                .peek(c -> {
                    if (c.getCustName() != null && !c.getCustName().isEmpty()) {
                        try {
                            c.setCustName(SM4EncryptUtils.sm4Decrypt(c.getCustName()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .collect(Collectors.toList());
        return orgConsumes;
    }

    @Override
    public List<OrgConsume> getlistBySuperlist(OrgConsume orgConsume) {
        List<OrgConsume> orgConsumes = mapper.getlistBySuperlist(orgConsume)
                .stream()
                .peek(c -> {
                    if (c.getCustName() != null && !c.getCustName().isEmpty()) {
                        try {
                            c.setCustName(SM4EncryptUtils.sm4Decrypt(c.getCustName()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .collect(Collectors.toList());
        return orgConsumes;
    }
    @Override
    public List<OrgConsume> getDeductionlist(OrgConsume orgConsume) {
        List<OrgConsume> orgConsumes = mapper.getDeductionlist(orgConsume)
                .stream()
                .peek(c -> {
                    if (c.getCustName() != null && !c.getCustName().isEmpty()) {
                        try {
                            c.setCustName(SM4EncryptUtils.sm4Decrypt(c.getCustName()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .collect(Collectors.toList());
        return orgConsumes;
    }
    @Override
    public List<OrgConsume> getlistByH5list(OrgConsume orgConsume) {
        List<OrgConsume> orgConsumes = mapper.getlistByH5list(orgConsume)
                .stream()
                .peek(c -> {
                    if (c.getCustName() != null && !c.getCustName().isEmpty()) {
                        try {
                            c.setCustName(SM4EncryptUtils.sm4Decrypt(c.getCustName()));
                        } catch (Exception e) {
                           e.printStackTrace();
                        }
                    }
                })
                .collect(Collectors.toList());
        return orgConsumes;
    }

    @Override
    public List<OrgConsume> getlistByOtherlist(OrgConsume orgConsume) {
        List<OrgConsume> orgConsumes = mapper.getlistByOtherlist(orgConsume)
                .stream()
                .peek(c -> {
                    if (c.getCustName() != null && !c.getCustName().isEmpty()) {
                        try {
                            c.setCustName(SM4EncryptUtils.sm4Decrypt(c.getCustName()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .collect(Collectors.toList());

// 如果列表为空，直接返回
        if (orgConsumes == null || orgConsumes.isEmpty()) {
            return orgConsumes;
        }
// 去重退款记录（flowType=130，payTime相同保留第一次）
        Set<String> seenPayTimes = new HashSet<>();
        orgConsumes.removeIf(c -> c.getFlowType() == 130 && !seenPayTimes.add(c.getPayTime()));

        return orgConsumes;

    }

    @Override
    public List<CanteenRecord> getPeoplelist(CanteenRecord orgConsume) {
        if(orgConsume.getCustName() != null){
            // 解密
            try {
                orgConsume.setCustName(SM4EncryptUtils.sm4Encrypt(orgConsume.getCustName()));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        List<CanteenRecord> list = mapper.getPeoplelist(orgConsume);
        for (CanteenRecord c : list) {
            try {
                if (c.getCustName() != null && !c.getCustName().isEmpty()) {
                    c.setCustName(SM4EncryptUtils.sm4Decrypt(c.getCustName()));
                }
                if (c.getPhone() != null) {
                    String phone = SM4EncryptUtils.sm4Decrypt(c.getPhone());
                    if (phone.length() == 11) {
                        phone = phone.substring(0, 3) + "****" + phone.substring(7);
                    }
                    c.setPhone(phone);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public List<CanteenOrg> getOrgTree() {
        List<CanteenOrg> all = mapper.selectAllOrgs();
        return buildTree(all, -1L); // 假设顶级 super_id = 0
    }


    private List<CanteenOrg> buildTree(List<CanteenOrg> list, Long parentId) {
        List<CanteenOrg> tree = new ArrayList<>();
        for (CanteenOrg org : list) {
            if (org.getSuperId().equals(parentId)) {
                org.setChildren(buildTree(list, org.getOrgId()));
                tree.add(org);
            }
        }
        return tree;
    }

}
