package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.dao.FirstOrderDAO;
import com.cool.store.dao.LineInfoDAO;
import com.cool.store.dao.ShopStageInfoDAO;
import com.cool.store.dto.openPreparation.FirstOrderDTO;
import com.cool.store.entity.FirstOrderDO;
import com.cool.store.entity.LineInfoDO;
import com.cool.store.entity.ShopInfoDO;
import com.cool.store.entity.ShopStageInfoDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.SMSMsgEnum;
import com.cool.store.enums.point.ShopSubStageEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.FirstOrderRequest;
import com.cool.store.service.CoolStoreStartFlowService;
import com.cool.store.service.FirstOrderService;
import com.cool.store.service.PreparationService;
import com.cool.store.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * @Auther: WangShuo
 * @Date: 2024/04/24/下午8:53
 * @Version 1.0
 * @注释:
 */
@Service
@Slf4j
public class FirstOrderServiceImp implements FirstOrderService {
    @Resource
    private FirstOrderDAO firstOrderDAO;
    @Resource
    private PreparationService preparationService;
    @Resource
    private CommonService commonService;
    @Resource
    private ShopService shopService;
    @Resource
    private ShopStageInfoDAO shopStageInfoDAO;
    @Resource
    private CoolStoreStartFlowService coolStoreStartFlowService;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private LineInfoDAO lineInfoDAO;

    @Override
    public Integer saveOrder(FirstOrderRequest request, LoginUserInfo user) {
        log.info("save order:{}", JSONObject.toJSONString(request));
        if (request == null) {
            throw new ServiceException(ErrorCodeEnum.FIRST_ORDER_PARAM_NULL);
        }
        String userId = user.getUserId();
        FirstOrderDO order = new FirstOrderDO();
        try {
            BeanUtils.copyProperties(order, request);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        FirstOrderDTO firstOrderDTO = firstOrderDAO.selectFirstOrderByShopId(order.getShopId());
        Integer num;
        if (Objects.isNull(firstOrderDTO)) {
            //第一次提交
            order.setCreateTime(new Date());
            order.setCreateUserId(userId);
            num = firstOrderDAO.insertFirstOrder(order);
        } else {
            //修改只更新下面2个
            order.setId(firstOrderDTO.getId());
            order.setUpdateTime(new Date());
            order.setUpdateUserId(userId);
            num = firstOrderDAO.updateByPrimaryKeySelective(order);
        }
        shopStageInfoDAO.updateShopStageInfo(order.getShopId(),
                ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_152);
        //发送消息至加盟商
        ShopInfoDO shopInfo = shopService.getShopInfo(order.getShopId());
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(shopInfo.getLineId());
        Map<String,String> messageMap =new HashMap<>();
        messageMap.put("totalOrderDeposit",request.getTotalOrderDeposit());
        commonService.sendSms(lineInfo.getMobile(), SMSMsgEnum.FIRST_ORDER, messageMap);
        //云立方同步
        if (num > 0) {
            try {
                String storeNum = shopInfo.getStoreNum();
                Boolean flag = coolStoreStartFlowService.getFirstOrder(storeNum);
                log.info("saveOrder,flag:{}", flag);
                if (flag == null) {
                    throw new ServiceException(ErrorCodeEnum.GET_FIRST_ORDER);
                }
                if (flag) {
                    //更改子阶段状态
                    shopStageInfoDAO.updateShopStageInfo(order.getShopId(),
                            ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151);
                    preparationService.whetherToOpenForAcceptance(order.getShopId());
                }
            } catch (Exception e) {
                log.error("获取鲜丰订货金异常", e);
            }
        }
        return num;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public FirstOrderDTO getOrder(Long shopId) {
        log.info("getOrder shopId:{},", shopId);
        if (shopId == null) {
            log.error("shopId is null");
            throw new ServiceException(ErrorCodeEnum.FIRST_ORDER_PARAM_NULL);
        }
        FirstOrderDTO order = firstOrderDAO.selectFirstOrderByShopId(shopId);
        ShopStageInfoDO shopSubStageInfo = shopStageInfoDAO.getShopSubStageInfo(shopId, ShopSubStageEnum.SHOP_STAGE_15);
        if (ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151.getShopSubStageStatus().equals(shopSubStageInfo.getShopSubStageStatus())) {

            String userName = enterpriseUserDAO.getUserName(order.getCreateUserId());
            order.setPartnerName(userName);
            order.setFirstOrderSubStage(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151.getShopSubStageStatus());
            return order;
        }
        if (Objects.nonNull(order)) {
            try {

                String userName = enterpriseUserDAO.getUserName(order.getCreateUserId());
                order.setPartnerName(userName);
                ShopInfoDO shopInfo = shopService.getShopInfo(order.getShopId());
                String storeNum = shopInfo.getStoreNum();
                Boolean flag = coolStoreStartFlowService.getFirstOrder(storeNum);
                log.info("saveOrder,flag:{}", flag);
                if (flag == null) {
                    throw new ServiceException(ErrorCodeEnum.GET_FIRST_ORDER);
                }
                if (flag) {
                    //更改子阶段状态
                    shopStageInfoDAO.updateShopStageInfo(order.getShopId(),
                            ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151);
                    order.setFirstOrderSubStage(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_151.getShopSubStageStatus());
                    preparationService.whetherToOpenForAcceptance(order.getShopId());
                } else {
                    order.setFirstOrderSubStage(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_152.getShopSubStageStatus());
                }
            } catch (Exception e) {
                log.error("获取鲜丰订货金异常", e);
            }

        }
        return order;
    }
}
