package com.cool.store.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.entity.*;
import com.cool.store.enums.*;
import com.cool.store.enums.point.ShopSubStageEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.WarehouseInfoMapper;
import com.cool.store.request.BuildInformationRequest;
import com.cool.store.request.BuildSettlerRequest;
import com.cool.store.response.BuildInformationResponse;
import com.cool.store.service.BuildInformationService;
import com.cool.store.mapper.BuildInformationMapper;
import com.cool.store.service.EnumInfoService;
import com.cool.store.service.PreparationService;
import com.cool.store.service.UserAuthMappingService;
import com.cool.store.utils.RedisConstantUtil;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author EDY
 * @description 针对表【xfsg_build_information(建店资料表)】的数据库操作Service实现
 * @createDate 2024-10-09 14:05:52
 */
@Service
@Slf4j
public class BuildInformationServiceImpl implements BuildInformationService {
    @Resource
    private  PlatformBuildDAO platformBuildDAO;
    @Resource
    private EnumInfoService enumInfoService;
    @Resource
    private RedisConstantUtil redisConstantUtil;
    @Resource
    private RedisUtilPool redisUtilPool;
    @Resource
    private WarehouseInfoMapper warehouseInfoMapper;
    @Resource
    private UserAuthMappingService userAuthMappingService;
    @Resource
    private BuildInformationDAO buildInformationDAO;
    @Autowired
    private ShopStageInfoDAO shopStageInfoDAO;
    @Autowired
    private PointInfoDAO pointInfoDAO;
    @Autowired
    private ShopInfoDAO shopInfoDAO;
    @Resource
    PreparationService preparationService;
    @Autowired
    private QualificationsInfoDAO qualificationsInfoDAO;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Resource
    private CommonService commonService;
    @Autowired
    private OrderSysInfoDAO orderSysInfoDAO;
    @Autowired
    private BigRegionDAO bigRegionDAO;
    @Resource
    private AcceptanceInfoDAO acceptanceInfoDAO;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer submitOrUpdate(BuildInformationRequest request) {
        log.info("提交/修改建店资料开始,shopId:{}", JSONObject.toJSONString(request));
        String lockKey = redisConstantUtil.submitBuildKey(request.getShopId());
        String lockValue = UUID.randomUUID().toString();
        boolean acquired = false;
        try {
            acquired = redisUtilPool.setNxExpire(lockKey, lockValue, CommonConstants.TEN_SECONDS);
            if (Boolean.TRUE.equals(acquired)) {
                ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(request.getShopId());
//                if (JoinModeEnum.FLAGSHIP_STORE.getCode()!=shopInfoDO.getJoinMode()){
//                    log.info("FLAGSHIP_STORE：{}，{}，{}，{}，{}，{}，{}",request.getSettlerName(),request.getSettlerIdCardFront(),
//                            request.getSettlerInHandFrontPicture(),request.getSettlerBankBackPhotoUrl(),
//                            request.getSettlerBankNumber(),request.getSettlerBankMobile(),request.getSettlerBankName());
//                    //校验结算人非空
//                    if (StringUtils.isAnyBlank(request.getSettlerName(),request.getSettlerIdCardFront(),
//                            request.getSettlerInHandFrontPicture(),request.getSettlerBankBackPhotoUrl(),
//                            request.getSettlerBankNumber(),request.getSettlerBankMobile(),request.getSettlerBankName())) {
//                        throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
//                    }
//                }

                BuildInformationDO informationDO = buildInformationDAO.selectOneByShopId(request.getShopId());
                BuildInformationDO buildInformationDO = request.toDO();
                OrderSysInfoDO orderSysInfoDO = getOrderSysInfoDO(request);
                OrderSysInfoDO orderSysInfoDO1 = orderSysInfoDAO.selectByShopId(request.getShopId());
                if (Objects.nonNull(orderSysInfoDO1)) {
                    orderSysInfoDAO.updateByShopId(orderSysInfoDO);
                } else {
                    orderSysInfoDAO.insertSelective(orderSysInfoDO);
                }
                LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfoDO.getLineId());
                QualificationsInfoDO qualificationsInfoDO = qualificationsInfoDAO.getByLineId(lineInfoDO.getId());
                if (request.getJuridicalIsSamePartner()) {
                    buildInformationDO.setJuridicalName(lineInfoDO.getUsername());
                    buildInformationDO.setJuridicalIdCardNo(qualificationsInfoDO.getIdCardNo());
                    buildInformationDO.setJuridicalIdCardFront(qualificationsInfoDO.getFrontOfIdCard());
                    buildInformationDO.setJuridicalIdCardReverse(qualificationsInfoDO.getBackOfIdCard());
                }
                if (request.getSettlerIsSamePartner()!=null&&request.getSettlerIsSamePartner()) {
                    buildInformationDO.setSettlerIdCardNo(qualificationsInfoDO.getIdCardNo());
                    buildInformationDO.setSettlerName(lineInfoDO.getUsername());
                    buildInformationDO.setSettlerIdCardFront(qualificationsInfoDO.getFrontOfIdCard());
                    buildInformationDO.setSettlerIdCardReverse(qualificationsInfoDO.getBackOfIdCard());
                }
                if (Objects.isNull(informationDO)) {
                    buildInformationDO.setCreateTime(new Date());
                    buildInformationDO.setUpdateTime(new Date());
                    shopStageInfoDAO.updateShopStageInfo(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("partnerUsername", lineInfoDO.getUsername());
                    map.put("partnerMobile", lineInfoDO.getMobile());
                    map.put("storeName", shopInfoDO.getShopName());
                    List<EnterpriseUserDO> logisticsList = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.LOGISTICS, shopInfoDO.getRegionId());
                    List<String> logistics = new ArrayList<>();
                    if (Objects.nonNull(logisticsList)) {
                        logistics.addAll(logisticsList.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList()));
                    }
                    commonService.sendQWMessage(logistics,
                            MessageEnum.MESSAGE_52,
                            map);
                    return buildInformationDAO.insertSelective(buildInformationDO);
                } else {
                    buildInformationDO.setUpdateTime(new Date());
                    List<PlatformBuildDO> platformBuildDOS = platformBuildDAO.selectByShopId(request.getShopId());
                    if (CollectionUtils.isNotEmpty(platformBuildDOS)){
                        for (PlatformBuildDO platformBuildDO : platformBuildDOS){
                            platformBuildDO.setSettlerName(buildInformationDO.getSettlerName());
                            platformBuildDO.setSettlerIdCardFront(buildInformationDO.getSettlerIdCardFront());
                            platformBuildDO.setSettlerIdCardReverse(buildInformationDO.getSettlerIdCardReverse());
                            platformBuildDO.setSettlerInHandBackPicture(buildInformationDO.getSettlerInHandBackPicture());
                            platformBuildDO.setSettlerInHandFrontPicture(buildInformationDO.getSettlerInHandFrontPicture());
                            platformBuildDO.setSettlerIdCardNo(buildInformationDO.getSettlerIdCardNo());
                            platformBuildDO.setSettlerBankPhotoUrl(buildInformationDO.getSettlerBankPhotoUrl());
                            platformBuildDO.setSettlerBankNumber(buildInformationDO.getSettlerBankNumber());
                            platformBuildDO.setSettlerBankMobile(buildInformationDO.getSettlerBankMobile());
                            platformBuildDO.setSettlerBankName(buildInformationDO.getSettlerBankName());
                        }
                    }
                    platformBuildDAO.batchUpdate(platformBuildDOS);
                    return buildInformationDAO.updateByShopIdSelective(buildInformationDO);
                }
            }else{
                throw  new ServiceException(ErrorCodeEnum.DUPLICATE_SUBMISSION);
            }
        } finally {
            if (Boolean.TRUE.equals(acquired)) {
                String currentValue = redisUtilPool.getString(lockKey);
                if (lockValue.equals(currentValue)) {
                    redisUtilPool.delKey(lockKey);
                }
            }
        }
    }

    @Override
    public BuildInformationResponse getBuildInformation(Long shopId) {
        BuildInformationResponse response = new BuildInformationResponse();
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(shopId);
        if (Objects.isNull(shopInfo)) {
            throw new ServiceException(ErrorCodeEnum.SHOP_NOT_EXIST);
        }
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(shopId, ShopSubStageEnum.SHOP_STAGE_15);
        response.setShopSubStageStatus(shopSubStageInfo.getShopSubStageStatus());
        response.setUsername(lineInfoDO.getUsername());
        response.setShopId(shopId);
        response.setShopName(shopInfo.getShopName());
        response.setShopCode(shopInfo.getShopCode());
        response.setProvince(shopInfo.getProvince());
        response.setDistrict(shopInfo.getDistrict());
        response.setCity(shopInfo.getCity());
        response.setTownship(shopInfo.getDetailAddress());
        BuildInformationDO informationDO = buildInformationDAO.selectOneByShopId(shopId);
        if (Objects.nonNull(informationDO)) {
            extracted(response, informationDO);
        }
        OrderSysInfoDO orderSysInfoDO = orderSysInfoDAO.selectByShopId(shopId);
        if (Objects.nonNull(orderSysInfoDO)) {
            response.setAddresseeName(orderSysInfoDO.getAddresseeName());
            response.setAddresseeMobile(orderSysInfoDO.getAddresseeMobile());
            response.setXgjVicePresident(orderSysInfoDO.getXgjVicePresident());
            response.setXgjRegionId(orderSysInfoDO.getXgjRegionId());
            response.setXgjRegionName(orderSysInfoDO.getXgjRegionName());
            response.setAddresseeProvince(orderSysInfoDO.getAddresseeProvince());
            response.setAddresseeCity(orderSysInfoDO.getAddresseeCity());
            response.setAddresseeDistrict(orderSysInfoDO.getAddresseeDistrict());
            response.setAddresseeAddress(orderSysInfoDO.getAddresseeAddress());
            response.setDeclareGoodsLogisticsWarehouse(orderSysInfoDO.getDeclareGoodsLogisticsWarehouse());
            response.setDeclareGoodsDate(orderSysInfoDO.getDeclareGoodsDate());
            response.setWarehouseDeliveryDate(orderSysInfoDO.getWarehouseDeliveryDate());
            response.setReceivingFirmName(orderSysInfoDO.getReceivingFirmName());
            response.setReceivingMsBankAccount(orderSysInfoDO.getReceivingMsBankAccount());
            response.setReceivingMsBankBranch(orderSysInfoDO.getReceivingMsBankBranch());
            response.setBankUnionPayAccount(orderSysInfoDO.getBankUnionPayAccount());
            response.setOrderType(orderSysInfoDO.getOrderType());
            WarehouseInfoDO warehouseInfoDO = warehouseInfoMapper.getByCode(orderSysInfoDO.getDeclareGoodsLogisticsWarehouse());
            if (Objects.nonNull(warehouseInfoDO)) {
                response.setDeclareGoodsLogisticsWarehouseName(warehouseInfoDO.getWarehouseName());
            }
            response.setDeclareGoodsType(orderSysInfoDO.getDeclareGoodsType());
        }
        if (StringUtils.isBlank(response.getXgjVicePresident())) {
            List<EnterpriseUserDO> userList = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.VICE_PRESIDENT_IN_CHARGE, shopInfo.getRegionId());
            if (CollectionUtils.isNotEmpty(userList)) {
                List<EnumInfoDO> xgjVicePresidentList = enumInfoService.getByTypeCode(ZxjpEnum.XGJ_VICE_PRESIDENT.getCode());
                List<String> userNameSet = userList.stream().map(EnterpriseUserDO::getName).collect(Collectors.toList());
                List<String> xgjVicePresidentNameList = xgjVicePresidentList.stream().map(EnumInfoDO::getSysValue).collect(Collectors.toList());
                List<String> resultUserNameList = userNameSet.stream()
                        .filter(xgjVicePresidentNameList::contains)
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(resultUserNameList)){
                    response.setXgjVicePresident(resultUserNameList.get(0));
                }
            }
        }
        //根据映射关系默认带出新管家组织
        if (StringUtils.isBlank(response.getXgjRegionName())) {
            Integer joinMode = shopInfo.getJoinMode() == 3 ? CommonConstants.ONE : CommonConstants.ZERO;
            BigRegionDO bigRegionDO = bigRegionDAO.queryOrgInfoByBigRegionAndJoinMode(shopInfo.getRegionId(), joinMode);
            if (Objects.nonNull(bigRegionDO)) {
                response.setXgjRegionId(bigRegionDO.getOrgId());
                response.setXgjRegionName(bigRegionDO.getOrgName());
            }
        }
        if (StringUtils.isBlank(response.getAddresseeProvince())) {
            response.setAddresseeProvince(shopInfo.getProvince());
        }
        if (StringUtils.isBlank(response.getAddresseeCity())) {
            response.setAddresseeCity(shopInfo.getCity());
        }
        if (StringUtils.isBlank(response.getAddresseeDistrict())) {
            response.setAddresseeDistrict(shopInfo.getDistrict());
        }
        if (StringUtils.isBlank(response.getAddresseeAddress())) {
            response.setAddresseeAddress(shopInfo.getDetailAddress());
        }
        // 不存在的情况下从装修验收中获取
        if (StringUtils.isBlank(response.getDoorPhoto()) || StringUtils.isBlank(response.getInStorePhoto())) {
            AcceptanceInfoDO acceptanceInfoDO = acceptanceInfoDAO.selectByShopId(shopId);
            if (Objects.nonNull(acceptanceInfoDO)) {
                response.setDoorPhoto(StringUtils.isNotBlank(response.getDoorPhoto()) ? response.getDoorPhoto() : acceptanceInfoDO.getShopDoorwayPhoto());
                response.setInStorePhoto(StringUtils.isNotBlank(response.getInStorePhoto()) ? response.getInStorePhoto() : acceptanceInfoDO.getShopInteriorPhoto());
            }
        }
        return response;

    }

    private static void extracted(BuildInformationResponse response, BuildInformationDO informationDO) {
        response.setShopContactName(informationDO.getShopContactName());
        response.setShopContactMobile(informationDO.getShopContactMobile());
        response.setBusinessHours(informationDO.getBusinessHours());
        response.setBusinessMobile(informationDO.getBusinessMobile());
        response.setDoorPhoto(informationDO.getDoorPhoto());
        response.setInStorePhoto(informationDO.getInStorePhoto());
        response.setJuridicalIdCardFront(informationDO.getJuridicalIdCardFront());
        response.setJuridicalName(informationDO.getJuridicalName());
        response.setJuridicalIdCardNo(informationDO.getJuridicalIdCardNo());
        response.setJuridicalIdCardReverse(informationDO.getJuridicalIdCardReverse());
        response.setJuridicalHandheldIdCardReverse(informationDO.getJuridicalHandheldIdCardReverse());
        response.setJuridicalHandheldIdCardFront(informationDO.getJuridicalHandheldIdCardFront());
        response.setJuridicalHandheldIdCardReverse(informationDO.getJuridicalHandheldIdCardReverse());
        response.setSettlerIdCardNo(informationDO.getSettlerIdCardNo());
        response.setSettlerName(informationDO.getSettlerName());
        response.setSettlerBankPhotoUrl(informationDO.getSettlerBankPhotoUrl());
        response.setSettlerIdCardFront(informationDO.getSettlerIdCardFront());
        response.setSettlerIdCardReverse(informationDO.getSettlerIdCardReverse());
        response.setSettlerBankNumber(informationDO.getSettlerBankNumber());
        response.setSettlerBankMobile(informationDO.getSettlerBankMobile());
        response.setSettlerBankName(informationDO.getSettlerBankName());
        response.setAuthorizationUrl(informationDO.getAuthorizationUrl());
        response.setRelationshipProve(informationDO.getRelationshipProve());
        response.setAccountOpeningPermit(informationDO.getAccountOpeningPermit());
        response.setSettlerInHandFrontPicture(informationDO.getSettlerInHandFrontPicture());
        response.setSettlerInHandBackPicture(informationDO.getSettlerInHandBackPicture());
        response.setMiniProgramsShopName(informationDO.getCShopName());
        response.setSettlerBankBackPhotoUrl(informationDO.getSettlerBankBackPhotoUrl());
        response.setSettlerIsSamePartner(informationDO.getSettlerIsSamePartner());
        response.setJuridicalIsSamePartner(informationDO.getJuridicalIsSamePartner());
    }

    private static @NotNull OrderSysInfoDO getOrderSysInfoDO(BuildInformationRequest request) {
        OrderSysInfoDO orderSysInfoDO = new OrderSysInfoDO();
        orderSysInfoDO.setShopId(request.getShopId());
        orderSysInfoDO.setAddresseeName(request.getAddresseeName());
        orderSysInfoDO.setAddresseeMobile(request.getAddresseeMobile());
        orderSysInfoDO.setAddresseeProvince(request.getAddresseeProvince());
        orderSysInfoDO.setAddresseeCity(request.getAddresseeCity());
        orderSysInfoDO.setAddresseeDistrict(request.getAddresseeDistrict());
        orderSysInfoDO.setAddresseeAddress(request.getAddresseeAddress());
        return orderSysInfoDO;
    }

    @Override
    public Integer getJoinType(Long lineId) {
        QualificationsInfoDO qualificationsInfoDO = qualificationsInfoDAO.getByLineId(lineId);
        if (Objects.isNull(qualificationsInfoDO)) {
            return null;
        }
        return qualificationsInfoDO.getJoinType();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBuildSettler(BuildSettlerRequest request,String userId) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        QualificationsInfoDO qualificationsInfoDO = qualificationsInfoDAO.getByLineId(shopInfo.getLineId());
        BuildInformationDO buildInformationDO = buildInformationDAO.selectOneByShopId(request.getShopId());
        if (request.getSettlerIsSamePartner()) {
            buildInformationDO.setSettlerIdCardNo(qualificationsInfoDO.getIdCardNo());
            buildInformationDO.setSettlerName(lineInfoDO.getUsername());
            buildInformationDO.setSettlerIdCardFront(qualificationsInfoDO.getFrontOfIdCard());
            buildInformationDO.setSettlerIdCardReverse(qualificationsInfoDO.getBackOfIdCard());
        }else{
            buildInformationDO.setSettlerName(request.getSettlerName());
            buildInformationDO.setSettlerIdCardNo(request.getSettlerIdCardNo());
            buildInformationDO.setSettlerIdCardFront(request.getSettlerIdCardFront());
            buildInformationDO.setSettlerIdCardReverse(request.getSettlerIdCardReverse());
        }
        buildInformationDO.setSettlerIsSamePartner(request.getSettlerIsSamePartner());
        buildInformationDO.setSettlerInHandBackPicture(request.getSettlerInHandBackPicture());
        buildInformationDO.setSettlerInHandFrontPicture(request.getSettlerInHandFrontPicture());
        buildInformationDO.setSettlerBankPhotoUrl(request.getSettlerBankPhotoUrl());
        buildInformationDO.setSettlerBankNumber(request.getSettlerBankNumber());
        buildInformationDO.setSettlerBankMobile(request.getSettlerBankMobile());
        buildInformationDO.setSettlerBankName(request.getSettlerBankName());
        buildInformationDO.setSettlerBankBackPhotoUrl(request.getSettlerBankBackPhotoUrl());
        buildInformationDO.setUpdateTime(new Date());
        buildInformationDO.setUpdateUser(userId);
        buildInformationDAO.updateByShopIdSelective(buildInformationDO);
        List<PlatformBuildDO> platformBuildDOS = platformBuildDAO.selectByShopId(request.getShopId());
        if (CollectionUtils.isNotEmpty(platformBuildDOS)){
            for (PlatformBuildDO platformBuildDO : platformBuildDOS){
                platformBuildDO.setSettlerName(buildInformationDO.getSettlerName());
                platformBuildDO.setSettlerIdCardFront(buildInformationDO.getSettlerIdCardFront());
                platformBuildDO.setSettlerIdCardReverse(buildInformationDO.getSettlerIdCardReverse());
                platformBuildDO.setSettlerInHandBackPicture(buildInformationDO.getSettlerInHandBackPicture());
                platformBuildDO.setSettlerInHandFrontPicture(buildInformationDO.getSettlerInHandFrontPicture());
                platformBuildDO.setSettlerIdCardNo(buildInformationDO.getSettlerIdCardNo());
                platformBuildDO.setSettlerBankPhotoUrl(buildInformationDO.getSettlerBankPhotoUrl());
                platformBuildDO.setSettlerBankNumber(buildInformationDO.getSettlerBankNumber());
                platformBuildDO.setSettlerBankMobile(buildInformationDO.getSettlerBankMobile());
                platformBuildDO.setSettlerBankName(buildInformationDO.getSettlerBankName());
            }
        }
        platformBuildDAO.batchUpdate(platformBuildDOS);
        return true;
    }


}




