package com.cnooc.expert.controller.auth;

import com.alibaba.fastjson.JSON;
import com.cnooc.expert.auth.service.SysCaptchaService;
import com.cnooc.expert.common.constant.TokenConstants;
import com.cnooc.expert.common.response.ApiResult;
import com.cnooc.expert.auth.service.LoginService;
import com.cnooc.expert.common.utils.JwtUtils;
import com.cnooc.expert.common.utils.KafkaProducerUtil;
import com.cnooc.expert.controller.auth.model.request.VerifyRequest;
import com.cnooc.expert.controller.auth.model.response.SlideCaptchaVO;
import com.cnooc.expert.external.expert.model.response.ExpertInfoResp;
import com.cnooc.expert.system.entity.pojo.ZhuanJiaUser;
import com.cnooc.expert.system.entity.vo.LoginVO;
import com.cnooc.expert.system.entity.vo.SysCaptchaVO;
import com.cnooc.expert.system.entity.vo.VerifyCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/sys")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private SysCaptchaService sysCaptchaService;

//    测试代码，先注掉
//    @Autowired
//    private KafkaProducerUtil kafkaProducerUtil;
//
//    @Resource(name="redisCommonTemplate")
//    private RedisTemplate<String, Object> redisTemplate;
//
//    private ZhuanJiaUser convert2ZhuanjiaUser(ExpertInfoResp expertInfoResp){
//        if( expertInfoResp == null ){
//            return null;
//        }
//
//        ZhuanJiaUser zhuanJiaUser = new ZhuanJiaUser();
//        zhuanJiaUser.setZhuanJiaGuid(expertInfoResp.getZhuanJiaGuid());
//        zhuanJiaUser.setMobile(expertInfoResp.getMobile());
//        zhuanJiaUser.setShenFenZheng(expertInfoResp.getShenFenZheng());
//        zhuanJiaUser.setShiFouYiFaZhuanJia(expertInfoResp.getShiFouYiFaZhuanJia());
//        zhuanJiaUser.setZhuanJiaCode(expertInfoResp.getZhuanJiaCode());
//        zhuanJiaUser.setSuoShuBuMeng(expertInfoResp.getSuoShuBuMeng());
//        zhuanJiaUser.setZhuanJiaName(expertInfoResp.getZhuanJiaName());
//        zhuanJiaUser.setZhuanJiaShiXiangGuid(expertInfoResp.getZhuanJiaShiXiangGuid());
//        zhuanJiaUser.setZhuanJiaZhuangTai(expertInfoResp.getZhuanJiaZhuangTai());
//
//        return zhuanJiaUser;
//    }
//
//    /**
//     * 手机号验证码/身份证号密码 登录功能
//     * @return Result<String> 统一返回操作码及信息
//     */
//    @GetMapping("/test")
//    public ApiResult<String> test() {
//        // 校验loginType 不为空
//
//
//        ExpertInfoResp expertInfoResp = new ExpertInfoResp();
//        expertInfoResp.setZhuanJiaGuid("1234");
//
//        ZhuanJiaUser zhuanJiaUser = convert2ZhuanjiaUser(expertInfoResp);
//        zhuanJiaUser.setZhuanJiaZhuangTai((short)2);
//        zhuanJiaUser.setMobile("18611383771");
//        zhuanJiaUser.setZhuanJiaCode("ttt");
//        zhuanJiaUser.setZhuanJiaGuid("11111111111");
//        zhuanJiaUser.setZhuanJiaName("weisong");
//        zhuanJiaUser.setSuoShuBuMeng("技术部");
//
//
//        redisTemplate.opsForValue().set(TokenConstants.LOGIN_USER_KEY_ + zhuanJiaUser.getZhuanJiaGuid(), zhuanJiaUser, 48, TimeUnit.HOURS);
//
//        log.info("set complete:  "+TokenConstants.LOGIN_USER_KEY_ + zhuanJiaUser.getZhuanJiaGuid());
//
//        ZhuanJiaUser zhuanjiaUser1 = (ZhuanJiaUser)redisTemplate.opsForValue().get(TokenConstants.LOGIN_USER_KEY_ + zhuanJiaUser.getZhuanJiaGuid());
//
//        log.info("get complete:");
//
//        log.info(JSON.toJSONString(zhuanjiaUser1));
//
//
//        String token = JwtUtils.createToken("1234","ttttt");
//        System.out.println("token is: "+token);
//
//        kafkaProducerUtil.sendMessage("test-topic", zhuanjiaUser1);
//        return ApiResult.success();
//    }


    /**
     * 手机号验证码/身份证号密码 登录功能
     * @param loginVO 登录表单
     * @return Result<String> 统一返回操作码及信息
     */
    @PostMapping("/login")
    public ApiResult<String> login(@Validated @RequestBody LoginVO loginVO) {
        // 校验loginType 不为空
        return ApiResult.successWithResult(loginService.login(loginVO));
    }
    /**
     * 获取验证码
     * @param vo 手机号等信息
     * @return Result<Integer> 统一返回操作结果及验证码
     */
//    @GetMapping("/sendCode/{phoneNumber}")
    @PostMapping("/sendSmsCode")
    public ApiResult<String> sendCode(@RequestBody LoginVO vo) {
        log.info("获取验证码的手机号: {}", vo.getPhoneNumber());
        return ApiResult.successWithResult(loginService.sendPhoneCode(vo));
    }
    @PostMapping("/verifyCode")
    public ApiResult<String> verifyCode(@RequestBody VerifyCodeVO codeVO) {
        return ApiResult.successWithResult(loginService.verifyCode(codeVO));
    }
    /**
     * 账号修改
     * @param loginVO
     * @return
     */
    @PostMapping("/changePass")
    public ApiResult<String> changePass(@RequestBody LoginVO loginVO) {
        return ApiResult.successWithResult(loginService.changePass(loginVO));
    }

    @GetMapping("/captcha")
    public ApiResult<Map<String, String>> captcha() {
        SysCaptchaVO captchaVO = sysCaptchaService.generate();
        // 5. 构建响应
        Map<String, String> response = new HashMap<>();
        response.put("captchaId", captchaVO.getKey());
        response.put("image", captchaVO.getImage());
        return ApiResult.successWithResult(response);
    }

    @GetMapping("/slideCaptcha")
    public ApiResult<Map<String, String>> slideCaptcha() {
        SlideCaptchaVO captchaVO = sysCaptchaService.generateSlide();
        // 5. 构建响应
        Map<String, String> response = new HashMap<>();
        response.put("backgroundImage", captchaVO.getBackgroundImage());
        response.put("slideImage", captchaVO.getSlideImage());
        response.put("token", captchaVO.getToken());
        response.put("startY",String.valueOf(captchaVO.getStartY()));
        return ApiResult.successWithResult(response);
    }

    @PostMapping("/verifySlideCaptcha")
    public ApiResult<Map<String, Object>> verifySlideCaptcha(
            @RequestBody VerifyRequest request) {
        Map<String, Object> result = new HashMap<>();
        boolean flag = sysCaptchaService.validateSlide(request.getToken(),request.getMoveX());
        String msg = "验证成功";
        if (!flag) {
            msg = "验证失败";
        }
        result.put("success", flag);
        result.put("message", msg);
        return ApiResult.successWithResult(result);
    }

    /**
     * 验证图片验证码
     */
    @PostMapping("/verifyCaptcha")
    public ResponseEntity<Map<String, Object>> verifyCaptchaNew(
            @RequestParam String captchaId,
            @RequestParam String inputCode) {
        Map<String, Object> result = new HashMap<>();
        boolean flag = sysCaptchaService.validate(captchaId, inputCode);
        String msg = "验证成功";
        if (!flag) {
            msg = "验证失败";
        }
        result.put("success", flag);
        result.put("message", msg);
        return ResponseEntity.ok(result);
    }
}
