package com.hzs.sale.postage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.enums.ETransactionKey;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.sale.postage.*;
import com.hzs.common.domain.sale.wares.BdWaresSpecialPostage;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.postage.params.PostageDetailParams;
import com.hzs.sale.postage.params.PostageFailAreaParams;
import com.hzs.sale.postage.params.PostageParams;
import com.hzs.sale.postage.params.SpecialAreaParams;
import com.hzs.sale.postage.mapper.BdPostageMapper;
import com.hzs.sale.postage.service.*;
import com.hzs.sale.postage.vo.PostageVo;
import com.hzs.sale.wares.service.IBdWaresSpecialPostageService;
import com.hzs.system.base.ITransactionServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 邮费设置 服务实现类
 *
 * @author hzs
 * @since 2022-08-27
 */
@Service
public class BdPostageServiceImpl extends ServiceImpl<BdPostageMapper, BdPostage> implements IBdPostageService {

    @Autowired
    private IBdWaresSpecialPostageService waresSpecialPostageService;
    @Autowired
    private IBdPostageDetailService postageDetailService;
    @Autowired
    private IBdPostageService postageService;
    @Autowired
    private IBdPostageFailAreaService postageFailAreaService;
    @Autowired
    private IBdPostageAreaService postageAreaService;
    @Autowired
    private IBdPostageDetailInfoService postageDetailInfoService;

    @DubboReference
    ITransactionServiceApi transactionServiceApi;

    @Autowired
    private RedisService redisService;

    /**
     * 生成邮费模板
     *
     * @param postageParams
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertPostage(PostageParams postageParams) {
        BdPostage postage = new BdPostage();
        postage.setTempName(postageParams.getTempName());
        postage.setRemark(postageParams.getRemark());
        postage.setPkCreator(postageParams.getPkCreator());
        postage.setCreationTime(new Date());
        postage.setTranType(postageParams.getTranType());
        postage.setPkCountry(postageParams.getPkCountry());
        postage.setChargeType(postageParams.getChargeType());
        R<Integer> transaction = transactionServiceApi.createTransaction(postageParams.getPkCountry(), ETransactionKey.WARES, postage.getTempName(), EYesNo.NO, EYesNo.NO);
        postage.setPkTransactionKey(transaction.getData());
        postage.setQuantityMode(postageParams.getQuantityMode());
        postageService.save(postage);
        savePostageInfo(postage, postageParams);
    }


    /**
     * 生成特殊邮费配置
     *
     * @return
     */
    @Override
    public Integer createWaresSpecialPostage(Integer pkPostage, Integer isSpecialPostage) {
        BdPostage postage = postageService.getPostage(pkPostage);

        QueryWrapper<BdWaresSpecialPostage> qw = new QueryWrapper<>();
        qw.eq("PK_POSTAGE", postage.getPkId());
        int count = waresSpecialPostageService.count(qw);
        if (isSpecialPostage.equals(EYesNo.YES.getIntValue())) {
            if (count == 0) {
                // 表示 记录不存在
                BdWaresSpecialPostage waresSpecialPostage = new BdWaresSpecialPostage();
                waresSpecialPostage.setPkPostage(pkPostage);
                waresSpecialPostage.setPkCountry(SecurityUtils.getPkCountry());
                waresSpecialPostage.setPkCreator(SecurityUtils.getUserId());
                waresSpecialPostage.setCreationTime(DateUtils.currentDateTime());
                waresSpecialPostageService.save(waresSpecialPostage);
            }
        } else if (isSpecialPostage.equals(EYesNo.NO.getIntValue())) {
            waresSpecialPostageService.deleteByPkPostage(pkPostage);
        }
        return null;
    }


    /**
     * 查询邮费列表
     *
     * @return
     */
    @Override
    public List<PostageVo> selectByList(Integer pkCountry) {
        return baseMapper.selectByList(pkCountry);
    }

    /**
     * 新增邮费详情表
     *
     * @param postage
     */
    private void savePostageInfo(BdPostage postage, PostageParams postageParams) {
        // 配送区域
        int groupValue = 0;
        for (PostageDetailParams pd : postageParams.getPostageDetailList()) {
            for (BdArea province : pd.getAreaIds()) {
                BdPostageDetail postageDetail = new BdPostageDetail();
                postageDetail.setFirstWeight(pd.getFirstWeight());
                postageDetail.setFirstPostage(pd.getFirstPostage());
                if (pd.getPostageDetailInfoList().size() > 0) {
                    postageDetail.setContinuedWeight(pd.getPostageDetailInfoList().get(0).getContinuedWeight());
                    postageDetail.setContinuedPostage(pd.getPostageDetailInfoList().get(0).getContinuedPostage());
                }
                postageDetail.setVolumeRatio(pd.getVolumeRatio());
                postageDetail.setCreationTime(new Date());
                postageDetail.setPkCountry(postageParams.getPkCountry());
                postageDetail.setPkCreator(postageParams.getPkCreator());
                postageDetail.setProvince(province.getPkId());
                postageDetail.setPkPostage(postage.getPkId());
                postageDetail.setType(1);
                postageDetail.setGroupValue(groupValue);
                postageDetailService.save(postageDetail);
                if (pd.getPostageDetailInfoList().size() > 0) {
                    for (BdPostageDetailInfo postageDetailInfo : pd.getPostageDetailInfoList()) {
                        postageDetailInfo.setCreationTime(new Date());
                        postageDetailInfo.setPkPostageDetail(postageDetail.getPkId());
                        postageDetailInfo.setPkCountry(postageParams.getPkCountry());
                        postageDetailInfo.setPkCreator(postageParams.getPkCreator());
                        postageDetailInfo.setPkPostage(postage.getPkId());
                        postageDetailInfoService.save(postageDetailInfo);
                    }
                }
            }
            groupValue += 1;
        }
        // 专区免邮配置
        List<BdPostageArea> postageAreaList = new ArrayList<>();
        for (SpecialAreaParams specialAreaParams : postageParams.getSpecialAreaList()) {
            BdPostageArea postageArea = new BdPostageArea();
            postageArea.setSpecialArea(specialAreaParams.getOrderType());
            postageArea.setFreeAmount(specialAreaParams.getPostage());
            postageArea.setPkPostage(postage.getPkId());
            postageArea.setCreationTime(new Date());
            postageArea.setPkCountry(postageParams.getPkCountry());
            postageArea.setPkCreator(postageParams.getPkCreator());
            postageAreaList.add(postageArea);
        }
        postageAreaService.saveBatch(postageAreaList);
        // 特殊区域配置
        int peculiarGroupValue = 0;
        for (PostageDetailParams pd : postageParams.getPeculiarPostageDetailList()) {
            for (BdArea area : pd.getAreaIds()) {
                BdPostageDetail postageDetail = new BdPostageDetail();
                postageDetail.setFirstWeight(pd.getFirstWeight());
                postageDetail.setFirstPostage(pd.getFirstPostage());
                if (pd.getPostageDetailInfoList().size() > 0) {
                    postageDetail.setContinuedWeight(pd.getPostageDetailInfoList().get(0).getContinuedWeight());
                    postageDetail.setContinuedPostage(pd.getPostageDetailInfoList().get(0).getContinuedPostage());
                } else {
                    postageDetail.setContinuedWeight(pd.getContinuedWeight());
                    postageDetail.setContinuedPostage(pd.getContinuedPostage());
                }

                postageDetail.setVolumeRatio(pd.getVolumeRatio());
                postageDetail.setCreationTime(new Date());
                postageDetail.setPkCountry(postageParams.getPkCountry());
                postageDetail.setPkCreator(postageParams.getPkCreator());
                if (area.getParent() == 0) {
                    postageDetail.setProvince(area.getPkId());
                } else {
                    postageDetail.setProvince(area.getParent());
                    postageDetail.setCity(area.getPkId());
                }
                postageDetail.setPkPostage(postage.getPkId());
                postageDetail.setType(2);
                postageDetail.setGroupValue(peculiarGroupValue);
                postageDetailService.save(postageDetail);
                if (pd.getPostageDetailInfoList().size() > 0) {
                    for (BdPostageDetailInfo postageDetailInfo : pd.getPostageDetailInfoList()) {
                        postageDetailInfo.setCreationTime(new Date());
                        postageDetailInfo.setPkPostageDetail(postageDetail.getPkId());
                        postageDetailInfo.setPkCountry(postageParams.getPkCountry());
                        postageDetailInfo.setPkCreator(postageParams.getPkCreator());
                        postageDetailInfo.setPkPostage(postage.getPkId());
                        postageDetailInfoService.save(postageDetailInfo);
                    }
                }
                for (SpecialAreaParams specialAreaParams : pd.getSpecialAreaList()) {
                    BdPostageArea postageArea = new BdPostageArea();
                    postageArea.setSpecialArea(specialAreaParams.getOrderType());
                    postageArea.setFreeAmount(specialAreaParams.getPostage());
                    postageArea.setPkPostage(postage.getPkId());
                    postageArea.setCreationTime(new Date());
                    postageArea.setPkCountry(postageParams.getPkCountry());
                    postageArea.setPkCreator(postageParams.getPkCreator());
                    if (area.getParent() == 0) {
                        postageArea.setProvince(area.getPkId());
                    } else {
                        postageArea.setProvince(area.getParent());
                        postageArea.setCity(area.getPkId());
                    }
                    postageAreaService.save(postageArea);
                }
            }
            peculiarGroupValue += 1;
        }

        // 无法送达区域
        int failAreaGroupValue = 0;
        for (PostageFailAreaParams postageFailArea : postageParams.getPostageFailAreaList()) {
            for (BdArea area : postageFailArea.getAreaIds()) {
                if (area.getParent() != null) {
                    if (area.getParent() == 0) {
                        postageFailArea.setProvince(area.getPkId());
                    } else {
                        postageFailArea.setProvince(area.getParent());
                        postageFailArea.setCity(area.getPkId());
                    }
                }
                postageFailArea.setPkPostage(postage.getPkId());
                postageFailArea.setCreationTime(new Date());
                postageFailArea.setPkCountry(postageParams.getPkCountry());
                postageFailArea.setPkCreator(SecurityUtils.getUserId());
                postageFailArea.setGroupValue(failAreaGroupValue);
                postageFailAreaService.save(postageFailArea);
            }
            failAreaGroupValue += 1;
        }
    }


    /**
     * 修改邮费模板
     *
     * @param postageParams
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePostage(PostageParams postageParams) {
        BdPostage pt = postageService.getPostage(postageParams.getPkId());
        BdPostage postage = new BdPostage();
        postage.setPkId(postageParams.getPkId());
        postage.setTempName(postageParams.getTempName());
        postage.setRemark(postageParams.getRemark());
        postage.setTranType(postageParams.getTranType());
        postage.setPkModified(postageParams.getPkCreator());
        postage.setModifiedTime(new Date());
        postage.setChargeType(postageParams.getChargeType());
        postage.setQuantityMode(postageParams.getQuantityMode());
        postageService.updateById(postage);
        String redisKey = CacheConstants.BD_POSTAGE + postageParams.getPkId();
        redisService.deleteObject(redisKey);
        // 删除相关邮费详情
        deletePostageInfo(postageParams);
        // 新增相关邮费详情
        savePostageInfo(postage, postageParams);
    }

    /**
     * 删除详情
     */
    private void deletePostageInfo(PostageParams postageParams) {
        // 删除邮费关联省市
        UpdateWrapper<BdPostageArea> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_POSTAGE", postageParams.getPkId());
        updateWrapper.set("PK_MODIFIED", postageParams.getPkModified());
        updateWrapper.set("MODIFIED_TIME", new Date());
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        postageAreaService.update(updateWrapper);
        // 删除邮费详情
        UpdateWrapper<BdPostageDetail> postageDetailWrapper = new UpdateWrapper<>();
        postageDetailWrapper.eq("PK_POSTAGE", postageParams.getPkId());
        postageDetailWrapper.set("PK_MODIFIED", postageParams.getPkModified());
        postageDetailWrapper.set("MODIFIED_TIME", new Date());
        postageDetailWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        postageDetailService.update(postageDetailWrapper);
        // 删除邮费详情续重
        UpdateWrapper<BdPostageDetailInfo> postageDetailInfoWrapper = new UpdateWrapper<BdPostageDetailInfo>();
        postageDetailInfoWrapper.eq("PK_POSTAGE", postageParams.getPkId());
        postageDetailInfoWrapper.set("PK_MODIFIED", postageParams.getPkModified());
        postageDetailInfoWrapper.set("MODIFIED_TIME", new Date());
        postageDetailInfoWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        postageDetailInfoService.update(postageDetailInfoWrapper);
        // 删除不配送区域表
        UpdateWrapper<BdPostageFailArea> postageFailAreaWrapper = new UpdateWrapper<BdPostageFailArea>();
        postageFailAreaWrapper.eq("PK_POSTAGE", postageParams.getPkId());
        postageFailAreaWrapper.set("PK_MODIFIED", postageParams.getPkModified());
        postageFailAreaWrapper.set("MODIFIED_TIME", new Date());
        postageFailAreaWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        postageFailAreaService.update(postageFailAreaWrapper);

    }


    /**
     * 根据id 查询相关邮费模板信息
     *
     * @param postageId
     * @return
     */
    @Override
    public BdPostage getPostage(Integer postageId) {
        // TODO 考虑是否使用注解方式处理
        String redisKey = CacheConstants.BD_POSTAGE + postageId;
        BdPostage postage = redisService.getCacheObject(redisKey);
        if (null == postage) {
            postage = baseMapper.selectById(postageId);
            if (null != postage) {
                redisService.setCacheObject(redisKey, postage);
            }
        }
        return postage;
    }

    /**
     * 删除
     *
     * @param pkId
     */
    @Override
    public void deletePostage(Integer pkId) {
        PostageParams postageParams = new PostageParams();
        postageParams.setPkModified(SecurityUtils.getUserId());
        postageParams.setPkId(pkId);

        UpdateWrapper<BdPostage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ID", pkId);
        updateWrapper.set("PK_MODIFIED", postageParams.getPkModified());
        updateWrapper.set("MODIFIED_TIME", new Date());
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        postageService.update(updateWrapper);

        deletePostageInfo(postageParams);
    }
}
