package com.ygtx.web.controller.system;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.ygtx.common.constant.UserConstants;
import com.ygtx.common.core.domain.EncryptRequest;
import com.ygtx.common.core.domain.entity.SysRole;
import com.ygtx.common.utils.*;
import com.ygtx.system.domain.SysOperLog;
import com.ygtx.system.service.ISysPostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ygtx.common.annotation.Anonymous;
import com.ygtx.common.constant.Constants;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.core.domain.entity.SysMenu;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginBody;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.core.text.Convert;
import com.ygtx.framework.web.service.SysLoginService;
import com.ygtx.framework.web.service.SysPermissionService;
import com.ygtx.framework.web.service.TokenService;
import com.ygtx.system.service.ISysConfigService;
import com.ygtx.system.service.ISysMenuService;
import com.ygtx.system.service.ISysUserService;
import com.ygtx.system.service.ISysOperLogService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysOperLogService operLogService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();

        String isOpenAse = configService.selectConfigByKey("sys.ase.open");
        if("1".equals(isOpenAse)){
            loginBody.setPassword(AesDecryptUtil.decrypt(loginBody.getPassword()));
            loginBody.setUsername(AesDecryptUtil.decrypt(loginBody.getUsername()));
            loginBody.setCode(AesDecryptUtil.decrypt(loginBody.getCode()));
        }

        // 检查是否为初始密码
        String initPassword = configService.selectConfigByKey("sys.user.initPassword");
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        if (initPassword != null && initPasswordModify == 1) {
            // 验证用户名和密码是否正确
            try {
                if(!SecurityUtils.validatePassword(loginBody.getPassword())){
                    String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                            loginBody.getUuid());
                    ajax.put("isInitPassword", true);
                    ajax.put("message", "密码为8位及以上且必须包含大小写字母+特殊字符+数字相结合，请修改密码后再登录");
                    return ajax;
                }
                if(initPassword.equals(loginBody.getPassword())){
                    String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                            loginBody.getUuid());
                    // 如果能成功登录，说明是初始密码
                    ajax.put("isInitPassword", true);
                    ajax.put("message", "您使用的是初始密码，请修改密码后再登录");
                    return ajax;
                }
            } catch (Exception e) {
                // 用户名或密码错误
                ajax.put("isInitPassword", false);
            }
        }

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 初始密码修改
     */
    @Anonymous
    @PutMapping("/initPassword")
    public AjaxResult initPassword(@RequestBody LoginBody loginBody)
    {
        // 验证用户名和密码是否正确
        try {
            String isOpenAse = configService.selectConfigByKey("sys.ase.open");
            if("1".equals(isOpenAse)) {
                loginBody.setPassword(AesDecryptUtil.decrypt(loginBody.getPassword()));
                loginBody.setUsername(AesDecryptUtil.decrypt(loginBody.getUsername()));
                loginBody.setNewPassword(AesDecryptUtil.decrypt(loginBody.getNewPassword()));
                loginBody.setCode(AesDecryptUtil.decrypt(loginBody.getCode()));
            }

            log.info("账号："+loginBody.getUsername()
                    +",密码："+loginBody.getPassword()
                    +",新密码："+loginBody.getNewPassword());

            loginService.login(loginBody.getUsername(), loginBody.getPassword(), UserConstants.APP_CODE,
                    loginBody.getUuid());

            String initPassword = configService.selectConfigByKey("sys.user.initPassword");
            if (!SecurityUtils.validatePassword(loginBody.getNewPassword()))
            {
                return AjaxResult.error("密码为8位及以上且必须包含大小写字母+特殊字符+数字相结合");
            }
            if (initPassword.equals(loginBody.getNewPassword())) {
                return AjaxResult.error("新密码不可与初始密码相同");
            }
            // 更新用户密码
            SysUser user = userService.selectUserByUserName(loginBody.getUsername());
            if (user != null) {
//                if (!SecurityUtils.matchesPassword(initPassword, user.getPassword())) {
//                    return AjaxResult.error("用户密码已被修改");
//                }
                user.setPassword(SecurityUtils.encryptPassword(loginBody.getNewPassword()));
                user.setPwdUpdateDate(new Date());
                userService.resetUserPwd(user.getUserId(), user.getPassword());
                return AjaxResult.success("密码修改成功");
            } else {
                return AjaxResult.error("用户不存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("密码修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        int postType = postService.getHomePostType(user.getUserId());
        String roleNames = user.getRoles().stream().map(SysRole::getRoleName)
                .collect(Collectors.joining(","));
        AjaxResult ajax = AjaxResult.success();

        String isOpenAse = configService.selectConfigByKey("sys.ase.open");
        if("1".equals(isOpenAse)) {
            try {
                SecurityUtils.encryptAllFieldsExclude(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("roleNames", roleNames);
        ajax.put("postType", postType);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 获取高频功能
     *
     * @return 高频功能
     */
    @GetMapping("/getHighUse")
    public AjaxResult getHighUse()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        int postType = postService.getHomePostType(user.getUserId());
        List<SysOperLog> highUse = operLogService.selectOperLogCountByOperName(user.getUserName(),postType);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("highUse", highUse);
        return ajax;
    }

    /**
     * 获取数据统计
     *
     * @return 数据统计
     */
    @GetMapping("/getStatistics")
    public AjaxResult getStatistics()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        int postType = postService.getHomePostType(user.getUserId());
        List<Map<String, Object>> dataList = menuService.getDataList(postType);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("statistics", dataList);
        return ajax;
    }

    /**
     * 获取图表数据
     *
     * @return 数据统计
     */
    @GetMapping("/getChartData")
    public AjaxResult getChartData()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        int postType = postService.getHomePostType(user.getUserId());
        // 工时分类统计
        List<Map<String, Object>> hourStatistics = null;
        // 班组成员工分分布
        List<Map<String, Object>> classPointStatistics = null;
        // 超时工单情况
        List<Map<String, Object>> overTimeStatistics = null;
        // 班组成员工分情况
        List<Map<String, Object>> pepolePointStatistics = null;
        // 平均设备故障复发时间
        List<Map<String, Object>> faultStatistics = null;
        // 个人工单完成情况
        List<Map<String, Object>> userOrderStatistics = null;
        // 个人工分统计
        List<Map<String, Object>> userPointStatistics = null;
        // 扣分工单反馈列表
        List<Map<String, Object>> deductionPointStatistics = null;
        if (postType==2) {
            hourStatistics = new ArrayList<>();
            hourStatistics.add(operLogService.createDataMap("工单总工时","3240"));
            hourStatistics.add(operLogService.createDataMap("接单工时","450"));
            hourStatistics.add(operLogService.createDataMap("准备工时","680"));
            hourStatistics.add(operLogService.createDataMap("施工工时","1750"));
            hourStatistics.add(operLogService.createDataMap("验收工时","360"));
            classPointStatistics = new ArrayList<>();
            classPointStatistics.add(operLogService.createDataMap("一班","1250"));
            classPointStatistics.add(operLogService.createDataMap("二班","1180"));
            classPointStatistics.add(operLogService.createDataMap("三班","1320"));
            classPointStatistics.add(operLogService.createDataMap("四班","980"));
            classPointStatistics.add(operLogService.createDataMap("五班","1450"));
            classPointStatistics.add(operLogService.createDataMap("六班","1050"));
            classPointStatistics.add(operLogService.createDataMap("七班","1280"));
            classPointStatistics.add(operLogService.createDataMap("八班","1120"));
        } else if (postType==1) {
            overTimeStatistics = new ArrayList<>();
            overTimeStatistics.add(operLogService.createDataMap("一月","3"));
            overTimeStatistics.add(operLogService.createDataMap("二月","2"));
            overTimeStatistics.add(operLogService.createDataMap("三月","1"));
            overTimeStatistics.add(operLogService.createDataMap("四月","4"));
            overTimeStatistics.add(operLogService.createDataMap("五月","2"));
            overTimeStatistics.add(operLogService.createDataMap("六月","1"));
            pepolePointStatistics = new ArrayList<>();
            pepolePointStatistics.add(operLogService.createDataMap("张三","185"));
            pepolePointStatistics.add(operLogService.createDataMap("李四","210"));
            pepolePointStatistics.add(operLogService.createDataMap("王五","165"));
            pepolePointStatistics.add(operLogService.createDataMap("赵六","230"));
            pepolePointStatistics.add(operLogService.createDataMap("钱七","195"));
            pepolePointStatistics.add(operLogService.createDataMap("孙八","205"));
            faultStatistics = new ArrayList<>();
            faultStatistics.add(operLogService.createDataMap("1月","35"));
            faultStatistics.add(operLogService.createDataMap("2月","32"));
            faultStatistics.add(operLogService.createDataMap("3月","40"));
            faultStatistics.add(operLogService.createDataMap("4月","38"));
            faultStatistics.add(operLogService.createDataMap("5月","45"));
            faultStatistics.add(operLogService.createDataMap("6月","50"));
        } else {
            userOrderStatistics = new ArrayList<>();
            userOrderStatistics.add(operLogService.createDataMap("已完成","10"));
            userOrderStatistics.add(operLogService.createDataMap("进行中","1"));
            userOrderStatistics.add(operLogService.createDataMap("待处理","0"));
            userPointStatistics = new ArrayList<>();
            userPointStatistics.add(operLogService.createDataMap("1月","30"));
            userPointStatistics.add(operLogService.createDataMap("2月","35"));
            userPointStatistics.add(operLogService.createDataMap("3月","25"));
            userPointStatistics.add(operLogService.createDataMap("4月","40"));
            userPointStatistics.add(operLogService.createDataMap("5月","35"));
            userPointStatistics.add(operLogService.createDataMap("6月","45"));
            deductionPointStatistics = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("code","WO-2023-0567");
            map.put("deductionPoint",-10);
            map.put("remark", "未按规定流程操作");
            map.put("status", "0");
            deductionPointStatistics.add(map);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("hourStatistics", hourStatistics);
        ajax.put("classPointStatistics", classPointStatistics);
        ajax.put("overTimeStatistics", overTimeStatistics);
        ajax.put("pepolePointStatistics", pepolePointStatistics);
        ajax.put("faultStatistics", faultStatistics);
        ajax.put("userOrderStatistics", userOrderStatistics);
        ajax.put("userPointStatistics", userPointStatistics);
        ajax.put("deductionPointStatistics", deductionPointStatistics);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
