package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.system.entity.Area;
import com.gxwebsoft.common.system.service.AreaService;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.mapper.ExpressTemplateMapper;
import com.gxwebsoft.shop.service.ExpressTemplateDetailService;
import com.gxwebsoft.shop.service.ExpressTemplateService;
import com.gxwebsoft.shop.param.ExpressTemplateParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 运费模板Service实现
 *
 * @author 科技小王子
 * @since 2024-11-05 18:03:28
 */
@Service
public class ExpressTemplateServiceImpl extends ServiceImpl<ExpressTemplateMapper, ExpressTemplate> implements ExpressTemplateService {

    @Resource
    private ExpressTemplateDetailService expressTemplateDetailService;
    @Resource
    private AreaService areaService;
    @Resource
    private GoodsService goodsService;

    @Autowired
    private RequestUtil requestUtil;


    @Override
    public PageResult<ExpressTemplate> pageRel(ExpressTemplateParam param) {
        PageParam<ExpressTemplate, ExpressTemplateParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ExpressTemplate> list = baseMapper.selectPageRel(page, param);
        for (ExpressTemplate expressTemplate : list) {
            expressTemplate.setDetailList(expressTemplateDetailService.listByTemplateId(expressTemplate.getId()));
        }
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ExpressTemplate> listRel(ExpressTemplateParam param) {
        List<ExpressTemplate> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ExpressTemplate, ExpressTemplateParam> page = new PageParam<>();
//        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public ExpressTemplate getByIdRel(Integer id) {
        ExpressTemplateParam param = new ExpressTemplateParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public BigDecimal calExpressAmount(List<OrderGoods> orderGoodsList, UserAddress userAddress) {
        requestUtil.setTenantId("10559");
        ApiResult<?> dictDataApiResult = requestUtil.getDictData(856);
        Map<String, Object> dictDataApiResultData = (Map<String, Object>) dictDataApiResult.getData();
        List<Object> dictDataList = (List<Object>) dictDataApiResultData.get("list");
        Map<String, Object> dictData1 = JSONUtil.parseObject(JSONUtil.toJSONString(dictDataList.get(0)), Map.class);
        String policy = (String) dictData1.get("dictDataCode");
        List<BigDecimal> amountList = new ArrayList<>();
        BigDecimal finalAmount = BigDecimal.ZERO;
        for (OrderGoods orderGoods : orderGoodsList) {
            Goods goods = orderGoods.getGoods();
            if (goods == null) goods = goodsService.getById(orderGoods.getGoodsId());
            if (goods != null && goods.getExpressTemplateId() != null) {
                String userAddressCity = userAddress.getCity();
                String userAddressProvince = userAddress.getProvince();
                Area province = areaService.areaInfoByName(userAddressProvince, 1);
                if (province != null) {
                    Integer provinceId = province.getId();
                    Area city = areaService.areaInfoByName(userAddressCity, 2);
                    if (city != null && city.getFid().equals(provinceId)) {
                        Integer cityId = city.getId();
                        ExpressTemplateDetail templateDetail = expressTemplateDetailService.getOne(
                                new LambdaQueryWrapper<ExpressTemplateDetail>()
                                        .eq(ExpressTemplateDetail::getTemplateId, goods.getExpressTemplateId())
                                        .eq(ExpressTemplateDetail::getCityId, cityId)
                                        .eq(ExpressTemplateDetail::getProvinceId, provinceId)
                                        .last("limit 1")
                        );
                        if (templateDetail != null) {
                            ExpressTemplate expressTemplate = getByIdRel(goods.getExpressTemplateId());
                            BigDecimal amount = expressTemplate.getFirstAmount();
                            // 按件
                            BigDecimal extraAmount = BigDecimal.ZERO;
                            if (expressTemplate.getExtraNum().compareTo(BigDecimal.ZERO) > 0) {
                                extraAmount = expressTemplate.getExtraAmount().divide(expressTemplate.getExtraNum(), RoundingMode.HALF_UP);
                            }
                            BigDecimal totalNumOrWeight = BigDecimal.ZERO;
                            if (expressTemplate.getType().equals(0)) {
                                totalNumOrWeight = BigDecimal.valueOf(orderGoods.getTotalNum());
                            }
                            // 按重量
                            else if (expressTemplate.getType().equals(1)) {
                                totalNumOrWeight = goods.getWeight().multiply(BigDecimal.valueOf(orderGoods.getTotalNum()));
                            }
                            if (totalNumOrWeight.compareTo(expressTemplate.getFirstNum()) < 0) {
                                amount = amount.add(expressTemplate.getFirstAmount().add(expressTemplate.getExtraAmount()));
                            } else {
                                amount = amount.add(extraAmount.multiply(totalNumOrWeight.subtract(expressTemplate.getExtraAmount())));
                            }
                            amountList.add(amount);
                        }
                    }
                }
            }
        }
        System.out.println(amountList.stream().reduce(BigDecimal.ZERO, BigDecimal::add));
        return switch (policy) {
            case "10" -> amountList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
            case "20" -> amountList.stream().min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            case "30" -> amountList.stream().max(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            default -> finalAmount;
        };
    }
}
