package com.huimv.eartag2.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.eartag2.admin.entity.Sheet1;
import com.huimv.eartag2.admin.entity.SysAccountMultilevel;
import com.huimv.eartag2.admin.entity.SysOrg;
import com.huimv.eartag2.admin.entity.dto.SysAccountMultilevelDto;
import com.huimv.eartag2.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.eartag2.admin.mapper.SysOrgMapper;
import com.huimv.eartag2.admin.service.ILoginService;
import com.huimv.eartag2.admin.service.ISheet1Service;
import com.huimv.eartag2.admin.session.AccessToken;
import com.huimv.eartag2.common.common.exception.ExceptionEnum;
import com.huimv.eartag2.common.common.exception.MiException;
import com.huimv.eartag2.common.common.token.TokenSign;
import com.huimv.eartag2.common.common.utils.VerifyUtil;
import com.huimv.eartag2.common.utils.Result;
import com.huimv.eartag2.common.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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


    @Autowired
    ILoginService iLoginService;



    @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 code = map.get("code");

        String remoteHost = req.getRemoteHost();

//        String redisCode = redisTemplate.opsForValue().get(remoteHost);
//        if (redisCode == null) {
//            return  new Result(10005,"验证码过期,点击刷新",false);
//        }
//        if (!redisCode.equals(code.toUpperCase())) {
//            return  new Result(10006,"验证码错误,登录失败",false);
//        }
        // 未对密码加密
        Result result = iLoginService.loginMultilevel(accountName, password);
        if(result.getCode() == 10000){

            SysAccountMultilevel accountEntity = (SysAccountMultilevel) result.getData();
            Integer id = accountEntity.getId();

            AccessToken accessToken = new AccessToken();
            accessToken.setCreated(new Date());
            accessToken.setAccountName(accountName);
            accessToken.setCode(result.getCode());
            accessToken.setMessage(result.getMessage());
            accessToken.setFarmId(accountEntity.getFarmIds());
            String token = TokenSign.sign(accountName,id,accountEntity.getFarmIds(),accountEntity.getOrgId()+"");
            accessToken.setToken(token);

            accessToken.setId(id);
            accessToken.setLoginIp(remoteHost);
            accessToken.setType(accountEntity.getType());
            return new Result(ResultCode.SUCCESS,accessToken);
        }
        return  result;
    }

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private SysAccountMultilevelMapper accountMultilevelMapper;


    //所有组织
    @GetMapping(value = "/getOrg")
    public Result getOrg(@RequestParam(name = "sort") Integer sort)  {
        List<SysOrg> list = sysOrgMapper.selectList(null);
        ArrayList<SysOrg> newList = new ArrayList<>();
        for (SysOrg sysOrg : list) {
            String pids = sysOrg.getPids();
            if (pids.split(",").length <= sort){
                newList.add(sysOrg);
            }
        }

        List<SysOrg>   collect = newList.stream()
                .filter(o -> o.getParentId() == 0)
                .peek(o -> o.setChildren(getChildrens(o, newList)))
                .collect(Collectors.toList());
        return new Result(ResultCode.SUCCESS,collect);
    }


    //注册牧场
    @Transactional
    @PostMapping(value = "/addFarm")
    public Result addFarm(@RequestBody SysAccountMultilevelDto sysAccountMultilevel )  {
        Long orgId = sysAccountMultilevel.getOrgId();
        SysOrg sysOrg = sysOrgMapper.selectById(orgId);

        SysOrg newSysOrg = new SysOrg();
        newSysOrg.setName(sysAccountMultilevel.getFarmName());
        newSysOrg.setPids(sysOrg.getPids()+","+sysOrg.getId());
        newSysOrg.setParentId(sysOrg.getId());
        newSysOrg.setAudit(1);
        newSysOrg.setApplyTime(new Date());

        sysOrgMapper.insert(newSysOrg);

        int account = accountMultilevelMapper.selectCount(new QueryWrapper<SysAccountMultilevel>().eq("account", sysAccountMultilevel.getAccount())).intValue();
        if (account > 0 ){
            return new Result(10001,"该账号已经存在，请重新创建",false);
        }

        sysAccountMultilevel.setPids(sysOrg.getPids()+","+newSysOrg.getId());
        sysAccountMultilevel.setOrgId(newSysOrg.getId());
        sysAccountMultilevel.setType(sysOrg.getPids().split(",").length);
        sysAccountMultilevel.setType(4);



        accountMultilevelMapper.insert(sysAccountMultilevel);


        return  new Result( 10000,"添加成功",true);
    }




    private List<SysOrg> getChildrens(SysOrg o, List<SysOrg> list) {

        return list.stream()
                .filter(m -> m.getParentId().equals( o.getId()))
                .peek(m -> m.setChildren(getChildrens(m, list)))
                .collect(Collectors.toList());
    }

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

    @Autowired
    ISheet1Service sheet1Service;


    //请删除
    @GetMapping("/test")
    public void test( ) {

        //省
      /*  List<Sheet1> list = sheet1Service.list(new QueryWrapper<Sheet1>().groupBy("name_prov"));
        for (Sheet1 sheet1 : list) {
            SysOrg sysOrg = new SysOrg();
            sysOrg.setParentId(0L);
            sysOrg.setPids("0");
            sysOrg.setName(sheet1.getNameProv());
            sysOrgMapper.insert(sysOrg);

        }*/
        //市级
       /* List<Sheet1> list = sheet1Service.list(new QueryWrapper<Sheet1>().groupBy("name_city"));
        for (Sheet1 sheet1 : list) {
            String nameCity = sheet1.getNameCity();
            SysOrg sysOrg = new SysOrg();
            sysOrg.setName(nameCity);


            SysOrg name = sysOrgMapper.selectOne(new QueryWrapper<SysOrg>().eq("name", sheet1.getNameProv()));


            sysOrg.setParentId(name.getId());
            sysOrg.setPids(name.getPids()+","+name.getId());

            sysOrgMapper.insert(sysOrg);

        }*/

        List<Sheet1> list = sheet1Service.list(new QueryWrapper<Sheet1>().groupBy("name_coun"));
        for (Sheet1 sheet1 : list) {
            String nameCity = sheet1.getNameCoun();
            SysOrg sysOrg = new SysOrg();
            sysOrg.setName(nameCity);


            List<SysOrg> name1 = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().eq("name", sheet1.getNameCity()));

      SysOrg name = name1.get(0);

            sysOrg.setParentId(name.getId());
            sysOrg.setPids(name.getPids()+","+name.getId());

            sysOrgMapper.insert(sysOrg);

        }
    }
}
