package com.mvc.controller.external;

import com.mvc.model.CustomUserModel;
import com.mvc.model.ResPageModel;
import com.mvc.model.ResultGeekerModel;
import com.mvc.model.external.AuthModel;
import com.mvc.model.external.IdentResultModel;
import com.mvc.service.external.ExternalRequestService;
import com.mvc.service.external.RefreshTokenService;
import com.mvc.service.taizhang.CustomUserService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.JwtUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 外部请求控制器
 * 向第三方提供数据
 */
@RequestMapping("/api/v1")
@Controller
public class ExternalRequestController {
    private static Logger log = LoggerFactory.getLogger(ExternalRequestController.class);

    @Resource
    private ExternalRequestService externalRequestService;

    @Resource
    private CustomUserService customUserService;

    @ApiOperation("获取Token")
    @RequestMapping(value = "/auth/token", method = RequestMethod.GET)
    @ResponseBody
    public ResultGeekerModel getToken(String accessKey) {
        log.info("接口调用:{}_accessKey:{}", "getToken", accessKey);

        ResultGeekerModel resultModel;
        try {
            //临时将userId作为accessKey,理论上现在不存在安全问题,userId并不是表主键,并且是GUID
            CustomUserModel userModel = customUserService.findCustomUserModelByUserId(accessKey);
            String errInfo = "";
            if (userModel == null) {
                errInfo = "accessKey invalid";
            }
            if (StringUtils.isNotEmpty(errInfo)) {
                resultModel = new ResultGeekerModel(errInfo);
                resultModel.setData("");
            } else {
                Map<String, Object> info = new HashMap<>();
                info.put("username", userModel.getLoginId());
                info.put("pwd", userModel.getLoginPwd());
                AuthModel authModel = JwtUtil.signAuthModel(userModel.getUserId(), info);

                resultModel = new ResultGeekerModel(authModel);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ResultGeekerModel(e.getMessage());
        }
        return resultModel;
    }

    @ApiOperation("根据刷新Token获取新的accToken")
    @RequestMapping(value = "/auth/token/refresh", method = RequestMethod.GET)
    @ResponseBody
    public ResultGeekerModel refreshToken(String refreshToken) {
        ResultGeekerModel resultModel;
        try {
            if (RefreshTokenService.checkSign(refreshToken)) {
                String userId = RefreshTokenService.getUserId(refreshToken);
                Map<String, Object> info = RefreshTokenService.getInfo(refreshToken);

                AuthModel authModel = JwtUtil.signAuthModel(userId, info);
                resultModel = new ResultGeekerModel(authModel);
                //使用刷新Token重新获取accToken后,使当前刷新token及其accToken直接登记过期
                JwtUtil.setTokenExpired(refreshToken);
            } else {
                resultModel = new ResultGeekerModel("refreshToken invalid");
                resultModel.setData("");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ResultGeekerModel(e.getMessage());
        }
        return resultModel;
    }

    @ApiOperation("根据遥测站编码获取识别记录")
    @RequestMapping(value = "/records", method = RequestMethod.POST)
    @ResponseBody
    public ResultGeekerModel getIdentRecord(@RequestParam("stationCode") String stationCode,
                                            @RequestParam(required = false, defaultValue = "") String startTime,
                                            @RequestParam(required = false, defaultValue = "") String endTime) {
        ResultGeekerModel resultModel;
        try {
            if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
                Date dtSt = DateUtil.parseTimeStr(startTime, DateUtil.PATTERN_DATA_NORMAL);
                Date dtEnd = DateUtil.parseTimeStr(endTime, DateUtil.PATTERN_DATA_NORMAL);
                if (dtSt == null || dtEnd == null) {
                    resultModel = new ResultGeekerModel("date format errror");
                } else {
                    //转换日期是为了适应TAiread的查询条件
                    startTime = DateUtil.formateDate(dtSt, DateUtil.PATTERN_DATA_UNSIGNED);
                    endTime = DateUtil.formateDate(dtEnd, DateUtil.PATTERN_DATA_UNSIGNED);
                    List<IdentResultModel> res = externalRequestService.getIdentRecords(stationCode, startTime, endTime);
                    resultModel = new ResultGeekerModel(res);
                }
            } else {
                //将返回结果统一为数组
                IdentResultModel model = externalRequestService.getIdentRecord(stationCode);
                List<IdentResultModel> res = new ArrayList<>();
                if (model != null) {
                    res.add(model);
                }
                resultModel = new ResultGeekerModel(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ResultGeekerModel(e.getMessage());
        }
        resultModel.setData(resultModel.getData() == null ? "" : resultModel.getData());//未查询到数据,data中设置为空串
        return resultModel;
    }

    @ApiOperation("获取当前用户下所有站点的最新数据")
    @RequestMapping(value = "/records/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultGeekerModel getIdentRecord(int pageNum,int pageSize) {
        ResultGeekerModel resultModel;
        try {
            ResPageModel res = externalRequestService.getIdentRecords(pageNum,pageSize);
            resultModel = new ResultGeekerModel(res);
        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ResultGeekerModel(e.getMessage());
        }
        resultModel.setData(resultModel.getData() == null ? "" : resultModel.getData());//未查询到数据,data中设置为空串
        return resultModel;
    }

    /* 在接口上直接传输userName和userPwd不太安全
    @ApiOperation("获取Token")
    @RequestMapping(value = "/auth/token", method = RequestMethod.GET)
    @ResponseBody
    public ResultGeekerModel getToken(String userName, String userPwd) {
        ResultGeekerModel resultModel;
        try {
            CustomUserModel userModel = customUserService.logincustomUser(userName);
            String errInfo = "";
            if (userModel == null) {
                errInfo = "用户不存在";
            } else if (!userModel.getLoginPwd().equals(userPwd)) {
                errInfo = "密码错误";
            }
            if (StringUtils.isNotEmpty(errInfo)) {
                resultModel = new ResultGeekerModel(errInfo);
                resultModel.setData("");
            } else {
                Map<String, Object> info = new HashMap<>();
                info.put("username", userModel.getLoginId());
                info.put("pwd", userModel.getLoginPwd());
                AuthModel authModel = JwtUtil.signAuthModel(userModel.getUserId(), info);

                resultModel = new ResultGeekerModel(authModel);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ResultGeekerModel(e.getMessage());
        }
        return resultModel;
    }*/
}
