package com.hzs.retail.member.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.retail.member.CuMemberRetailRegion;
import com.hzs.common.domain.retail.member.ext.CuMemberRetailRegionExt;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.common.domain.system.base.ext.AreaCache;
import com.hzs.retail.member.mapper.CuMemberRetailRegionMapper;
import com.hzs.retail.member.param.RetailMemberRegionParam;
import com.hzs.retail.member.service.ICuMemberRetailRegionService;
import com.hzs.retail.member.vo.UnboundAreaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 新零售会员区域配置 服务实现类
 */
@Slf4j
@Service
public class CuMemberRetailRegionServiceImpl extends ServiceImpl<CuMemberRetailRegionMapper, CuMemberRetailRegion> implements ICuMemberRetailRegionService {

    @Autowired
    private RedisService redisService;

    @Override
    public CuMemberRetailRegionExt getRegionByMember(Long pkMember, Integer gradeValue, Integer systemType) {
        return baseMapper.getRegionByMember(pkMember, gradeValue, systemType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String setRegion(RetailMemberRegionParam param) {
        String redisKey = String.format(CacheConstants.RETAIL_REGION, param.getProvince(), param.getCity(), param.getCounty());
        try {
            // 按省、市、区上锁
            if (!redisService.lockKeyMany(redisKey)) {
                return "收益区域绑定失败，请重试";
            }

            if (null != param.getPkId()) {
                // 之前存在数据，将旧数据取消
                this.update(Wrappers.<CuMemberRetailRegion>lambdaUpdate()
                        .eq(CuMemberRetailRegion::getPkMember, param.getPkMember())
                        .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
                        .eq(CuMemberRetailRegion::getSystemType, param.getSystemType())
                        .set(CuMemberRetailRegion::getEffective, EYesNo.NO.getIntValue())
                        .set(CuMemberRetailRegion::getPkModified, param.getPkMember())
                        .set(CuMemberRetailRegion::getModifiedTime, new Date())
                );
            }
            // 新増数据
            CuMemberRetailRegion retailRegion = CuMemberRetailRegion.builder()
                    .pkMember(param.getPkMember())
                    .province(param.getProvince())
                    .city(param.getCity())
                    .county(param.getCounty())
                    // 数据来源会员端
                    .source(param.getSource())
                    .systemType(param.getSystemType())
                    .build();
            retailRegion.setPkCreator(param.getPkMember());
            if (baseMapper.insertData(retailRegion) == 0) {
                throw new ServiceException("选择区域失败，请刷新后重试");
            }
        } finally {
            redisService.unlock(redisKey);
        }
        return null;
    }

    @Override
    public List<UnboundAreaVO> unboundAreaList(Integer pkCountry, Integer systemType) {
        return baseMapper.unboundAreaList(pkCountry, systemType);
    }

    @Override
    public List<CuMemberRetailRegionExt> memberretailRegList(CuMemberRetailRegionExt mrrExt) {
        return baseMapper.memberretailRegList(mrrExt);
    }

    @Override
    public int getOrderCount(Long pkMember, Integer systemType, List<String> waresCodeList) {
        return baseMapper.getOrderCount(pkMember, systemType, waresCodeList);
    }

    @Override
    public List<Tree<String>> getRegionTreeList(String queryType, Long pkMember) {
        List<BdArea> areaList = baseMapper.getRegionTreeList(queryType, pkMember);
        if (CollectionUtil.isEmpty(areaList)) {
            return null;
        }
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(3);
        if (RetailRegionTreeQueryConstants.CITY.equals(queryType)) {
            treeNodeConfig.setDeep(2);
        }
        return TreeUtil.build(areaList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getPkId().toString());
                    tree.setParentId(treeNode.getParent().toString());
                    tree.setName(treeNode.getName());
                });
    }

    @Override
    public List<BdArea> getRegionList(String queryType, Long pkMember) {
        List<BdArea> allList = baseMapper.getRegionTreeList(queryType, pkMember);
        /*
        List<BdArea> provinceList = new ArrayList<>();
        List<BdArea> cityList = new ArrayList<>();
        List<BdArea> countyList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(allList)) {
            //省
            for (BdArea ac : allList) {
                // 上级为0，则为省一级
                if (ac.getParent().equals(0)) {
                    provinceList.add(ac);
                }
            }
        }
        //市
        for (BdArea ac : provinceList) {
            for (BdArea ct : allList) {
                if (ct.getParent().intValue() == ac.getPkId()) {
                    cityList.add(ct);
                }
            }
        }
        Set<Integer> idSet = new HashSet<>();
        for (BdArea cache : cityList) {
            for (BdArea ac : allList) {
                if (ac.getParent().intValue() == cache.getPkId().intValue()) {
                    idSet.add(ac.getPkId());
                }
            }
        }
        for (BdArea cache : allList) {
            for (Integer integer : idSet) {
                if (cache.getPkId().equals(integer)) {
                    countyList.add(cache);
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("provinceList", provinceList);
        result.put("cityList", cityList);
        result.put("countyList", countyList);
         */
        return allList;
    }

    @Override
    public int mergeMemberRetailRegion(CuMemberRetailRegion retailRegion) {
        return baseMapper.mergeMemberRetailRegion(retailRegion);
    }

}
