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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.enums.EPostageDetailType;
import com.hzs.common.core.service.RedisService;
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.core.utils.TransactionUtils;
import com.hzs.sale.postage.controller.manage.params.PostageDetailParams;
import com.hzs.sale.postage.controller.manage.params.PostageFailAreaParams;
import com.hzs.sale.postage.controller.manage.params.PostageParams;
import com.hzs.sale.postage.controller.manage.params.SpecialAreaParams;
import com.hzs.sale.postage.service.*;
import com.hzs.sale.postage.vo.PostageVo;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.base.dto.CountryDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
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;
    @DubboReference
    private ICountryServiceApi countryServiceApi;
    @Autowired
    private IBdPostageDetailService postageDetailService;
    @DubboReference
    private ITransactionServiceApi transactionServiceApi;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IBdPostageAreaService postageAreaService;
    @Autowired
    private IBdPostageFailAreaService postageFailAreaService;
    /**
     * 邮费模板列表
     * @param bdPostage
     * @return
     */
    @Log(module = EOperationModule.POSTAGE_LIST, method = EOperationMethod.SELECT)
    @GetMapping("list")
    public TableDataInfo list(BdPostage bdPostage){
        startPage();
        QueryWrapper<BdPostage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY",SecurityUtils.getPkCountry());
        List<BdPostage> list = postageService.list(queryWrapper);
        List<PostageVo> resultList = new ArrayList<>();
        for (BdPostage postage : list) {
            PostageVo postageVo = BeanUtil.copyProperties(postage, PostageVo.class);
            R<CountryDTO> country = countryServiceApi.getCountry(postage.getPkCountry());
            if (country.getData() != null){
                postageVo.setNationalFlag2(country.getData().getNationalFlag2());
                postageVo.setShortName(country.getData().getShortName());
                resultList.add(postageVo);
            }
        }
        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);

        // 查询配送区域
        QueryWrapper<BdPostageDetail> postageDetailWrapper = new QueryWrapper();
        postageDetailWrapper.eq("TYPE",EPostageDetailType.DELIVERY_AREA.getValue());
        postageDetailWrapper.eq("PK_POSTAGE",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);
                // 续重运费数组
                QueryWrapper<BdPostageDetailInfo> postageDetailInfo = new QueryWrapper();
                postageDetailInfo.eq("PK_POSTAGE_DETAIL",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<>();
        QueryWrapper<BdPostageDetail> peculiarDetailWrapper = new QueryWrapper();
        peculiarDetailWrapper.eq("TYPE", EPostageDetailType.SPECIAL_AREA.getValue());
        peculiarDetailWrapper.eq("PK_POSTAGE",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<>();
                QueryWrapper<BdPostageArea> areaWrapper = new QueryWrapper();
                if (bdPostageDetail.getProvince()!= null){
                    areaWrapper.eq("PROVINCE",bdPostageDetail.getProvince());
                }
                if (bdPostageDetail.getCity()!= null){
                    areaWrapper.eq("CITY",bdPostageDetail.getCity());
                }
                areaWrapper.eq("PK_POSTAGE",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);
                // 续重运费数组
                QueryWrapper<BdPostageDetailInfo> postageDetailInfo = new QueryWrapper();
                postageDetailInfo.eq("PK_POSTAGE_DETAIL",bdPostageDetail.getPkId());
                postageDetailParams.setPostageDetailInfoList(postageDetailInfoService.list(postageDetailInfo));

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


        // 配送不到达区域
        List<PostageFailAreaParams> postageFailAreaList = new ArrayList<>();
        QueryWrapper<BdPostageFailArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_POSTAGE",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());
        return AjaxResult.success(postageParams);
    }

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

}
