package com.huimv.admin.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.admin.common.utils.*;
import com.huimv.admin.entity.SysAccountMultilevel;
import com.huimv.admin.entity.dto.WeCahtVo;
import com.huimv.admin.service.ILoginService;
import com.huimv.admin.service.ISysAccountMultilevelService;
import com.huimv.admin.session.AccessToken;
import com.huimv.admin.common.exception.ExceptionEnum;
import com.huimv.admin.common.exception.MiException;
import com.huimv.admin.common.token.TokenSign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/admin/my")
@CrossOrigin
public class LoginController {

    @Autowired
    ILoginService iLoginService;
    @Autowired
    private ISysAccountMultilevelService accountMultilevelService;
    @Autowired
    private UploadImage uploadImage;

    @RequestMapping("/test")
    public String logout() {
        return "线上服务器1";
    }

    @RequestMapping("/logout")
    public Result logout(@RequestParam(name = "accountName", required = true) String accountName, @RequestParam(name = "password", required = true) String password) {
        return iLoginService.logout();
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send")
    public void createImg(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置响应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            VerifyUtil randomValidateCode = new VerifyUtil();
            //输出验证码图片
            String code = randomValidateCode.getRandcode(request, response);
            System.out.println(code);
            //将生成的随机验证码存放到redis中
            String remoteHost = request.getRemoteHost();
            redisTemplate.opsForValue().set(remoteHost, code, 300, TimeUnit.SECONDS);
        } catch (Exception e) {
            System.out.println("获取验证码异常:" + e);
            throw new MiException(ExceptionEnum.VERIFCATION_FAID);
        }
    }

    //登录-多牧场
    @PostMapping(value = "/loginMultilevel")
    public Result loginMultilevel(HttpServletRequest req, @RequestBody Map<String, String> map) {


        String accountName = map.get("accountName");
        String password = map.get("password");

        String remoteHost = req.getRemoteHost();

        // 未对密码加密
        Result result = iLoginService.loginMultilevel(accountName, password);
        if (result.getCode() == 10000) {

            SysAccountMultilevel accountEntity = (SysAccountMultilevel) result.getData();
            Integer id = accountEntity.getId();
            IpTools.getRemoteHost(req);
            AccessToken accessToken = new AccessToken();
            accessToken.setCreated(new Date());
            accessToken.setAccountName(accountName);
            accessToken.setFarmId(accountEntity.getFarmIds());
            String token = TokenSign.sign(accountName, id, accountEntity.getFarmIds(), null, null);
            accessToken.setToken(token);

            accessToken.setId(id);
            accessToken.setLoginIp(remoteHost);
            accessToken.setType(accountEntity.getType());
            Integer lastFarmId = accountEntity.getLastFarmId();
            if (ObjectUtil.isEmpty(lastFarmId)) {
                lastFarmId = Integer.parseInt(accountEntity.getFarmIds().split(",")[0]);
            }
            accessToken.setLastFarmId(lastFarmId);
            accessToken.setUserName(accountEntity.getUserName());

            return new Result(ResultCode.SUCCESS, accessToken);
        }
        return result;
    }

    //测试-token
    @PostMapping(value = "/getToken")
    public String getToken(HttpServletRequest req) {
        String token = TokenSign.sign("superadmin", 1, null, null, null);
        return token;
    }

    @RequestMapping("/logoutClient")
    public Result logoutClient(HttpServletRequest req, @RequestBody Map<String, String> map) {
        String accountName = map.get("accountName");
        String password = map.get("password");
        String remoteHost = req.getRemoteHost();
        Result result = iLoginService.loginMultilevel(accountName, password);
        if (result.getCode() == 10000) {
            SysAccountMultilevel data = (SysAccountMultilevel) result.getData();
            AccessToken accessToken = new AccessToken();
            accessToken.setSysAccountMultilevel(data);
            accessToken.setAccountName(accountName);
            accessToken.setUserName(data.getUserName());
            accessToken.setFarmId(data.getFarmIds());
            accessToken.setType(data.getType());
            accessToken.setId(data.getId());
            String token = TokenSign.sign(data.getUserName(), data.getId(), data.getFarmIds(), data.getWorkLocationType(), data.getType());
            accessToken.setToken(token);
            Integer lastFarmId = data.getLastFarmId();
            if (ObjectUtil.isEmpty(lastFarmId)) {
                lastFarmId = Integer.parseInt(data.getFarmIds().split(",")[0]);
            }
            accessToken.setLastFarmId(lastFarmId);
            accessToken.setLoginIp(remoteHost);
            return new Result(ResultCode.SUCCESS, accessToken);
        } else {
            return result;
        }
    }

    @RequestMapping("/logoutOne")
    public Result logoutOne(HttpServletRequest req, @RequestBody Map<String, String> map) {
        String accountName = map.get("accountName");
        String password = map.get("password");
        Result result = iLoginService.loginMultilevel(accountName, password);
        if (result.getCode() == 10000) {
            SysAccountMultilevel data = (SysAccountMultilevel) result.getData();
            AccessToken accessToken = new AccessToken();
            String token = TokenSign.sign(data.getUserName(), data.getId(), data.getFarmIds(), data.getWorkLocationType(), data.getType());
            accessToken.setToken(token);
            return new Result(ResultCode.SUCCESS, token);
        } else {
            return result;
        }
    }

/*    @RequestMapping("/logoutWeChat")
    public Result logoutWeChat(HttpServletRequest req, @RequestBody Map<String, String> map) {
        String remark = map.get("remark");
        QueryWrapper<SysAccountMultilevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", remark);
        SysAccountMultilevel one = accountMultilevelService.getOne(queryWrapper);
        AccessToken accessToken = new AccessToken();
        if (ObjectUtil.isEmpty(one)) {
            SysAccountMultilevel accountMultilevel = new SysAccountMultilevel();
            accountMultilevel.setAccount(remark);
            accountMultilevel.setFarmIds("25");
            accountMultilevel.setColor("");
            accountMultilevel.setMode(true);
            accountMultilevel.setUserName("访客");
            accountMultilevel.setType(7);
            accountMultilevelService.save(accountMultilevel);
            QueryWrapper<SysAccountMultilevel> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("account", remark);
            SysAccountMultilevel one1 = accountMultilevelService.getOne(queryWrapper1);

            accessToken.setAccountName(remark);
            accessToken.setUserName("访客");
            accessToken.setFarmId("25");
            accessToken.setType(7);
            accessToken.setId(one1.getId());
            String token = TokenSign.sign(remark, one1.getId(), one1.getFarmIds(), null,7);
            accessToken.setToken(token);
        } else {
            accessToken.setAccountName(one.getUserName());
            accessToken.setUserName("访客");
            accessToken.setFarmId("25");
            accessToken.setType(7);
            accessToken.setId(one.getId());
            String token = TokenSign.sign(remark, one.getId(), one.getFarmIds(), one.getWorkLocationId(),7);
            accessToken.setToken(token);
        }
        return new Result(ResultCode.SUCCESS,accessToken);
  *      String accountName = map.get("accountName");
        String password = map.get("password");
        String remoteHost = req.getRemoteHost();
        Result result = iLoginService.loginMultilevel(accountName, password);
        if (result.getCode() == 10000) {
            SysAccountMultilevel data = (SysAccountMultilevel) result.getData();
            AccessToken accessToken = new AccessToken();
            accessToken.setAccountName(accountName);
            accessToken.setUserName(data.getUserName());
            accessToken.setFarmId(data.getFarmIds());
            accessToken.setType(data.getType());
            accessToken.setId(data.getId());
            String token = TokenSign.sign(accountName,data.getId(),data.getFarmIds(),data.getWorkLocationId());
            accessToken.setToken(token);
            Integer lastFarmId = data.getLastFarmId();
            if (ObjectUtil.isEmpty(lastFarmId)){
                lastFarmId = Integer.parseInt(data.getFarmIds().split(",")[0]);
            }
            accessToken.setLastFarmId(lastFarmId);
            accessToken.setLoginIp(remoteHost);
            return new Result(ResultCode.SUCCESS,accessToken);
        } else {
            return result;
        }*//*
    }*/

    @GetMapping("/logoutWeChat")
    public Result logoutWeChat(HttpServletRequest req, @RequestParam String jsCode) {
        String remoteHost = req.getRemoteHost();
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("appid", "wxa28e45fe5cb10ff1");
        paramsMap.put("secret", "c16e584ec6e69fd35edd98ec21ec5e94");
        paramsMap.put("js_code", jsCode);
        paramsMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", paramsMap);
        System.out.println(result);
        JSONObject jsonObject = JSON.parseObject(result);
        System.out.println(jsonObject);
        String openid = (String) jsonObject.get("openid");
        String sessionKey = (String) jsonObject.get("session_key");
        System.out.println("拿到了openid" + openid);
        System.out.println("拿到了sessionKey" + sessionKey);
        QueryWrapper<SysAccountMultilevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_id", openid);
        SysAccountMultilevel data = accountMultilevelService.getOne(queryWrapper);
        WeCahtVo weCahtVo = new WeCahtVo();
        weCahtVo.setOpenId(openid);
        weCahtVo.setSessionKey(sessionKey);
        if (ObjectUtil.isEmpty(data)) {
            return new Result(ResultCode.FAIL, weCahtVo);
        } else {
            AccessToken accessToken = new AccessToken();
            accessToken.setSysAccountMultilevel(data);
            accessToken.setAccountName(data.getAccount());
            accessToken.setUserName(data.getUserName());
            accessToken.setFarmId(data.getFarmIds());
            accessToken.setType(data.getType());
            accessToken.setId(data.getId());
            String token = TokenSign.sign(data.getUserName(), data.getId(), data.getFarmIds(), data.getWorkLocationType(), 7);
            accessToken.setToken(token);
            Integer lastFarmId = data.getLastFarmId();
            if (ObjectUtil.isEmpty(lastFarmId)) {
                lastFarmId = Integer.parseInt(data.getFarmIds().split(",")[0]);
            }
            accessToken.setLastFarmId(lastFarmId);
            accessToken.setLoginIp(remoteHost);
            return new Result(ResultCode.SUCCESS, accessToken);
        }
    }

    @PostMapping("/register")
    public Result addAdmission(HttpServletRequest req, @RequestParam("userName") String userName,
                               @RequestParam("phone") String phone,
                               @RequestParam("workName") String workName,
                               @RequestParam("papersType") String papersType,
                               @RequestParam("papersCode") String papersCode,
                               @RequestParam(value = "imgUrl", required = false) MultipartFile imgUrl,
                               @RequestParam("openId") String openId) throws IOException {
        String remoteHost = req.getRemoteHost();
        QueryWrapper<SysAccountMultilevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone).or().eq("papers_code", papersCode);
        if (ObjectUtil.isNotEmpty(accountMultilevelService.getOne(queryWrapper))) {
            return new Result(10001, "该手机号或身份证号已被使用！", false);
        }
        if (!PhoneNumberValidator.isValidPhoneNumber(phone)) {
            return new Result(10001, "手机号格式错误！", false);
        }
        if (papersType.equals("0")) {
            if (!IDCardValidator.isValidIDCard(papersCode)) {
                return new Result(10001, "身份证号格式错误!", false);
            }
        }
        SysAccountMultilevel sysAccountMultilevel = new SysAccountMultilevel();
        sysAccountMultilevel.setUserName(userName);
        sysAccountMultilevel.setPapersCode(papersCode);
        sysAccountMultilevel.setPhone(phone);
        sysAccountMultilevel.setAccount(phone);
        sysAccountMultilevel.setPid(0);
        sysAccountMultilevel.setPids("0");
        sysAccountMultilevel.setPassword("123456");
        sysAccountMultilevel.setWorkName(workName);
        sysAccountMultilevel.setAccountStatus(1);
        sysAccountMultilevel.setFarmIds("25");
        sysAccountMultilevel.setLastFarmId(25);
        sysAccountMultilevel.setPapersType(papersType);
        sysAccountMultilevel.setWechatId(openId);
        sysAccountMultilevel.setType(7);
        String imageCom = uploadImage.getImageCom(imgUrl);
        if (imageCom.equals("上传失败")) {
            return new Result(10001, "图片上传失败！", false);
        }
        sysAccountMultilevel.setImgUrl(imageCom);
        accountMultilevelService.save(sysAccountMultilevel);
        AccessToken accessToken = new AccessToken();
        accessToken.setSysAccountMultilevel(sysAccountMultilevel);
        accessToken.setAccountName(sysAccountMultilevel.getAccount());
        accessToken.setUserName(sysAccountMultilevel.getUserName());
        accessToken.setFarmId(sysAccountMultilevel.getFarmIds());
        accessToken.setType(sysAccountMultilevel.getType());
        accessToken.setId(sysAccountMultilevel.getId());
        String token = TokenSign.sign(sysAccountMultilevel.getUserName(), sysAccountMultilevel.getId(), sysAccountMultilevel.getFarmIds(), sysAccountMultilevel.getWorkLocationType(), sysAccountMultilevel.getType());
        accessToken.setToken(token);
        Integer lastFarmId = sysAccountMultilevel.getLastFarmId();
        if (ObjectUtil.isEmpty(lastFarmId)) {
            lastFarmId = Integer.parseInt(sysAccountMultilevel.getFarmIds().split(",")[0]);
        }
        accessToken.setLastFarmId(lastFarmId);
        accessToken.setLoginIp(remoteHost);
        return new Result(ResultCode.SUCCESS, accessToken);
    }
}
