package yangtz.cs.liu.campus.controller.common;

import com.alibaba.druid.support.http.util.IPAddress;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.utils.UploadToServer;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.weather.Address;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.core.utils.WeatherUtil.*;
import static com.ruoyi.common.utils.ip.IpUtils.getHostIp;
import static com.ruoyi.common.utils.ip.IpUtils.getIpAddr;


/**
 * @author lyric
 * @date 2022/10/21 16:32
 */
@RestController
@RequestMapping("/school/common")
public class SchoolCommonController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISchoolClassService schoolClassService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    ISchoolTeacherService teacherService;

    private Logger log = LoggerFactory.getLogger(SchoolCommonController.class);

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    //127.0.0.1
    public static final String LOCALHOST = "127.0.0.1";

    @Autowired
    private ServerConfig serverConfig;

    @Value("${ruoyi.serverAddress}")
    private String serverAddress;

    @Value("${server.port}")
    private String port;

    /**
     * @author lyric
     * @date 2022/10/21 16:32
     * <p>
     * 根据 roleKey查询用户集合
     */
    @GetMapping("/getRoleUserList/{roleKey}")
    public TableDataInfo getUserListByRoleKey(@PathVariable("roleKey") String roleKey, SysUser user) {
        startPage();
        List<SysUser> userList = userService.getUserListByRoleKey(user, roleKey);
        return getDataTable(userList);
    }

    /**
     * @author lyric
     * @date 2022/10/21 18:23
     * 返回班级集合
     */
    @GetMapping("/getGradeList")
    public AjaxResult getGradeList() {
        LambdaQueryWrapper<SchoolClass> lwq = new LambdaQueryWrapper<>();
        lwq.select(SchoolClass::getId, SchoolClass::getSchoolYear,
                SchoolClass::getClassType, SchoolClass::getGradeValue, SchoolClass::getGradeName,
                SchoolClass::getClassValue, SchoolClass::getClassName);
        List<SchoolClass> schoolClassList = schoolClassService.list(lwq);
        try {
            Map<Integer, Map<String, Map<Integer, Map<Integer, List<SchoolClass>>>>> map = schoolClassList.stream().collect(Collectors.groupingBy(SchoolClass::getSchoolYear,
                    Collectors.groupingBy(SchoolClass::getClassType, Collectors.groupingBy(SchoolClass::getGradeValue,
                            Collectors.groupingBy(SchoolClass::getClassValue)))));
            return AjaxResult.success(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("返回班级集合错误");
        }
    }

    /**
     *  首页天气，获取实时城市天气
     */
    @GetMapping("/weather")
    public AjaxResult getCityWeather() {
        AjaxResult ajax = AjaxResult.success();
        //姓名，上次登录时间，星期几，2022/09/09
        SysUser user =  userService.selectUserById(getUserId());
        ajax.put("user",user);
        //星期几，2022/09/09
        ajax.put("weekday",DateUtils.getWeekday());
        ajax.put("date",DateUtils.datePath());
        //获取客户端ip，目前跑本地的话，获取的ip为127.0.0.1
        String ip = getIpAddr(ServletUtils.getRequest());
        Address address = city(ip);
        //省
        ajax.put("pro",address.getPro());
        //类似香港之类的只能获取到pro,city中获取不到，所以需要进行判断
        if(address.getCity().equals("")){
            ajax.put("weather",getProWeather(address.getPro()));
            return ajax;
        }
        ajax.put("city",address.getCity());
        ajax.put("weather",getRealWeather(address.getCity()));
        return ajax;


    }

    /**
     * 根据ip获取当前所在地
     * */
    private static Address city(String ip){
        Address address = new Address();
        //若出错，则默认北京市
        address.setCity("北京市");
        if(ip.equals(LOCALHOST)){
            return address;
        }
        //判断是否是内网地址,默认北京市
        if (IpUtils.internalIp(ip))
        {
            return address;
        }
        try
        {
            String rspStr = HttpUtils.sendGet(IP_URL,"ip=" + ip + "&json=true", Constants.GBK);
            if (StringUtils.isEmpty(rspStr))
            {
              return address;
            }
            JSONObject obj = JSON.parseObject(rspStr);
            address.setIp(obj.getString("ip"));
            address.setPro(obj.getString("pro"));
            address.setProCode(obj.getString("proCode"));
            address.setCity(obj.getString("city"));
            address.setCityCode(obj.getString("cityCode"));
            address.setRegion(obj.getString("region"));
            address.setRegionCode(obj.getString("regionCode"));
            address.setAddr(obj.getString("addr"));
            address.setRegionNames(obj.getString("regionNames"));
            address.setErr(obj.getString("err"));
            return address;
        }
        catch (Exception e)
        {
            return address;
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("originalFilename", file.getOriginalFilename());
            Map map = UploadToServer.upload(serverAddress,port,file);
            ajax.put("fileName",map.get("fileName"));
            ajax.put("newFileName",map.get("newFileName"));
            ajax.put("type",file.getContentType());
            ajax.put("url",serverAddress+":"+port+map.get("fileName"));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * @param file
     * @return AjaxResult
     * <p>
     * 用户头像
     * @author lyric
     * @date 2022/11/5 19:26
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("originalFilename", file.getOriginalFilename());
            Map map = UploadToServer.uploadAvatar(serverAddress,file);
            ajax.put("url", serverAddress+":"+port+map.get("url"));
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * @param file
     * @return AjaxResult
     * <p>
     * 用户签名
     * @author lyric
     * @date 2022/11/5 19:26
     */
    @PostMapping("/sign")
    public AjaxResult sign(MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("originalFilename", file.getOriginalFilename());
            Map map = UploadToServer.uploadSign(serverAddress,port,file);
            ajax.put("url", serverAddress+":"+port+map.get("url"));
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 头像上传到数据库
     */
    @PostMapping("/upAvatar")
    public AjaxResult upAvatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            Map map = UploadToServer.uploadAvatar(serverAddress,file);
            String avatar = serverAddress+":"+port+map.get("url");
            if (userService.updateAvatar(loginUser.getUserId(), avatar))
            {
                //更新教师表的图片
                teacherService.updatePic(loginUser.getUserId(), avatar);
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 签名上传到数据库
     */
    @PostMapping("/upSign")
    public AjaxResult upSign(@RequestParam("signfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            Map map = UploadToServer.uploadSign(serverAddress,port,file);
            String sign = serverAddress+":"+port+map.get("url");
            if (userService.updateUserSign(loginUser.getUserId(), sign))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", sign);
                // 更新缓存用户头像
                loginUser.getUser().setSign(sign);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

}
