package com.fufan.mtsaas.aliyun;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.fufan.mtsaas.aliyun.dto.SendVerificationCodeRequest;
import com.fufan.mtsaas.aliyun.dto.VerifyVerificationCodeRequest;
import com.fufan.mtsaas.aliyun.enums.VerificationCodeResultEnum;
import com.fufan.mtsaas.aliyun.model.SendVerificationCode;
import com.fufan.mtsaas.aliyun.model.VerifyVerificationCode;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.modules.common.bo.request.DataRequestT;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.hrsys.bo.request.LoginRequest;
import com.fufan.mtsaas.modules.sysmgr.hrsys.service.HRLoginUserSvc;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDetailQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupHSvc;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.model.SYmenu;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYuserDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuser;
import com.fufan.mtsaas.util.ParamUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Api(tags = "MTSaas：短信验证管理", description = "短信验证接口")
@Slf4j
@Validated
@RestController
@RequestMapping("/SYS/SMS")
public class SmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private HRLoginUserSvc loginUserSvc;
    @Autowired
    private SYuserDao sYuserDao;
    @Autowired
    private SYmenuDao sYmenuDao;
    @Autowired
    private SYgroupHSvc sYgroupHSvc;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
//
//    @ApiOperation("发送短信")
//    @PostMapping
//    public void send(@Validated @RequestBody Sms sms) {
//        smsService.send(sms);
//    }

//    @ApiOperation("发送短信验证码")
//    @PostMapping("/sendVerificationCode")
//    public ResultStandard sendVerificationCode(@RequestBody @ApiIgnore DataRequestT<SendVerificationCodeRequest> data, SendVerificationCodeRequest sendVerificationCodeRequest) {
//        ResultStandard resultStandard = new ResultStandard();
//        SendVerificationCode sendVerificationCode = new SendVerificationCode();
//        sendVerificationCode.setPhoneNumber(data.getData().getParam().getPhoneNumber());
//        String result = smsService.sendVerificationCode(sendVerificationCode);
//        if(StringUtils.isEmpty(result)){
//            resultStandard.setResData(null);
//            resultStandard.setResMsg("发送成功");
//            resultStandard.setResStatus("S0000");
//        }else {
//            resultStandard.setResData(null);
//            resultStandard.setResMsg(result);
//            resultStandard.setResStatus("S0000");
//        }
//        return resultStandard;
//    }
//
//    @ApiOperation(value = "验证短信验证码", notes = "返回结果为int, 0:正确, 1:不正确, 2:不存在")
//    @PostMapping("/verifyCode")
//    public ResultStandard verifyVerificationCode(@RequestBody @ApiIgnore DataRequestT<VerifyVerificationCodeRequest> data, VerifyVerificationCodeRequest verifyVerificationCodeRequest, @ApiIgnore HttpSession session) {
//        ResultStandard result = new ResultStandard();
//        int verify = 2;
//        try{
//            VerifyVerificationCode verifyVerificationCode = new VerifyVerificationCode();
//            verifyVerificationCode.setPhoneNumber(data.getData().getParam().getPhoneNumber());
//            verifyVerificationCode.setCode(data.getData().getParam().getCode());
//            verify = smsService.verifyVerificationCode(verifyVerificationCode).getResult();
//            LoginRequest loginRequest = new LoginRequest();
//            loginRequest.setUserID(data.getData().getParam().getPhoneNumber());
////            loginRequest.setPassword(data.getData().getParam().getCode());
//            if(verify == 0){
////                result = loginUserSvc.loginCheckJs(verifyVerificationCode.getPhoneNumber(), session);
//                Result resultCheck = loginUserSvc.loginCheck(loginRequest, session);
//                //TODO - 返回权限
//                result.setResData((JSONObject) JSonUtil.textToJson(JSonUtil.toJSONString(resultCheck)));
//            }else {
//                result.setResStatus("E0000");
//                result.setResMsg("验证码错误");
//            }
//        }catch (Exception e){
//            log.error("数据出错" + JSON.toJSONString(verifyVerificationCodeRequest));
//            log.error("数据出错：",e);
//            result.setResStatus("E1002");
//            result.setResMsg("请求参数不合法！");
//        }
//        return result;
//    }
@ApiOperation("发送短信验证码")
@PostMapping("/sendVerificationCode")
public Result sendVerificationCode(@RequestBody @ApiIgnore @Valid DataRequestT<SendVerificationCodeRequest> data, SendVerificationCodeRequest sendVerificationCodeRequest) {
    Result resultStandard = new Result();
    SendVerificationCode sendVerificationCode = new SendVerificationCode();
    sendVerificationCode.setPhoneNumber(data.getData().getParam().getPhoneNumber());
    String result = smsService.sendVerificationCode(sendVerificationCode);
    if(StringUtils.isEmpty(result)){
        resultStandard.setResData(null);
        resultStandard.setResMsg("发送成功");
        resultStandard.setResStatus("S0000");
    }else {
        resultStandard.setResData(null);
        resultStandard.setResMsg("发送成功");
        resultStandard.setResStatus("S0000");
    }
    return resultStandard;
}

    @ApiOperation(value = "验证短信验证码", notes = "返回结果为int, 0:正确, 1:不正确, 2:不存在，5：连续5次失败")
    @PostMapping("/verifyCode")
    public Result verifyVerificationCode(@RequestBody @ApiIgnore DataRequestT<VerifyVerificationCodeRequest> data, VerifyVerificationCodeRequest verifyVerificationCodeRequest, @ApiIgnore HttpSession session) {
        Result result = new Result();
        int verify = 2;
        try{
            VerifyVerificationCode verifyVerificationCode = new VerifyVerificationCode();
            verifyVerificationCode.setPhoneNumber(data.getData().getParam().getPhoneNumber());
            verifyVerificationCode.setCode(data.getData().getParam().getCode());
            verify = smsService.verifyVerificationCode(verifyVerificationCode).getResult();
            LoginRequest loginRequest = new LoginRequest();
            loginRequest.setUserID(data.getData().getParam().getPhoneNumber());
//            loginRequest.setPassword(data.getData().getParam().getCode());
            if(verify == 0){
//                result = loginUserSvc.loginCheckJs(verifyVerificationCode.getPhoneNumber(), session);
                Result resultCheck = loginUserSvc.loginCheck(loginRequest, session);
                //TODO - 返回权限
                result =  resultCheck;
            }else {
                result.setResStatus("E0000");
                result.setResMsg("验证码错误或其他异常，请检查后再试");
                if(verify == VerificationCodeResultEnum.MAX_TRY.getResult()){
                    result.setResMsg("连续5次失败，该号码被锁住30分钟，请稍后再试");
                }
            }
        }catch (Exception e){
            log.error("数据出错" + JSON.toJSONString(verifyVerificationCodeRequest));
            log.error("数据出错：",e);
            result.setResStatus("E1002");
            result.setResMsg("请求参数不合法！");
        }
        return result;
    }
    @ApiOperation(value = "获取用户登录测试数据接口（包含菜单与按钮）", httpMethod = "POST", produces = "application/json")
    @PostMapping("/getTestUserData")
    public Result getTestUserData() {
        Result result = new Result();

        RequestPojo requestPojo = ParamUtil.doChange();
        HashMap<String, String> hsData = new HashMap();
        hsData.put("CompanyID", requestPojo.getCustId());
        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +requestPojo.getStaffId());
        hsData.put("id", userRedisId);
        Page page = new Page<>();
        List<SYuser> sYuser = sYuserDao.selectList(page, hsData);
        if(sYuser.size() == 0){
            result.setResStatus(ResStatus.STATUS_USER_IS_EMPTY);
            result.setResMsg(ResStatus.STATUS_USER_IS_EMPTY_MSG);
            return result;
        }

        if(StringUtils.isEmpty(sYuser.get(0).getUserGroupID())){
            result.setResStatus(ResStatus.STATUS_ROLE_IS_EMPTY);
            result.setResMsg(ResStatus.STATUS_ROLE_IS_EMPTY_MSG);
            return result;
        }

        try{
            JSONObject   data = new JSONObject();
            GroupDetailQueryRequest groupDetailQueryRequest = new GroupDetailQueryRequest();
            groupDetailQueryRequest.setId(Long.valueOf(sYuser.get(0).getUserGroupID()));
            List dataList = sYgroupHSvc.doQueryDetail(groupDetailQueryRequest,requestPojo).getResData().getRecords();
            if(dataList != null && dataList.size() > 0){
                data  =  JSONObject.parseObject(JSONObject.toJSONString(dataList.get(0)));
                String roles = "";
                roles = data.getJSONArray("roles").toJSONString().replace("[", "").replace("]", "");
//                for(int i = 0; i < data.getJSONArray("roles").size(); i++){
//                    roles = roles + "'" + data.getJSONArray("roles").get(i) + "',";
//                }
//                roles = roles.substring(0, roles.length() - 1);
                hsData = new HashMap();
                hsData.put("MenuCodeList", roles);
                page.setSize(0);
                List<SYmenu> sYmenuList = sYmenuDao.selectList(page, hsData);
                data.put("menuList", sYmenuList);
                data.put("username",sYuser.get(0).getName());
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(data);
            page.setRecords(jsonArray);
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            result.setResData(page);
        }catch (Exception e){
            log.error("数据出错：",e);
            result.setResStatus("E1002");
            result.setResMsg("请求参数不合法！");
        }
        return result;
    }
}
