package com.cool.store.service.plan.impl;

import cn.hutool.core.date.DateUtil;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.dao.*;
import com.cool.store.dao.order.StoreOrderDAO;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.entity.LineInfoDO;
import com.cool.store.entity.ShopInfoDO;
import com.cool.store.entity.SysRoleDO;
import com.cool.store.entity.order.StoreOrderDO;
import com.cool.store.entity.plan.ShopDeliveryPlanDO;
import com.cool.store.entity.plan.ShopDeliveryPlanItemDO;
import com.cool.store.enums.*;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.EnterpriseUserRoleMapper;
import com.cool.store.request.plan.NotifyDeliveryRequest;
import com.cool.store.request.plan.UpdateDeliveryItemRequest;
import com.cool.store.service.UserAuthMappingService;
import com.cool.store.service.impl.CommonService;
import com.cool.store.service.plan.ShopDeliveryPlanService;
import com.cool.store.utils.BeanUtil;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.vo.plan.DeliveryDetailVO;
import com.cool.store.vo.plan.DeliveryInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 门店发货阶段服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopDeliveryPlanServiceImpl implements ShopDeliveryPlanService {

    private final ShopDeliveryPlanDAO shopDeliveryPlanDAO;
    private final ShopDeliveryPlanItemDAO shopDeliveryPlanItemDAO;
    private final ShopStageInfoDAO shopStageInfoDAO;
    private final StoreOrderDAO storeOrderDAO;
    private final CommonService commonService;
    private final EnterpriseUserDAO enterpriseUserDAO;
    private final EnterpriseUserRoleMapper enterpriseUserRoleMapper;
    private final ShopInfoDAO shopInfoDAO;
    private final LineInfoDAO lineInfoDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean notifyDelivery(NotifyDeliveryRequest request) {
        // 校验门店是否已存在发货计划
        ShopDeliveryPlanDO existingPlan = shopDeliveryPlanDAO.getByShopId(request.getShopId());
        if (existingPlan != null) {
            throw new ServiceException("该门店已存在发货计划，不能重复通知发货");
        }

        // 创建发货计划主表
        ShopDeliveryPlanDO planDO = new ShopDeliveryPlanDO();
        planDO.setShopId(request.getShopId());
        planDO.setExpectedDeliveryTime(request.getExpectedDeliveryDate());
        planDO.setRemark(request.getRemark());
        planDO.setCreateUser(CurrentUserHolder.getUser().getName());

        int result = shopDeliveryPlanDAO.insert(planDO);
        if (result <= 0) {
            throw new ServiceException("创建发货计划失败");
        }

        // 创建默认的发货项明细（采购设备和火码设备，初始状态为未发货）
        List<ShopDeliveryPlanItemDO> list = new ArrayList<>();
        ShopDeliveryPlanItemDO purchaseItem = new ShopDeliveryPlanItemDO();
        purchaseItem.setPlanId(planDO.getId());
        purchaseItem.setItemType(DeliveryItemTypeEnum.PURCHASE_DEVICE.getCode());
        purchaseItem.setDeliveryStatus(DeliveryStatusEnum.NOT_DELIVERED.getCode());
        list.add(purchaseItem);

        ShopDeliveryPlanItemDO fireCodeItem = new ShopDeliveryPlanItemDO();
        fireCodeItem.setPlanId(planDO.getId());
        fireCodeItem.setItemType(DeliveryItemTypeEnum.FIRE_CODE_DEVICE.getCode());
        fireCodeItem.setDeliveryStatus(DeliveryStatusEnum.NOT_DELIVERED.getCode());
        list.add(fireCodeItem);

        shopDeliveryPlanItemDAO.batchInsert(list);

        log.info("通知发货成功，门店ID：{}，发货计划ID：{}", request.getShopId(), planDO.getId());
        //阶段变为待发货
        shopStageInfoDAO.updateShopStageInfo(planDO.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_291);
        //发送短信通知
        List<String> userIds = enterpriseUserRoleMapper.getUserIdsByRoleIdList(Arrays.asList(UserRoleEnum.DEVICE_SHIPMENT_HM.getCode(), UserRoleEnum.DEVICE_SHIPMENT_CG.getCode()));
        List<EnterpriseUserDO> userInfoByUserIds = enterpriseUserDAO.getUserInfoByUserIds(userIds);
        userInfoByUserIds = userInfoByUserIds.stream().filter(x->StringUtils.isNotBlank(x.getMobile())).collect(Collectors.toList());
        Map<String, String> templateParam = new HashMap<>();
        ShopInfoDO shopInfo = shopInfoDAO.getShopInfo(request.getShopId());
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        templateParam.put("partnerName",lineInfo.getUsername());
        templateParam.put("shopName",shopInfo.getShopName());
        templateParam.put("shippingDate", DateUtil.format(request.getExpectedDeliveryDate(), CoolDateUtils.DATE_FORMAT_DAY));
        userInfoByUserIds.stream().forEach(x->{
            commonService.sendSms(x.getMobile(), SMSMsgEnum.DEVICE_NOTICE, templateParam);
        });
        return Boolean.TRUE;
    }

    @Override
    public DeliveryInfoVO queryDeliveryInfo(Long shopId) {
        if (shopId == null) {
            return null;
        }

        ShopDeliveryPlanDO planDO = shopDeliveryPlanDAO.getByShopId(shopId);
        if (planDO == null) {
            return null;
        }

        return BeanUtil.toBean(planDO, DeliveryInfoVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDeliveryItem(UpdateDeliveryItemRequest request) {
        // 查询发货计划
        ShopDeliveryPlanDO planDO = shopDeliveryPlanDAO.getByShopId(request.getShopId());
        if (planDO == null) {
            throw new ServiceException("该门店不存在发货计划");
        }

        // 查询对应的发货项
        ShopDeliveryPlanItemDO itemDO = shopDeliveryPlanItemDAO.getByPlanIdAndItemType(planDO.getId(), request.getItemType());
        if (itemDO == null) {
            throw new ServiceException("发货项不存在");
        }

        // 更新发货项信息
        itemDO.setDeliveryStatus(request.getDeliveryStatus());
        if (StringUtils.isNotBlank(request.getDeliveryRemark())) {
            itemDO.setDeliveryRemark(request.getDeliveryRemark());
        }
        int result = shopDeliveryPlanItemDAO.update(itemDO);
        if (result <= 0) {
            throw new ServiceException("更新发货项失败");
        }

        ShopSubStageStatusEnum shopSubStageStatusEnum = calculateDeliveryStage(planDO.getId());
        shopStageInfoDAO.updateShopStageInfo(planDO.getShopId(),shopSubStageStatusEnum );
        // 重新计算发货阶段
        return Boolean.TRUE;
    }

    @Override
    public DeliveryDetailVO queryDeliveryDetail(Long shopId) {
        if (shopId == null) {
            return null;
        }
        DeliveryDetailVO vo = new DeliveryDetailVO();

        StoreOrderDO latestOrderByShopId = storeOrderDAO.getLatestOrderByShopId(shopId);
        if (latestOrderByShopId!=null){
            vo.setOrderId(latestOrderByShopId.getId());
        }

        ShopDeliveryPlanDO planDO = shopDeliveryPlanDAO.getByShopId(shopId);
        if (planDO == null) {
            return vo;
        }

        BeanUtils.copyProperties(planDO,vo,"orderId");


        // 查询发货项明细
        List<ShopDeliveryPlanItemDO> items = shopDeliveryPlanItemDAO.listByPlanId(planDO.getId());
        if (CollectionUtils.isNotEmpty(items)) {
            for (ShopDeliveryPlanItemDO item : items) {
                if (DeliveryItemTypeEnum.PURCHASE_DEVICE.getCode().equals(item.getItemType())) {
                    vo.setPurchaseDeviceDeliveryStatus(item.getDeliveryStatus());
                    vo.setPurchaseDeviceDeliveryRemark(item.getDeliveryRemark());
                } else if (DeliveryItemTypeEnum.FIRE_CODE_DEVICE.getCode().equals(item.getItemType())) {
                    vo.setFireCodeDeviceDeliveryStatus(item.getDeliveryStatus());
                    vo.setFireCodeDeviceDeliveryRemark(item.getDeliveryRemark());
                }
            }
        }

        // 计算发货阶段
        return vo;
    }

    /**
     * 计算发货阶段
     * @param planId 发货计划ID
     * @return 发货阶段枚举
     */
    private ShopSubStageStatusEnum calculateDeliveryStage(Long planId) {
        List<ShopDeliveryPlanItemDO> items = shopDeliveryPlanItemDAO.listByPlanId(planId);
        if (CollectionUtils.isEmpty(items)) {
            return ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_291;
        }

        int deliveredCount = 0;
        int totalCount = items.size();

        for (ShopDeliveryPlanItemDO item : items) {
            if (DeliveryStatusEnum.DELIVERED.getCode().equals(item.getDeliveryStatus())) {
                deliveredCount++;
            }
        }


        if (deliveredCount == 0) {
            return ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_291;
        } else if (deliveredCount == totalCount) {
            return ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_294;
        } else {
            return ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_292;
        }
    }
}
