package com.hzs.sale.postage.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.sale.postage.*;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
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.service.*;
import com.hzs.sale.postage.vo.PostageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 邮费相关controller
 * @Author: yuhui
 * @Time: 2022/8/29 10:59
 * @Classname: BdPostageController#
 * @PackageName: com.hzs.sale.postage.controller.manage
 */
@Slf4j
@RestController
@RequestMapping("/manage/postage")
public class BdPostageController extends BaseController {

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

    /**
     * 邮费模板列表
     *
     * @param bdPostage
     * @return
     */
    @AccessPermissions("PostageManage")
    @Log(module = EOperationModule.POSTAGE_CONFIG, business = EOperationBusiness.POSTAGE_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("list")
    public TableDataInfo list(BdPostage bdPostage) {
        startPage();
        bdPostage.setPkCountry(SecurityUtils.getPkCountry());
        List<PostageVo> list = postageService.selectByList(SecurityUtils.getPkCountry());

        List<PostageVo> resultList = new ArrayList<>();
        for (PostageVo postage : list) {
            if (postage.getSpecialPostageCount() > 0) {
                postage.setIsSpecialPostage(EYesNo.YES.getIntValue());
            } else {
                postage.setIsSpecialPostage(EYesNo.NO.getIntValue());
            }
            resultList.add(postage);
        }
        return getDataTable(resultList);
    }

    /**
     * 生成邮费模板
     *
     * @param postageParams
     * @return
     */
    @Log(module = EOperationModule.POSTAGE_SAVE, method = EOperationMethod.INSERT)
    @PostMapping("save")
    public AjaxResult save(@RequestBody PostageParams postageParams) {
        if (StringUtils.isBlank(postageParams.getTempName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.POSTAGE_TEMPLATE_IS_REQUIRED));
        }

        postageParams.setPkCreator(SecurityUtils.getUserId());
        postageParams.setPkCountry(SecurityUtils.getPkCountry());
        postageService.insertPostage(postageParams);
        return AjaxResult.success();
    }

    /**
     * 编辑邮费模板
     *
     * @param postageParams
     * @return
     */
    @Log(module = EOperationModule.POSTAGE_UPDATE, method = EOperationMethod.UPDATE)
    @PostMapping("update")
    public AjaxResult update(@RequestBody PostageParams postageParams) {
        if (StringUtils.isBlank(postageParams.getTempName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.POSTAGE_TEMPLATE_IS_REQUIRED));
        }
        Long userId = SecurityUtils.getUserId();
        postageParams.setPkCreator(userId);
        postageParams.setPkCountry(SecurityUtils.getPkCountry());
        postageParams.setPkModified(userId);
        postageService.updatePostage(postageParams);
        return AjaxResult.success();
    }

    /**
     * 删除邮费模板
     *
     * @param pkId
     * @return
     */
    @Log(module = EOperationModule.POSTAGE_DELETE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Integer pkId) {
        postageService.deletePostage(pkId);
        return AjaxResult.success();
    }

    /**
     * 查询详情
     *
     * @param postageId
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(Long postageId) {
        PostageParams postageParams = new PostageParams();
        // 邮费模板
        BdPostage postage = postageService.getById(postageId);

        // 查询配送区域
        LambdaQueryWrapper<BdPostageDetail> postageDetailWrapper = new LambdaQueryWrapper<>();
        postageDetailWrapper.eq(BdPostageDetail::getType, EPostageDetailType.DELIVERY_AREA.getValue());
        postageDetailWrapper.eq(BdPostageDetail::getPkPostage, postage.getPkId());
        List<BdPostageDetail> detailList = postageDetailService.list(postageDetailWrapper);
        Map<Integer, List<BdPostageDetail>> collect = detailList.stream().collect(Collectors.groupingBy(BdPostageDetail::getGroupValue));
        List<PostageDetailParams> postageDetailList = new ArrayList<>();
        for (Map.Entry<Integer, List<BdPostageDetail>> mp : collect.entrySet()) {
            if (mp.getValue().size() > 0) {
                BdPostageDetail bdPostageDetail = mp.getValue().get(0);
                PostageDetailParams postageDetailParams = BeanUtil.copyProperties(bdPostageDetail, PostageDetailParams.class);
                List<BdArea> areaList = new ArrayList<>();
                for (BdPostageDetail postageDetail : mp.getValue()) {
                    if (postageDetail.getCity() != null) {
                        areaList.add(new BdArea().setPkId(postageDetail.getCity()).setParent(postageDetail.getProvince()));
                    } else {
                        areaList.add(new BdArea().setPkId(postageDetail.getProvince()));
                    }
                }
                postageDetailParams.setAreaIds(areaList);
                // 续重运费数组
                LambdaQueryWrapper<BdPostageDetailInfo> postageDetailInfo = new LambdaQueryWrapper<>();
                postageDetailInfo.eq(BdPostageDetailInfo::getPkPostageDetail, bdPostageDetail.getPkId());
                postageDetailParams.setPostageDetailInfoList(postageDetailInfoService.list(postageDetailInfo));
                postageDetailList.add(postageDetailParams);
            }
        }
        postageParams.setPostageDetailList(postageDetailList);
        // 查询专区免邮
        List<BdPostageArea> postageAreas = postageAreaService.selectBySpecialAreaPostage(postageId);
        List<SpecialAreaParams> specialArea = new ArrayList<>();
        for (BdPostageArea postageArea : postageAreas) {
            SpecialAreaParams specialAreaParams = new SpecialAreaParams();
            specialAreaParams.setOrderType(postageArea.getSpecialArea());
            specialAreaParams.setPostage(postageArea.getFreeAmount());
            specialArea.add(specialAreaParams);
        }
        postageParams.setSpecialAreaList(specialArea);
        // 查询 特殊区域
        List<PostageDetailParams> peculiarPostageDetailList = new ArrayList<>();
        LambdaQueryWrapper<BdPostageDetail> peculiarDetailWrapper = new LambdaQueryWrapper<>();
        peculiarDetailWrapper.eq(BdPostageDetail::getType, EPostageDetailType.SPECIAL_AREA.getValue());
        peculiarDetailWrapper.eq(BdPostageDetail::getPkPostage, postage.getPkId());
        List<BdPostageDetail> peculiarDetailList = postageDetailService.list(peculiarDetailWrapper);
        Map<Integer, List<BdPostageDetail>> collectList = peculiarDetailList.stream().collect(Collectors.groupingBy(BdPostageDetail::getGroupValue));
        ;
        for (Map.Entry<Integer, List<BdPostageDetail>> mp : collectList.entrySet()) {
            if (mp.getValue().size() > 0) {
                BdPostageDetail bdPostageDetail = mp.getValue().get(0);
                PostageDetailParams postageDetailParams = BeanUtil.copyProperties(bdPostageDetail, PostageDetailParams.class);
                // 专区免邮配置
                List<SpecialAreaParams> specialAreaList = new ArrayList<>();
                LambdaQueryWrapper<BdPostageArea> areaWrapper = new LambdaQueryWrapper<>();
                if (bdPostageDetail.getProvince() != null) {
                    areaWrapper.eq(BdPostageArea::getProvince, bdPostageDetail.getProvince());
                }
                if (bdPostageDetail.getCity() != null) {
                    areaWrapper.eq(BdPostageArea::getCity, bdPostageDetail.getCity());
                }
                areaWrapper.eq(BdPostageArea::getPkPostage, postage.getPkId());
                List<BdPostageArea> list = postageAreaService.list(areaWrapper);
                //特殊区域 专区
                for (BdPostageArea postageArea : list) {
                    if (postageArea != null) {
                        SpecialAreaParams sp = new SpecialAreaParams();
                        sp.setPostage(postageArea.getFreeAmount());
                        sp.setOrderType(postageArea.getSpecialArea());
                        specialAreaList.add(sp);
                    }

                }
                List<BdArea> areaList = new ArrayList<>();
                for (BdPostageDetail postageDetail : mp.getValue()) {
                    if (postageDetail.getCity() != null) {
                        areaList.add(new BdArea().setPkId(postageDetail.getCity()).setParent(postageDetail.getProvince()));
                    } else {
                        areaList.add(new BdArea().setPkId(postageDetail.getProvince()));
                    }
                }
                postageDetailParams.setAreaIds(areaList);
                postageDetailParams.setSpecialAreaList(specialAreaList);
                // 续重运费数组
                LambdaQueryWrapper<BdPostageDetailInfo> postageDetailInfo = new LambdaQueryWrapper<>();
                postageDetailInfo.eq(BdPostageDetailInfo::getPkPostageDetail, bdPostageDetail.getPkId());
                postageDetailParams.setPostageDetailInfoList(postageDetailInfoService.list(postageDetailInfo));

                peculiarPostageDetailList.add(postageDetailParams);
            }
        }
        postageParams.setPeculiarPostageDetailList(peculiarPostageDetailList);


        // 配送不到达区域
        List<PostageFailAreaParams> postageFailAreaList = new ArrayList<>();
        LambdaQueryWrapper<BdPostageFailArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdPostageFailArea::getPkPostage, postageId);
        List<BdPostageFailArea> postageFailArea = postageFailAreaService.list(queryWrapper);
        Map<Integer, List<BdPostageFailArea>> collect1 = postageFailArea.stream().collect(Collectors.groupingBy(BdPostageFailArea::getGroupValue));
        for (Map.Entry<Integer, List<BdPostageFailArea>> mp : collect1.entrySet()) {
            BdPostageFailArea bdPostageFailArea1 = mp.getValue().get(0);
            PostageFailAreaParams postageFailAreaParams = BeanUtil.copyProperties(bdPostageFailArea1, PostageFailAreaParams.class);
            List<BdArea> areaList = new ArrayList<>();
            for (BdPostageFailArea bdPostageFailArea : mp.getValue()) {
                if (bdPostageFailArea.getCity() != null) {
                    // 添加市
                    BdArea bdArea = new BdArea();
                    bdArea.setPkId(bdPostageFailArea.getCity());
                    bdArea.setParent(bdPostageFailArea.getProvince());
                    areaList.add(bdArea);
                } else {
                    // 添加省
                    BdArea bdArea = new BdArea();
                    bdArea.setPkId(bdPostageFailArea.getProvince());
                    areaList.add(bdArea);
                }
            }
            postageFailAreaParams.setAreaIds(areaList);
            postageFailAreaList.add(postageFailAreaParams);
        }
        postageParams.setPostageFailAreaList(postageFailAreaList);
        // 返回模板基本信息
        postageParams.setTempName(postage.getTempName());
        postageParams.setTranType(postage.getTranType());
        postageParams.setChargeType(postage.getChargeType());
        postageParams.setQuantityMode(postage.getQuantityMode());
        return AjaxResult.success(postageParams);
    }

    /**
     * 查询邮费
     *
     * @return
     */
    @GetMapping("find-all")
    public AjaxResult findAll(BdPostage bdPostage) {
        LambdaQueryWrapper<BdPostage> queryWrapper = new LambdaQueryWrapper<>();
        if (bdPostage.getTranType() != null) {
            queryWrapper.eq(BdPostage::getTranType, bdPostage.getTranType());
        }
        queryWrapper.eq(BdPostage::getPkCountry, SecurityUtils.getPkCountry());
        List<BdPostage> list = postageService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    /**
     * 特殊邮费配置
     */
    @GetMapping("special-postage")
    public AjaxResult specialPostage(Integer pkPostage, Integer isSpecialPostage) {
        postageService.createWaresSpecialPostage(pkPostage, isSpecialPostage);
        return AjaxResult.success();
    }
}
