package com.cool.store.service.impl;

import com.cool.store.constants.CommonConstants;
import com.cool.store.context.LoginUserInfo;
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.FranchiseFeeMapper;
import com.cool.store.mapper.SignFranchiseMapper;
import com.cool.store.request.AuditRequest;
import com.cool.store.request.HqtBuildRequest;
import com.cool.store.request.OrderSysInfoRequest;
import com.cool.store.service.*;
import com.cool.store.utils.poi.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
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;

import static com.cool.store.enums.UserRoleEnum.*;
import static com.cool.store.enums.point.ShopSubStageStatusEnum.*;

/**
 * @Author: WangShuo
 * @Date: 2025/04/06/16:07
 * @Version 1.0
 * @注释:
 */
@Service
public class OrderSysInfoServiceImpl implements OrderSysInfoService {

    @Resource
    private ShopService shopService;
    @Resource
    private HqtAPIService hqtAPIService;
    @Resource
    private BigRegionDAO bigRegionDAO;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private SyncMainSysServer syncMainSysServer;
    @Resource
    FranchiseFeeMapper franchiseFeeMapper;
    @Resource
    private OperationLogDAO operationLogDAO;
    @Resource
    private OrderSysInfoDAO orderSysInfoDAO;
    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    private PreparationServiceImpl preparationService;
    @Resource
    private UserAuthMappingService userAuthMappingService;
    @Resource
    private CommonService commonService;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private ShopAuditInfoDAO shopAuditInfoDAO;
    @Value("${special.user.id}")
    private String specialUserId;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateByShopId(OrderSysInfoRequest request, LoginUserInfo user) {
        //当前登录用户
        String curUserId = user.getUserId();
        String curName = user.getName();
        //参数校验
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        if (!request.check(shopInfo.getJoinMode())) {
            throw new ServiceException(ErrorCodeEnum.THE_DATA_IS_NOT_FILLED);
        }
        OrderSysInfoDO orderSysInfoDO = orderSysInfoDAO.selectByShopId(request.getShopId());
        if (Objects.isNull(orderSysInfoDO)) {
            orderSysInfoDO = new OrderSysInfoDO();
            orderSysInfoDO.setShopId(request.getShopId());
            orderSysInfoDAO.insertSelective(orderSysInfoDO);
        }
        ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(request.getShopId(), ShopSubStageEnum.SHOP_STAGE_15);
        if (request.getType().equals(OrderSysTypeEnum.ORDER_SYS_TYPE_1.getType())) {
            String xgjVicePresident = request.getXgjVicePresident();
            orderSysInfoDO.setXgjVicePresident(xgjVicePresident);
            if (StringUtils.isNotBlank(xgjVicePresident)&&xgjVicePresident.contains("-")){
                String name = xgjVicePresident.substring(xgjVicePresident.indexOf("-")+1);
                orderSysInfoDO.setXgjVicePresident(name);
            }
            orderSysInfoDO.setXgjRegionName(request.getXgjRegionName());
            orderSysInfoDO.setXgjRegionId(request.getXgjRegionId());
            orderSysInfoDO.setAddresseeProvince(request.getAddresseeProvince());
            orderSysInfoDO.setAddresseeCity(request.getAddresseeCity());
            orderSysInfoDO.setAddresseeDistrict(request.getAddresseeDistrict());
            orderSysInfoDO.setAddresseeAddress(request.getAddresseeAddress());
            orderSysInfoDO.setDeclareGoodsLogisticsWarehouse(request.getDeclareGoodsLogisticsWarehouse());
            orderSysInfoDO.setDeclareGoodsType(request.getDeclareGoodsType());
            orderSysInfoDO.setDeclareGoodsDate(request.getDeclareGoodsDate());
            orderSysInfoDO.setWarehouseDeliveryDate(request.getWarehouseDeliveryDate());
            orderSysInfoDO.setOrderRemark(request.getOrderRemark());
            if (shopSubStageInfo.getShopSubStageStatus().equals(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151.getShopSubStageStatus())) {
                orderSysInfoDO.setOrderCreateTime(new Date());
                orderSysInfoDO.setOrderCreateUser(curUserId);
                shopStageInfoDAO.updateShopStageInfo(request.getShopId(), SHOP_SUB_STAGE_STATUS_156);
                stageCompletion(request.getShopId());
                syncMainSysServer.syncStore(request.getShopId());
                return orderSysInfoDAO.updateByShopId(orderSysInfoDO);
            } else {
                orderSysInfoDO.setOrderUpdateTime(new Date());
                orderSysInfoDO.setOrderUpdateUser(curUserId);
                return orderSysInfoDAO.updateByShopId(orderSysInfoDO);
            }
        }
        if (request.getType().equals(OrderSysTypeEnum.ORDER_SYS_TYPE_2.getType())) {
            //检验门店编码是否重复
            if(shopService.checkShopCodeRepeat(request.getShopCode(), request.getShopId())){
                throw new ServiceException(ErrorCodeEnum.SHOP_CODE_EXIST);
            }
            shopInfoDAO.updateShopCode(request.getShopCode(), request.getShopId());
            orderSysInfoDO.setReceivingFirmName(request.getReceivingFirmName());
            orderSysInfoDO.setReceivingMsBankAccount(request.getReceivingMsBankAccount());
            orderSysInfoDO.setReceivingMsBankBranch(request.getReceivingMsBankBranch());
            orderSysInfoDO.setBankUnionPayAccount(request.getBankUnionPayAccount());
            orderSysInfoDO.setOrderType(request.getOrderType());
            if (shopSubStageInfo.getShopSubStageStatus().equals(SHOP_SUB_STAGE_STATUS_152.getShopSubStageStatus())) {
                if (orderSysInfoDO.getReceivingCreateTime() == null) {
                    orderSysInfoDO.setReceivingCreateTime(new Date());
                    orderSysInfoDO.setReceivingCreateUser(curUserId);
                } else {
                    orderSysInfoDO.setReceivingUpdateTime(new Date());
                    orderSysInfoDO.setReceivingUpdateUser(curUserId);
                }
                shopStageInfoDAO.updateShopStageInfo(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_153);
                //审批流
                operationLogService.addOperationLog(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_152, curUserId, curName,
                        OperationTypeEnum.OPERATION_TYPE_0, "建店资料财务提交审批", OperationStatusEnum.PROCESSED);
                List<EnterpriseUserDO> directorList = new ArrayList<>();
                List<EnterpriseUserDO> headUser = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.HEAD_OF_DIVISION, shopInfoDAO.getShopInfo(request.getShopId()).getRegionId());
                if (CollectionUtils.isNotEmpty(headUser)) {
                    directorList.addAll(headUser);
                }
                List<EnterpriseUserDO> manager = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.REGIONAL_MANAGER, shopInfoDAO.getShopInfo(request.getShopId()).getRegionId());
                if (CollectionUtils.isNotEmpty(manager)) {
                    directorList.addAll(manager);
                }
                operationLogService.addOperationLog(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_153,
                        curUserId, directorList,
                        OperationTypeEnum.OPERATION_TYPE_1, "建店资料分管总监审批", OperationStatusEnum.NOT_PROCESSED);
                List<String> userIds = directorList.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList());
                sendSms(request.getShopId(), userIds);
                return orderSysInfoDAO.updateByShopId(orderSysInfoDO);
            } else {
                orderSysInfoDO.setReceivingUpdateTime(new Date());
                orderSysInfoDO.setReceivingUpdateUser(curUserId);
                return orderSysInfoDAO.updateByShopId(orderSysInfoDO);
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer audit(AuditRequest request, LoginUserInfo user) {
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        if (shopInfo.getShopDecorationAttributes() == null){
            throw new ServiceException(ErrorCodeEnum.SHOP_DECORATION_ATTRIBUTES_IS_NULL);
        }
        String curUserId = user.getUserId();
        request.setOperateUserId(user.getUserId());
        request.setOperateUserName(user.getName());
        ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(request.getShopId(), ShopSubStageEnum.SHOP_STAGE_15);
        if (!shopSubStageInfo.getShopSubStageStatus().equals(request.getShopSubStageStatus()) || shopSubStageInfo.getShopSubStageStatus().equals(SHOP_SUB_STAGE_STATUS_156.getShopSubStageStatus())) {
            throw new ServiceException(ErrorCodeEnum.WORK_FLOW_STAGE_PASS_ERROR);
        }
        ShopSubStageStatusEnum nowStatus = ShopSubStageStatusEnum.getShopSubStageStatusEnum(request.getShopSubStageStatus());
        if (nowStatus == null) {
            throw new ServiceException(ErrorCodeEnum.SHOP_STAGE_ERROR);
        }
        ShopAuditInfoDO shopAuditInfoDO = AuditRequest.convert(request, AuditTypeEnum.BUILDINFORMATION);
        Long auditId = shopAuditInfoDAO.addAuditInfo(shopAuditInfoDO);
        //更新操作记录
        List<OperationLogDO> operationLogs = operationLogDAO.getBySubStageStatusEnumAndsStatus(request.getShopId(), nowStatus, OperationTypeEnum.OPERATION_TYPE_1.getCode());
        operationLogService.batchUpdateProcessed(operationLogs, auditId, request.getOperateUserId(), request.getReason());

        //查询毛泽军下级区域 只有毛泽军的下级需要总裁处理 其他不需要总裁处理:
        List<String> regionIds = userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(specialUserId);
        //是否有总裁处理flag
        Boolean flag = Boolean.FALSE;
        //如果是毛泽军的下级 则需要总裁处理
        if (shopInfo != null && shopInfo.getRegionId() != null) {
            flag = regionIds.contains(String.valueOf(shopInfo.getRegionId()));
        }


        //下一阶段
        ShopSubStageStatusEnum nextStatus;
        switch (nowStatus) {
            case SHOP_SUB_STAGE_STATUS_153:
                nextStatus = SHOP_SUB_STAGE_STATUS_154;
                List<EnterpriseUserDO> users = userAuthMappingService.getUserIdByRoleEnumAndRegionId(Arrays.asList(VICE_PRESIDENT_IN_CHARGE, BRAND_HEAD), shopInfoDAO.getShopInfo(request.getShopId()).getRegionId());
                List<String> userIds = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(users)) {
                    userIds = users.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList());
                }
                sendSms(request.getShopId(), userIds);
                operationLogService.addOperationLog(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_154,
                        curUserId, users,
                        OperationTypeEnum.OPERATION_TYPE_1, "建店资料分管副总裁审批", OperationStatusEnum.NOT_PROCESSED);
                break;
            case SHOP_SUB_STAGE_STATUS_154:
                nextStatus = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_155;
                if (flag) {
                    List<EnterpriseUserDO> users1 = userAuthMappingService.getAllUserByRoleEnumAndRegionId(PRESIDENT, shopInfoDAO.getShopInfo(request.getShopId()).getRegionId());
                    List<String> userIds1 = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(users1)) {
                        userIds1 = users1.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList());
                    }
                    sendSms(request.getShopId(), userIds1);
                    operationLogService.addOperationLog(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_155,
                            curUserId, users1,
                            OperationTypeEnum.OPERATION_TYPE_1, "建店资料总裁审批", OperationStatusEnum.NOT_PROCESSED);
                }
                break;
            case SHOP_SUB_STAGE_STATUS_155:
                nextStatus = SHOP_SUB_STAGE_STATUS_156;
                break;
            default:
                nextStatus = null;
                break;
        }
        //
        if (AuditResultTypeEnum.REJECT.getCode().equals(request.getResultType())) {
            //回退
            return shopStageInfoDAO.updateShopStageInfo(request.getShopId(), SHOP_SUB_STAGE_STATUS_152);
        }
        //测量阶段
        ShopStageInfoDO measurementStage = shopStageInfoDAO.getShopSubStageInfo(request.getShopId(), ShopSubStageEnum.SHOP_STAGE_8_6);
        if (AuditResultTypeEnum.PASS.getCode().equals(request.getResultType())) {
            //如果不是毛泽军下级大区 直接完成不用总裁审批
            if (!flag && SHOP_SUB_STAGE_STATUS_154.equals(nowStatus)) {
                shopStageInfoDAO.updateShopStageInfo(request.getShopId(), SHOP_SUB_STAGE_STATUS_156);
                stageCompletion(request.getShopId());
                syncMainSysServer.syncStore(request.getShopId());
                return CommonConstants.ONE;

            } else {
                shopStageInfoDAO.updateShopStageInfo(request.getShopId(), nextStatus);
                if (SHOP_SUB_STAGE_STATUS_156.equals(nextStatus)) {
                    stageCompletion(request.getShopId());
                    syncMainSysServer.syncStore(request.getShopId());
                }
                return CommonConstants.ONE;
            }
        }
        return 0;
    }

    void sendSms(Long shopId, List<String> userIds) {
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(shopId);
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfoDO.getLineId());
        HashMap<String, String> map = new HashMap<>();
        map.put("partnerUsername", lineInfoDO.getUsername());
        map.put("partnerMobile", lineInfoDO.getMobile());
        map.put("storeName", shopInfoDO.getShopName());

        commonService.sendQWMessage(userIds,
                MessageEnum.MESSAGE_54,
                map);
    }

    void stageCompletion(Long shopId) {
        //初始化数据
        preparationService.licenseCompleted(shopId);
        preparationService.sysStoreCompleted(shopId);
        preparationService.businessLicenseAndBuildStoreCompleted(shopId);
        preparationService.buildStoreAndDecorationComplete(shopId);
        preparationService.selectSiteAndBuildStoreComplete(shopId);
        preparationService.buildStoreComplete(shopId);
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(shopId);
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfoDO.getLineId());
        HashMap<String, String> map = new HashMap<>();
        map.put("partnerUsername", lineInfoDO.getUsername());
        map.put("partnerMobile", lineInfoDO.getMobile());
        map.put("storeName", shopInfoDO.getShopName());
        List<EnterpriseUserDO> itList = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.IT_EMPLOYEE, shopInfoDO.getRegionId());
        List<String> itUsers = new ArrayList<>();
        if (Objects.nonNull(itList)) {
            itUsers.addAll(itList.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList()));
        }
        commonService.sendQWMessage(itUsers,
                MessageEnum.MESSAGE_39,
                map);
        List<EnterpriseUserDO> posList = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.HUO_MA_EMPLOYEE, shopInfoDO.getRegionId());
        List<String> posUsers = new ArrayList<>();
        if (Objects.nonNull(posList)) {
            posUsers.addAll(posList.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList()));
        }
        commonService.sendQWMessage(posUsers,
                MessageEnum.MESSAGE_38,
                map);
        List<EnterpriseUserDO> xfList = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.XIN_FA_SYS_CUSTOMER, shopInfoDO.getRegionId());
        List<String> xfUsers = new ArrayList<>();
        if (Objects.nonNull(xfList)) {
            xfUsers.addAll(xfList.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList()));
        }
        commonService.sendQWMessage(xfUsers,
                MessageEnum.MESSAGE_40,
                map);
        List<EnterpriseUserDO> zxtList = userAuthMappingService.getAllUserByRoleEnumAndRegionId(UserRoleEnum.TENT_PASS_CUSTOMER, shopInfoDO.getRegionId());
        List<String> zxtUsers = new ArrayList<>();
        if (Objects.nonNull(zxtList)) {
            zxtUsers.addAll(zxtList.stream().map(EnterpriseUserDO::getUserId).collect(Collectors.toList()));
        }
        commonService.sendQWMessage(zxtUsers,
                MessageEnum.MESSAGE_41,
                map);
    }
}
