package com.sckw.payment.service.operate;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.vo.TableTop;
import com.sckw.core.utils.StringTimeUtil;
import com.sckw.payment.dao.KwpSettlementLogisticsMapper;
import com.sckw.payment.model.constant.LogisticsUnitType;
import com.sckw.payment.model.constant.SettlementEnum;
import com.sckw.payment.model.dto.ISettlement;
import com.sckw.payment.model.vo.SettlementLogistics;
import com.sckw.payment.model.vo.req.SettlementReq;
import com.sckw.payment.model.vo.res.SettlementLogisticsSumVo;
import com.sckw.payment.utils.CommonValidator;
import com.sckw.payment.utils.PageMoreRes;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;


@RequiredArgsConstructor
@Service
@Slf4j
public class SettlementLogisticsService {
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    private final KwpSettlementLogisticsMapper settlementLogisticsMapper;

    /**
     * 字典转换
     *
     * @param list 结算单列表数据
     */
    private void changeDict(List<? extends ISettlement> list) {
        //字典等数据转换
        Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.TRADE_TYPE.getType());
        for (ISettlement iSettlement : list) {
            String trading = iSettlement.getTrading();
            SysDictResDto sysDictResDto = dictResDtoMap.get(trading);
            if (Objects.nonNull(sysDictResDto)) {
                iSettlement.setTradingLabel(sysDictResDto.getLabel());
            }
            iSettlement.setStatusLabel(SettlementEnum.getStatusDesc(iSettlement.getStatus()));
        }
    }

    public List<TableTop> count(SettlementReq settlementReq) {
        settlementReq.setUnitType(LogisticsUnitType.SHIPPER);
        settlementReq.setUnitTypeTwo(LogisticsUnitType.CARRIER);
        validSettlementReq(settlementReq);

        Map<String, Long> count = settlementLogisticsMapper.count(settlementReq);
        List<TableTop> res = new ArrayList<>(4);
        for (SettlementEnum value : SettlementEnum.values()) {
            TableTop tableTop = new TableTop();
            tableTop.setName(value.getDesc());
            tableTop.setValue(value.getStatus());
            tableTop.setTotal(Math.toIntExact(count.get(value.getLabel())));
            res.add(tableTop);
        }
        return res;
    }

    /**
     * 列表分页查询
     *
     * @param settlementReq
     * @return
     */
    public PageMoreRes<SettlementLogistics> list(SettlementReq settlementReq) {
        settlementReq.setUnitType(LogisticsUnitType.SHIPPER);
        settlementReq.setUnitTypeTwo(LogisticsUnitType.CARRIER);
        //验证相关参数
        validSettlementReq(settlementReq);
        //添加默认分页数据
        PageHelper.startPage(settlementReq.getPage(), settlementReq.getPageSize());
        //查询分页数据
        List<SettlementLogistics> kwpLedgerLogisticsList = settlementLogisticsMapper.list(settlementReq);
        //查询同样条件下的合计
        SettlementLogisticsSumVo settlementLogisticsSum = settlementLogisticsMapper.sum(settlementReq);

        // 对查询结果进行处理，转换 status 等状态值为对应中文描述
        return new PageMoreRes<>(getSettlementLogisticsDtoPageRes(kwpLedgerLogisticsList), settlementLogisticsSum);
    }


    public List<SettlementLogistics> exportList(SettlementReq settlementReq) {
        validSettlementReq(settlementReq);
        List<SettlementLogistics> settlementLogistics = settlementLogisticsMapper.exportList(settlementReq, settlementReq.getIdList());
        changeDict(settlementLogistics);
        for (SettlementLogistics tmp : settlementLogistics) {
            UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(tmp.getCreateBy());
            tmp.setCreateByLabel(Objects.nonNull(userCacheResDto) ? userCacheResDto.getName() : "");
        }
        return settlementLogistics;
    }


    private void validSettlementReq(SettlementReq settlementReq) {
        //判断时间是否成对
        CommonValidator.isValidCoexisting(settlementReq.getStartCreateTime(), settlementReq.getEndCreateTime(), "");
        CommonValidator.isValidCoexisting(settlementReq.getStartReceiptTime(), settlementReq.getEndReceiptTime(), "预计付款开始和结束时间");
        //补全时间信息
        if (StringUtils.isNotBlank(settlementReq.getStartCreateTime())) {
            settlementReq.setStartCreateTime(StringTimeUtil.fillStart(settlementReq.getStartCreateTime()));
        }
        if (StringUtils.isNotBlank(settlementReq.getEndCreateTime())) {
            settlementReq.setEndCreateTime(StringTimeUtil.fillEnd(settlementReq.getEndCreateTime()));
        }
        if (StringUtils.isNotBlank(settlementReq.getStartReceiptTime())) {
            settlementReq.setStartCreateTime(StringTimeUtil.fillStart(settlementReq.getStartReceiptTime()));
        }
        if (StringUtils.isNotBlank(settlementReq.getEndReceiptTime())) {
            settlementReq.setEndCreateTime(StringTimeUtil.fillEnd(settlementReq.getEndReceiptTime()));
        }
    }

    private PageInfo<SettlementLogistics> getSettlementLogisticsDtoPageRes(List<SettlementLogistics> kwpLedgerLogisticsList) {
        Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.TRADE_TYPE.getType());
        Map<Long, UserCacheResDto> map = new HashMap<>(Global.NUMERICAL_SIXTEEN);

        for (SettlementLogistics settlementLogisticsDto : kwpLedgerLogisticsList) {
            SysDictResDto sysDictResDto = dictResDtoMap.get(settlementLogisticsDto.getTrading());
            if (Objects.nonNull(sysDictResDto)) {
                settlementLogisticsDto.setTradingLabel(sysDictResDto.getLabel());
            }
            //更改创建、更新人名称及字段
            settlementLogisticsDto.setStatusLabel(SettlementEnum.getStatusDesc(settlementLogisticsDto.getStatus()));
            if (settlementLogisticsDto.getTotalPrice() != null) {
                if (settlementLogisticsDto.getActualPrice() != null) {
                    settlementLogisticsDto.setWaitPrice(settlementLogisticsDto.getTotalPrice().subtract(settlementLogisticsDto.getActualPrice()));
                } else {
                    settlementLogisticsDto.setWaitPrice(settlementLogisticsDto.getTotalPrice());
                }
            } else {
                settlementLogisticsDto.setWaitPrice(new BigDecimal(0));
            }
            //"创建人名称"
            settlementLogisticsDto.setCreateByLabel("创建人名称");
            //"更新人名称"
            settlementLogisticsDto.setUpdateByLabel("更新人名称");

            Long createBy = settlementLogisticsDto.getCreateBy();
            Long updateBy = settlementLogisticsDto.getUpdateBy();
            UserCacheResDto userCacheResDto = map.get(createBy);
            if (Objects.isNull(userCacheResDto)) {
                //通过缓存拿对应数据
                userCacheResDto = remoteSystemService.queryUserCacheById(createBy);
                map.put(createBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                //写入对应数据
                settlementLogisticsDto.setCreateByLabel(userCacheResDto.getName());
            }
            userCacheResDto = map.get(updateBy);
            if (Objects.isNull(userCacheResDto)) {
                //通过缓存拿对应数据
                userCacheResDto = remoteSystemService.queryUserCacheById(updateBy);
                map.put(updateBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                //写入对应数据
                settlementLogisticsDto.setUpdateByLabel(userCacheResDto.getName());
            }
        }
        return new PageInfo<>(kwpLedgerLogisticsList);
    }
}
