package com.gree.mall.manager.logic;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.Freight.FreightTemplateBean;
import com.gree.mall.manager.bean.Freight.RegionTreeBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.enums.RegionLevelEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.FreightTemplate;
import com.gree.mall.manager.plus.entity.FreightTemplateDetail;
import com.gree.mall.manager.plus.entity.Region;
import com.gree.mall.manager.plus.service.FreightTemplateDetailService;
import com.gree.mall.manager.plus.service.FreightTemplateService;
import com.gree.mall.manager.plus.service.RegionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FreightLogic {

    @Autowired
    FreightTemplateService freightTemplateService;
    @Autowired
    FreightTemplateDetailService freightTemplateDetailService;
    @Autowired
    RegionService regionService;
    @Autowired
    CommonLogic commonLogic;

    /**
     * 运费模板列表
     */
    public IPage<FreightTemplate> list(HttpServletRequest request, String name, Boolean status, String startTime, String endTime, Integer pageNo, Integer pageSize) {

        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();

        return freightTemplateService.lambdaQuery()
                .like(StringUtils.isNotEmpty(name), FreightTemplate::getName, name)
                .eq(status != null, FreightTemplate::getStatus, status)
                .between(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime), FreightTemplate::getCreateTime, startTime, endTime + " 23:59:59")
                .page(new Page<>(pageNo, pageSize));
    }

    /**
     * 运费模板详情
     */
    public FreightTemplateBean detail(String freightTemplateId) {
        FreightTemplate freightTemplate = freightTemplateService.getById(freightTemplateId);
        FreightTemplateBean bean = new FreightTemplateBean();
        BeanUtils.copyProperties(freightTemplate, bean);
        //查询列表
        List<FreightTemplateDetail> list = freightTemplateDetailService.lambdaQuery().eq(FreightTemplateDetail::getFreightTemplateId, freightTemplateId).list();
        bean.setFreightTemplateDetails(list);
        return bean;
    }

    /**
     * 删除运费模板
     */
    @Transactional
    public void delete(String freightTemplateId) {
        freightTemplateService.removeById(freightTemplateId);
        freightTemplateDetailService.lambdaUpdate().eq(FreightTemplateDetail::getFreightTemplateId, freightTemplateId).remove();
    }

    /**
     * 保存运费模板
     * 带freightTemplateId则为修改，否则新增
     */
    @Transactional
    public void save(FreightTemplateBean freightTemplateBean, HttpServletRequest request) {

        //设置企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        freightTemplateBean.setCreateUserName(adminUser.getNickName());
        freightTemplateBean.setCreateTime(new Date());
        freightTemplateService.saveOrUpdate(freightTemplateBean);

        if (freightTemplateBean.getFreightTemplateDetails() == null || freightTemplateBean.getFreightTemplateDetails().size() < 1) {
            return;
        }
        //删除运费明细
        if (StringUtils.isNotEmpty(freightTemplateBean.getFreightTemplateId())) {
            freightTemplateDetailService.lambdaUpdate()
                    .eq(FreightTemplateDetail::getFreightTemplateId, freightTemplateBean.getFreightTemplateId()).remove();
        }
        //新增运费明细
        List<FreightTemplateDetail> freightTemplateDetails = freightTemplateBean.getFreightTemplateDetails();
        for (FreightTemplateDetail freightTemplateDetail : freightTemplateDetails) {
            freightTemplateDetail.setFreightTemplateId(freightTemplateBean.getFreightTemplateId());
            freightTemplateDetail.setCompanyId(null);
            freightTemplateDetail.setCompanyName(null);
            freightTemplateDetail.setCreateTime(new Date());
        }
        freightTemplateDetailService.saveBatch(freightTemplateDetails);
    }

    /**
     * 启用/禁用
     */
    @Transactional
    public void updateStatus(String freightTemplateId, Boolean status) {

        freightTemplateService.lambdaUpdate().set(FreightTemplate::getStatus, status)
                .eq(FreightTemplate::getFreightTemplateId, freightTemplateId).update();

        freightTemplateDetailService.lambdaUpdate()
                .set(FreightTemplateDetail::getStatus, status)
                .eq(FreightTemplateDetail::getFreightTemplateId, freightTemplateId)
                .update();
    }


    /**
     * 根据件数以及地区计算运费
     */
    public BigDecimal getFreightAmount(HttpServletRequest request, String province, String city, String area, Integer num) throws RemoteServiceException {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyIds = adminUser.getAdminCompanyIds();

        FreightTemplateDetail one = freightTemplateDetailService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(companyIds), FreightTemplateDetail::getCompanyId, companyIds)
                .eq(FreightTemplateDetail::getProvince, province)
                .eq(FreightTemplateDetail::getCity, city)
//                .eq(FreightTemplateDetail::getArea, area)
                .eq(FreightTemplateDetail::getStatus, true).one();
        if (one == null) {
            throw new RemoteServiceException("暂不支持该地区的配送服务");
        }
        Integer firstLimit = one.getFirstLimit();
        Integer continuousLimit = one.getContinuousLimit();
        if (num <= firstLimit) {
            return one.getFirstAmount();
        }
        //续件费用
        int xj = (num - firstLimit) / continuousLimit + ((num - firstLimit) % continuousLimit == 0 ? 0 : 1);
        BigDecimal conAmount = one.getContinuousAmount().multiply(new BigDecimal(xj));

        return one.getFirstAmount().add(conAmount);
    }


    /**
     * 获取地区树
     *
     * @return
     */
    public List<RegionTreeBean> regionTree(Integer level) {
        if (level == null) {
            level = 3;
        }
        List<Region> regions = regionService.lambdaQuery()
                .le(Region::getLevel, level)
                .list();

        List<RegionTreeBean> list = new ArrayList<>();
        for (int i = 0; i < regions.size(); i++) {
            RegionTreeBean regionTree = new RegionTreeBean();
            BeanUtils.copyProperties(regions.get(i), regionTree);
            list.add(regionTree);
        }
        //省
        List<RegionTreeBean> province = list.stream().filter(v -> v.getLevel() == RegionLevelEnum.PROVINCE.getId()).collect(Collectors.toList());
        for (RegionTreeBean regionTree : province) {
            regionTree.setChild(this.regionTree(list, regionTree.getId(), regionTree.getName()));
        }
        return province;
    }

    private List<RegionTreeBean> regionTree(List<RegionTreeBean> list, Long parentId, String parentName) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<RegionTreeBean> childs = list.stream().filter(v -> v.getPid().equals(parentId)).collect(Collectors.toList());
        for (RegionTreeBean regionTree : childs) {
            regionTree.setParentName(parentName);
            regionTree.setChild(this.regionTree(list, regionTree.getId(), regionTree.getName()));
        }
        return childs;
    }


}
