package com.cool.store.service.impl;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.context.PartnerUserHolder;
import com.cool.store.dao.HyOpenAreaInfoDAO;
import com.cool.store.dao.HyPartnerUserInfoDAO;
import com.cool.store.dto.log.UserInfoUpdateDTO;
import com.cool.store.entity.HyOpenAreaInfoDO;
import com.cool.store.entity.HyPartnerLineInfoDO;
import com.cool.store.entity.HyPartnerUserInfoDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.OperateTypeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.PartnerIntentInfoRequest;
import com.cool.store.request.PartnerUserInfoRequest;
import com.cool.store.service.*;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.vo.ApplyBaseInfoVO;
import com.cool.store.vo.InviteCodeDetailVO;
import com.cool.store.vo.PartnerUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class PartnerUserInfoServiceImpl implements PartnerUserInfoService {

    @Autowired
    private HyPartnerUserInfoDAO hyPartnerUserInfoDAO;

    @Resource
    HyPartnerLineInfoService hyPartnerLineInfoService;

    @Resource
    private HyPartnerBaseInfoService hyPartnerBaseInfoService;

    @Resource
    HyOpenAreaInfoDAO hyOpenAreaInfoDAO;
    @Resource
    private RedisUtilPool redisUtilPool;
    @Autowired
    private LogService logService;
    @Resource
    HyPhoneLocationService hyPhoneLocationService;

    @Override
    public HyPartnerUserInfoDO selectByPartnerId(String partnerId) {
        return hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
    }

    @Override
    public Boolean queryJoinNotice(String partnerId) {
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
        if (hyPartnerUserInfoDO==null){
            throw new ServiceException(ErrorCodeEnum.PARTNER_USER_NOT_EXIST);
        }
        return hyPartnerUserInfoDO.getIsWritePartnerKnow() == 1;
    }

    @Override
    public Boolean completeJoinNotice(String partnerId) {
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
        if (hyPartnerUserInfoDO == null){
            throw new ServiceException(ErrorCodeEnum.PARTNER_USER_NOT_EXIST);
        }
        hyPartnerUserInfoDAO.updateJoinKnowById(CommonConstants.ONE, hyPartnerUserInfoDO.getId());
        return true;
    }

    @Override
    public InviteCodeDetailVO selectInviteCodeDetail(String partnerId) {
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
        if (hyPartnerUserInfoDO==null){
            throw new ServiceException(ErrorCodeEnum.PARTNER_USER_NOT_EXIST);
        }
        InviteCodeDetailVO inviteCodeDetailVO = new InviteCodeDetailVO();
        inviteCodeDetailVO.setInviteCode(hyPartnerUserInfoDO.getInviteCode());
        inviteCodeDetailVO.setStoreName(hyPartnerUserInfoDO.getShopName());
        inviteCodeDetailVO.setStoreCode(hyPartnerUserInfoDO.getShopCode());
        inviteCodeDetailVO.setPartnerPhone(hyPartnerUserInfoDO.getRecommendPartnerMobile());
        inviteCodeDetailVO.setPartnerName(hyPartnerUserInfoDO.getRecommendPartnerName());
        return inviteCodeDetailVO;
    }

    @Override
    public ApplyBaseInfoVO updatePartnerUserInfo(PartnerUserInfoRequest partnerUserInfoRequest) {
        log.info("PartnerUserInfoServiceImpl#updatePartnerUserInfo partnerUserInfoRequest:{}", JSONObject.toJSONString(partnerUserInfoRequest));
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(String.valueOf(partnerUserInfoRequest.getPartnerId()));
        if (hyPartnerUserInfoDO == null){
            throw new ServiceException(ErrorCodeEnum.PARTNER_USER_NOT_EXIST);
        }
        UserInfoUpdateDTO.UserInfoUpdate beforeUserinfoUpdate = new UserInfoUpdateDTO.UserInfoUpdate(hyPartnerUserInfoDO.getUsername(), hyPartnerUserInfoDO.getMobile(), hyPartnerUserInfoDO.getLiveArea(), hyPartnerUserInfoDO.getWantShopArea(), hyPartnerUserInfoDO.getAcceptAdjustType());
        UserInfoUpdateDTO.UserInfoUpdate afterUserinfoUpdate = new UserInfoUpdateDTO.UserInfoUpdate(partnerUserInfoRequest.getUsername(), partnerUserInfoRequest.getMobile(), partnerUserInfoRequest.getLiveArea(), partnerUserInfoRequest.getWantShopArea(), partnerUserInfoRequest.getAcceptAdjustType());

        ApplyBaseInfoVO applyBaseInfoVO = new ApplyBaseInfoVO();
        fillUserInfoDOByRequest(hyPartnerUserInfoDO, partnerUserInfoRequest);
        hyPartnerUserInfoDAO.updateByPrimaryKeySelective(hyPartnerUserInfoDO);
        // 生成一条线索
        HyPartnerLineInfoDO hyPartnerLineInfoDO =  hyPartnerLineInfoService.generateDefaultLineInfo(hyPartnerUserInfoDO.getPartnerId(), partnerUserInfoRequest.getWantShopArea(), partnerUserInfoRequest.getAcceptAdjustType(),Boolean.TRUE);
        // 生成一条意向基本信息
        hyPartnerBaseInfoService.generateBaseInfo(hyPartnerUserInfoDO, hyPartnerLineInfoDO.getId(), null);
        HyOpenAreaInfoDO hyOpenAreaInfoDO = hyOpenAreaInfoDAO.selectById(Long.valueOf(partnerUserInfoRequest.getWantShopArea()));
        List<HyOpenAreaInfoDO> hyOpenAreaInfoDOS = null;
        if(hyOpenAreaInfoDO != null){
            applyBaseInfoVO.setSelectAreaStatus(hyOpenAreaInfoDO.getAreaStatus());
            String areaPath = hyOpenAreaInfoDO.getAreaPath();
            String province = areaPath.substring(0, areaPath.indexOf("/", areaPath.indexOf("/") + 1));
            hyOpenAreaInfoDOS = hyOpenAreaInfoDAO.queryByKeyword(province, true, null, true);
         }
        applyBaseInfoVO.setProvinceHasOpenArea(false);
        if (CollectionUtils.isNotEmpty(hyOpenAreaInfoDOS)) {
            applyBaseInfoVO.setProvinceHasOpenArea(true);
        }
        applyBaseInfoVO.setPartnerLineId(hyPartnerLineInfoDO.getId());
        applyBaseInfoVO.setLineStatus(hyPartnerLineInfoDO.getLineStatus());
        String cacheKey = MessageFormat.format(RedisConstant.PARTNER_INTENTINFO_CACHE_KEY, partnerUserInfoRequest.getPartnerId(), hyPartnerLineInfoDO.getId());
        if (StringUtils.isNotBlank(redisUtilPool.getString(cacheKey))) {
            PartnerIntentInfoRequest request = JSONObject.parseObject(redisUtilPool.getString(cacheKey), PartnerIntentInfoRequest.class);
            if(!partnerUserInfoRequest.getWantShopArea().equals(request.getWantShopArea())
                    || !partnerUserInfoRequest.getAcceptAdjustType().equals(request.getAcceptAdjustType())){
                request.setWantShopArea(partnerUserInfoRequest.getWantShopArea());
                request.setAcceptAdjustType(partnerUserInfoRequest.getAcceptAdjustType());
                redisUtilPool.setString(cacheKey, JSONObject.toJSONString(request), RedisConstant.ONE_DAY_SECONDS);
            }
        }
        //记录日志
        PartnerUserInfoVO operator = PartnerUserHolder.getUser();
        UserInfoUpdateDTO log = UserInfoUpdateDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getPartnerId()).operateUsername(operator.getUsername())
                .operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC))
                .beforeUserinfoUpdate(beforeUserinfoUpdate).afterUserinfoUpdate(afterUserinfoUpdate).build();
        logService.recordPartnerBizLog(operator,hyPartnerLineInfoDO.getId(), OperateTypeEnum.USERINFO_UPDATE,log);
        return applyBaseInfoVO;
    }

    private void fillUserInfoDOByRequest(HyPartnerUserInfoDO hyPartnerUserInfoDO, PartnerUserInfoRequest partnerUserInfoRequest) {
        hyPartnerUserInfoDO.setUsername(partnerUserInfoRequest.getUsername());
        hyPartnerUserInfoDO.setMobile(partnerUserInfoRequest.getMobile());
        hyPartnerUserInfoDO.setLiveArea(partnerUserInfoRequest.getLiveArea());
        hyPartnerUserInfoDO.setWantShopArea(partnerUserInfoRequest.getWantShopArea());
        if (!Objects.isNull(partnerUserInfoRequest.getAcceptAdjustType())){
            hyPartnerUserInfoDO.setAcceptAdjustType(partnerUserInfoRequest.getAcceptAdjustType());
        }
        hyPartnerUserInfoDO.setInviteCode(partnerUserInfoRequest.getInviteCode());
        hyPartnerUserInfoDO.setShopCode(partnerUserInfoRequest.getShopCode());
        hyPartnerUserInfoDO.setShopName(partnerUserInfoRequest.getShopName());
        hyPartnerUserInfoDO.setShopId(partnerUserInfoRequest.getShopId());
        hyPartnerUserInfoDO.setRecommendPartnerId(partnerUserInfoRequest.getRecommendPartnerId());
        hyPartnerUserInfoDO.setRecommendPartnerName(partnerUserInfoRequest.getRecommendPartnerName());
        hyPartnerUserInfoDO.setRecommendPartnerMobile(partnerUserInfoRequest.getRecommendPartnerMobile());
    }
}
