package com.fdkankan.ucenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.ConstantUrl;
import com.fdkankan.common.util.SecurityUtil;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.ucenter.common.RedisKeyUtil;
import com.fdkankan.ucenter.common.SceneSourceUtil;
import com.fdkankan.ucenter.common.constants.ResultCode;
import com.fdkankan.ucenter.config.UcenterConfig;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.exception.BusinessException;
import com.fdkankan.ucenter.geo.IPUtils;
import com.fdkankan.ucenter.mapper.IContactUsMapper;
import com.fdkankan.ucenter.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.ucenter.util.DateUserUtil;
import com.fdkankan.ucenter.vo.request.RegisterParam;
import com.fdkankan.ucenter.vo.response.LoginVo;
import com.fdkankan.ucenter.vo.response.SceneInfoVo;
import com.fdkankan.ucenter.vo.response.ScenePlusVo;
import com.fdkankan.ucenter.vo.response.SceneVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2025-10-20
 */
@Service
@Slf4j
public class ContactUsServiceImpl extends ServiceImpl<IContactUsMapper, ContactUs> implements IContactUsService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    IMailTemplateService mailTemplateService;
    @Autowired
    IUserService userService;
    @Autowired
    LoginService loginService;
    @Autowired
    IContactUsPointService contactUsPointService;
    @Autowired
    UcenterConfig ucenterConfig;

    @Override
    public void submit(ContactUs contactUs) {
        if(StringUtils.isBlank(contactUs.getName()) || StringUtils.isBlank(contactUs.getTel())
                || StringUtils.isBlank(contactUs.getEmail()) || StringUtils.isBlank(contactUs.getCompany())){
            throw new BusinessException(ResultCode.PARAM_MISS);
        }
        String redisKey = String.format(RedisKeyUtil.CONTACT_US_KEY,contactUs.getEmail());
        if(redisUtil.hasKey(redisKey)){
            throw new BusinessException(ResultCode.email_submit);
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String redisKey2 = String.format(RedisKeyUtil.CONTACT_US_KEY,uuid);

        User user = userService.getByUserName(contactUs.getEmail());
        contactUs.setCountry(IPUtils.getCountry(contactUs.getIpAddress()));
        redisUtil.set(redisKey,"1",60 *5);
        if(user !=null){
            mailTemplateService.sendContactUs2(contactUs.getEmail(),13);
            this.save(contactUs);
            return;
        }

        String callBackUrl = ucenterConfig.getContactUsCallBackUrl() + uuid;
        Boolean b = mailTemplateService.sendContactUs(contactUs.getEmail(),callBackUrl);
        if(b){
            redisUtil.set(redisKey2, JSONObject.toJSONString(contactUs),ucenterConfig.getEmailExTime());
        }
        this.save(contactUs);
    }

    @Override
    public LoginVo callBack(String uuid) {
        String rediskey = String.format(RedisKeyUtil.CONTACT_US_KEY,uuid);
        if(!redisUtil.hasKey(rediskey)){
            throw new BusinessException(ResultCode.url_exprix);
        }

        try {
            if(redisUtil.hasKey(rediskey) ){
                ContactUs contactUs = JSONObject.parseObject( redisUtil.get(rediskey),ContactUs.class);
                User userEntity = userService.getByUserName(contactUs.getEmail());
                if(userEntity == null){
                    userEntity = new User();
                    userEntity.setPassword(SecurityUtil.MD5(ucenterConfig.getContactUsDfPassword()));
                    userEntity.setEmail(contactUs.getEmail());
                    userEntity.setUserName(contactUs.getEmail());
                    userEntity.setNickName(contactUs.getName());
                    userEntity.setHead(ConstantUrl.DEFAULT_USER_HEAD);
                    userEntity.setStatus(1);
                    userEntity.setIsNotice(1);
                    userEntity.setRecStatus("A");
                    userEntity.setCreateTime(DateUserUtil.getDate(new Date()));
                    userEntity.setUpdateTime(DateUserUtil.getDate(new Date()));
                    userEntity.setAgentKey("wherefor");
                    userService.save(userEntity);
                }
                LoginVo login = loginService.login(userEntity);
                return login;
            }

        }catch (Exception e){
            log.info("contact-us-callback-error:{}",e);
        }finally {
            redisUtil.del(rediskey);
        }
        return null;
    }

    @Override
    public  void point(ContactUsPoint contactUsPoint) {
        ContactUsPoint contactUsPoint2 = contactUsPointService.getBySessionId(contactUsPoint.getSessionId());
        if(contactUsPoint2 == null){
            contactUsPoint.setStopTime(1L);
            contactUsPoint.setCountry(IPUtils.getCountry(contactUsPoint.getIpAddress()));
        }
        if(contactUsPoint2 != null){
            contactUsPoint.setId(contactUsPoint2.getId());
            contactUsPoint.setStopTime(contactUsPoint2.getStopTime() + 1);
        }
        contactUsPointService.saveOrUpdate(contactUsPoint);
    }

    @Autowired
    IContactUsSceneService contactUsSceneService;
    @Autowired
    IScenePlusService scenePlusService;
    @Override
    public List<SceneVo> sceneList() {
        List<ContactUsScene> list = contactUsSceneService.list();
        List<String> numList = list.stream().map(ContactUsScene::getNum).collect(Collectors.toList());
        if(numList.isEmpty()){
            return new ArrayList<>();
        }
        List<SceneVo> sceneVos = scenePlusService.getVoByNumList(numList);
        for (SceneVo sceneVo : sceneVos) {
            if(SceneSourceUtil.isLaser(sceneVo.getSceneSource())){
                if(ucenterConfig.getActive().contains("prod")){
                    sceneVo.setWebSite(ucenterConfig.getBasePath() +"/index.html?m="+sceneVo.getNum());
                }else {
                    sceneVo.setWebSite(ucenterConfig.getBasePath() +"/uat/index.html?m="+sceneVo.getNum());
                }
                sceneVo.setSceneName(sceneVo.getLaserTitle());
            }
        }
        return sceneVos;
    }
}
