package com.ruoyi.web.controller.backstage;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AppLoginBody;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.app.baidu.GsonUtils;
//import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.utils.PageUtils.startPage;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/backstage/system")
public class BackstageController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BackstageController.class);

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserStService sysUserCountService;

    @Autowired
    private IDailyUserService dailyUserService;

    @Autowired
    private IUserWorkService userWorkService;

    @Autowired
    private ISysUserWorkCountService sysUserWorkCountService;

    @Autowired
    private ISysCityService sysCityService;

    @Autowired
    private ISysScenicService sysScenicService;

    @Autowired
    private ISysSourceService sysSourceService;

    @Autowired
    private IUserTypeService userTypeService;

    @Autowired
    private SysLoginService loginService;

//    @Autowired
//    private ISysUserService userService;


    // 查看系统用户
    @GetMapping("/getAllUserInfo")
    public TableDataInfo getAllUserInfo(){

        if(isAuthority(Constants.USER_MANAGE)) {

            // 这里面是不是就没有user_type啊,直接解码的token不包含user_type
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long userId = user.getUserId();

            SysUser user1 = sysUserService.selectUserById(userId);
            String userType = user1.getUserType();
            // 分页
            startPage();
            List<UserInfo> userInfoList = userInfoService.selectAllUserInfo();

            return getDataTable(userInfoList);

        }
        return noAuthority();



    }

    // 修改用户状态
    @PostMapping("/changeUserStatus")
    public AjaxResult changeUserState(@RequestBody UpdateUserStateDto updateUserStateDto){

        if(isAuthority(Constants.USER_MANAGE)){
            String username = updateUserStateDto.getUsername();
            String status = updateUserStateDto.getStatus();

            int back = sysUserService.updateUserState1(username,status);

            if(back>0){
                return success();
            }
            else{
                return AjaxResult.error("修改用户权限失败");
            }
        }
        else{

            return AjaxResult.error("无权限");
        }

    }

    //获取所有用户总数
    @GetMapping("/getUserCount")
    public AjaxResult getUserCount(){

        if(isAuthority(Constants.USER_MANAGE)) {

            AjaxResult ajax = new AjaxResult();

            Long count = sysUserCountService.getUserCount();
            ajax.put("userCount", count);
            return ajax;
        }
        else{

            return error("无权限访问");
        }

    }

    // 获取近7天用户总数
    @GetMapping("/getSeUserCount")
    public AjaxResult getSeUserCount(){
        if(isAuthority(Constants.USER_MANAGE)){
            AjaxResult ajax = new AjaxResult();
//            startPage();
            List<SeUserCountDto> seUserCount = sysUserCountService.getSeUserCount();
            ajax.put("seUserCount", seUserCount);
            return ajax;
        }
        else{

            return error("无权限访问");
        }
    }

    // 获取所有用户作品
    @GetMapping("/getAllUserWork")
    public AjaxResult getAllUserWork(){
        if(isAuthority(Constants.CONTENT_AUDIT)){
            AjaxResult ajax = new AjaxResult();
            startPage();
            List<UserWork> userWorkList = userWorkService.selectUserWorkList(new UserWork());
            ajax.put("userWork", userWorkList);
            return ajax;
        }
        else{

            return error("无权限访问");
        }
    }

    // 获取近7天作品总数
    @GetMapping("/getSeUserWorkCount")
    public AjaxResult getSeUserWorkCount(){
        if(isAuthority(Constants.CONTENT_AUDIT)){
            AjaxResult ajax = new AjaxResult();
            startPage();
            List<SeUserWorkCountDto> seUserWorkCount = sysUserWorkCountService.getSeUserWorkCount();
            ajax.put("seUserWorkCount", seUserWorkCount);
            return ajax;
        }
        else{

            return error("无权限访问");

        }
    }

//    @Log(title = "内容审核--审核作品", businessType = BusinessType.UPDATE)
//    //审核作品
//    @PostMapping("reviewWork")
//    public AjaxResult reviewWork(@RequestBody ReviewWorkDto reviewWorkDto){
//
//        Long userId = SecurityUtils.getUserId();
//        SysUser user = sysUserService.selectUserById(userId);
//
//        if(!isAuthority(Constants.CONTENT_AUDIT)){
//            return error("无权限访问");
//        }
//
//        Long workId = reviewWorkDto.getWorkId();
//        String workStatus = reviewWorkDto.getWorkStatus();
//        String auditOpinion = reviewWorkDto.getAuditOpinion();
//
//        // 这里默认一定能查到, 不然怎么审核这个作品
//        UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);
//
//        String workAuditOpinion = userWork.getAuditOpinion();
//
//        //当前这个作品的审核意见 一个json字符串
//        Map<String, String> allAuditOpinion = GsonUtils.fromJson(workAuditOpinion, HashMap.class);
//
//        Date now = new Date();
//
//        // key值格式为 time_userId_nickName_workStatus
//        String key = now.toString() +"_"+userId.toString() + "_" + user.getNickName() + "_" + workStatus;
//
//        allAuditOpinion.put(key, auditOpinion);
//
//        userWork.setWorkStatus(workStatus);
//        userWork.setAuditOpinion(GsonUtils.toJson(allAuditOpinion));
//
//        // 先不进行系统更新, 具体看下面的操作.
//        int back = userWorkService.updateUserWork(userWork);
//        if(back == 0){
//            return error("更新审核情况失败");
//        }
//
//        //作品审核通过和不通过的逻辑
//        if(workStatus.equals(Constants.WORKFAIL)){
//            //作品审核不通过, 根据作品展示时间来进一步选择行为.
//            //未展示 ------ 判断审核员数 : > 2 直接否决 状态改为5--不在审核   >1 交由第三个审核员审核. 状态改为待审
//            //展示中------直接退款
//            //根据作品 sourceId 查看资源位的情况.
//
//            //作品审核通过 直接更新就行了.
//        }
//
//
//
//        return success("作品审核成功");
//
//    }


    /*
    * 获取所有城市数景区数资源位数*/
    @GetMapping("stCityScenicSource")
    public AjaxResult getAllCity(){
        if(isAuthority(Constants.PRODUCT_MANAGE)) {
            int city_count = sysCityService.selectSysCityList(new SysCity()).size();

            int scenic_count = sysScenicService.selectSysScenicList(new SysScenic()).size();

            int source_count = sysSourceService.selectSysSourceList(new SysSource()).size();

            AjaxResult ajax = new AjaxResult();
            ajax.put("city_count", city_count);
            ajax.put("scenic_count", scenic_count);
            ajax.put("source_count", source_count);
            return ajax;
        }

        return error("无权限访问");

    }
//    @Log(title = "产品管理--获取所有资源位详情", businessType = BusinessType.GET)
    /*
    * 获取所有资源位详情*/
    @GetMapping("/getAllSource")
    public TableDataInfo getAllSource(){
        if(isAuthority(Constants.PRODUCT_MANAGE)){
            startPage();
            List<SysSource> sysSourceList = sysSourceService.selectSysSourceList(new SysSource());

            return getDataTable(sysSourceList);
        }

        return noAuthority();
    }

    @Log(title = "产品管理--更换资源的默认背景", businessType = BusinessType.UPDATE)
    // 更换资源的默认背景
    @PostMapping("/changeSourceBackground")
    public AjaxResult updateUserInfo(@RequestParam("changeSourceBackgroundDto") String changeSourceBackgroundDt,@RequestParam("work") MultipartFile work)
    {
        if(isAuthority(Constants.PRODUCT_MANAGE)) {




            ChangeSourceBackgroundDto changeSourceBackgroundDto = GsonUtils.fromJson(changeSourceBackgroundDt, ChangeSourceBackgroundDto.class);
            String city = changeSourceBackgroundDto.getCity();
            String part = changeSourceBackgroundDto.getPart();
            String scenic = changeSourceBackgroundDto.getScenic();

            SysSource sysSource = new SysSource();

            String localPath = RuoYiConfig.getProfile();
            //头像图片
            if (work.isEmpty()) {
                return error("图像文件为空");
            }
            // 验证文件类型（可选，这里只允许jpg,jpeg和png格式）
            String fileType = work.getContentType().split("/")[1].toLowerCase();

            if (!"jpg".equals(fileType) && !"jpeg".equals(fileType) && !"png".equals(fileType)) {
                return error("只支持jpg、jpeg和png格式的图片");
            }
            String filePath = localPath + "/work";
            try {

                // 保存文件到服务器
                work.transferTo(new File(filePath, city+'_'+scenic+'_'+part + "_default.jpg"));
//                sysSource.setWorkAddress(filePath+"/"+city+'_'+scenic+'_'+part + "_default.jpg");


                int back = sysSourceService.updateDefaultSourceWorkAddress(city, scenic, part, "0", filePath+"/"+city+'_'+scenic+'_'+part + "_default.jpg");
                if (back > 0) {
//                    AjaxResult ajax = success();
                    return success("默认背景更换成功");// 可以返回文件的相对路径或URL给前端
                } else {
                    return error("更换默认背景失败");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return error("头像文件上传失败");
            }
        }
        else{
            return error("无权限访问");
        }



//        return AjaxResult.success();
    }

    @Log(title = "产品管理--修改资源位价格", businessType = BusinessType.UPDATE)
    //修改资源位价格,
    // 参数: 城市,景区,区域,价格
    @PostMapping("/changeSourcePrice")
    public AjaxResult changeSourcePrice(@RequestBody  ChangeSourcePriceDto changeSourcePriceDto){
        if(isAuthority(Constants.PRODUCT_MANAGE)) {
            String city = changeSourcePriceDto.getCity();
            String scenic = changeSourcePriceDto.getScenic();
            String part = changeSourcePriceDto.getPart();
            SourcePriceDto price = changeSourcePriceDto.getPrice();

            System.out.println(price.toString());

            int back = sysSourceService.updateDefaultSourcePrice(city, scenic, part, price.toString());

            if(back > 0){
                return success("更新资源位默认价格成功");
            }
            return error("更新资源位默认价格失败");

        }

        return error("无权限");

    }

//    @Log(title = "系统管理--角色管理--获取用户类型", businessType = BusinessType.GET)
    //获取系统所有用户
    @GetMapping("/getAllUserType")
    public TableDataInfo getAllUser(){
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            startPage();
            List<UserType> userTypeList = userTypeService.selectUserTypeList(new UserType());
            return getDataTable(userTypeList);
        }

        return noAuthority();
    }

    @Log(title = "系统管理--角色管理--修改用户类型", businessType = BusinessType.UPDATE)
    //修改用户类型内容
    @PostMapping("/changeUserType")
    public AjaxResult changeUserType(@RequestBody UserType userType){
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            int back = userTypeService.updateUserType(userType);
            if(back > 0){
                return success("修改用户类型成功");
            }
            return error("修改用户类型失败");
        }

        return error("无权限访问");

    }

    @Log(title = "系统管理--角色管理--新建用户类型", businessType = BusinessType.INSERT)
    // 新建用户类型
    @PostMapping("/createUserType")
    public AjaxResult createUserType(@RequestBody UserType userType){
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            int back = userTypeService.insertUserType(userType);
            if(back > 0){
                return success("新建用户类型成功");
            }
            return error("新建用户类型失败");
        }

        return error("无权限访问");

    }

    @Log(title = "系统管理--角色管理--删除用户类型", businessType = BusinessType.DELETE)
    //删除用户类型
    @PostMapping("/deleteUserType")
    public AjaxResult deleteUserType(@RequestParam("typeId") Long typeId){
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            int back = userTypeService.deleteUserTypeByTypeId(typeId);
            if(back > 0){
                return success("删除用户类型成功");
            }
            return error("删除用户类型失败");
        }
        return error("无权限访问");
    }


    //------------------------------------------------旧版系统登录-------------------------------------------------
//    @Log(title = "系统登录--账密登录", businessType = BusinessType.OTHER)
    // 后台账密登录
    @PostMapping("/loginPassword")
    public AjaxResult loginPassword(@RequestBody AppLoginBody loginBody) {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.backstageLoginPassword(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    @Log(title = "系统登录--验证码登录", businessType = BusinessType.OTHER)
    // 后台验证码登录
    @PostMapping("/loginSms")
    public AjaxResult loginMessage(@RequestBody AppLoginBody loginBody) {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.backstageLoginMessage(loginBody.getUsername(), loginBody.getCode(),loginBody.getPhone());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

//    @Log(title = "系统管理--人员管理--获取所有后台系统用户", businessType = BusinessType.GET)
    //人员管理---获取所有后台系统用户
    @GetMapping("/getAllBackstageUser")
    public TableDataInfo getAllBackstageUser() {
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            startPage();
            List<BackstageUserDto> sysUserList = sysUserService.selectBackstageUserList();
            return getDataTable(sysUserList);
        }
        return noAuthority();

    }

    //新建后台用户
    @Log(title = "系统管理--人员管理--新建后台用户", businessType = BusinessType.INSERT)
    @PostMapping("/createBackstageUser")
    public AjaxResult createBackstageUser(@RequestBody BackstageUserDto backstageUserDto){
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            String nickName = backstageUserDto.getNickName();
            String phone = backstageUserDto.getPhonenumber();
            String realName = backstageUserDto.getRealName();
            String status = backstageUserDto.getStatus();
//            String userType = backstageUserDto.getUserType();
            String userType = "0000000001";
            String password = backstageUserDto.getPassword();

            if(password == null){
                password = "dafs81sd#j#@hkf*";
            }

            //先验证手机号是否已经注册
            int i = sysUserService.checkUserPhone(phone);
            if (i > 0) {
                return error("该手机号已经注册");
            }

            SysUser sysUser = new SysUser();
            sysUser.setNickName(nickName);
            sysUser.setPhonenumber(phone);
            sysUser.setStatus(status);
            sysUser.setUserType(userType);
            sysUser.setUserName(phone);
            sysUser.setAvatar("https://gips0.baidu.com/it/u=3124792457,2870658645&fm=3039&app=3039&f=JPEG");

//            System.out.println(nickName+","+phone+","+realName+","+status+","+userType+","+sysUser.getUserName()+","+password);

            sysUser.setPassword(SecurityUtils.encryptPassword(password));

            UserInfo userInfo = new UserInfo();



            int back = sysUserService.insertUser(sysUser);

            if (back > 0){
                System.out.println(nickName+","+phone+","+realName+","+status+","+userType);

                // 查询数据库中的用户账号信息
                SysUser newSysUser = sysUserService.selectUserByUserName(phone);
                //---------------------------- 新建用户个人信息--------------------------------------------
                userInfo.setUserId(newSysUser.getUserId());
                userInfo.setRealName(realName);
                userInfo.setPhonenumber(phone);
                userInfo.setBackGround("https://img.keaitupian.cn/newupload/11/1668068437206545.jpg");
                // 获取当前时间的毫秒值
                long currentTimeMillis = System.currentTimeMillis();
                // 利用毫秒值构造Date对象
                Date currentDate = new Date(currentTimeMillis);
                userInfo.setUpdateTime(currentDate);

                //设置上一次计算时间大约为10天前
                Date calculationTime = new Date(currentTimeMillis-1000000000);
                userInfo.setCalculationTime(calculationTime);

                int infoFlag = userInfoService.insertUserInfo(userInfo);
                if (infoFlag == 0) {
                    return error("个人信息注册失败,请联系系统管理人员");
                }
                return success("新建用户成功");
            }

            return error("新建用户失败, 请联系管理员");
        }
        return error("无权限访问");
    }

    @Log(title = "系统管理--人员管理--删除后台用户", businessType = BusinessType.DELETE)
    // 删除后台用户
    @PostMapping("/deleteBackstageUser")
    public AjaxResult deleteBackstageUser(@RequestParam("userId") Long userId){
        if(isAuthority(Constants.SYSTEM_MANAGE)){
            int back = sysUserService.deleteUserById(userId);
            if(back > 0){
                return success("删除用户成功");
            }
            return error("删除用户失败");
        }
        return error("无权限访问");
    }




    // 不能这样用啊,
//    @PostMapping("/updateUserOnlineTime")
    public AjaxResult updateUserOnlineTime(@RequestParam("duration") String  duration){
        Long userId = SecurityUtils.getUserId();


        Long durationLong = Long.parseLong(duration) / 1000;

        LocalDate now = LocalDate.now();

        DailyUser dailyUser = dailyUserService.selectDailyUserByUserIdAndDate(userId, now);

        //今天还没更新过用户数据
        if (dailyUser==null){
            DailyUser dailyUser1 = new DailyUser();
            dailyUser1.setUserId(userId);
            dailyUser1.setUpdateTime(new Date());
            dailyUser1.setCreateTime(new Date());
            dailyUser1.setOnlineTime(durationLong);
            dailyUser1.setDate(now);

            int back = dailyUserService.insertDailyUser(dailyUser1);
            if(back == 0){
                LOGGER.error("插入用户每天在线时间失败");
                System.out.println("插入用户每天在线时间失败");
                return error("更新用户每天在线时间失败");
            }
            else{
                LOGGER.info("插入新的用户每天数据");
                return success("更新成功");
            }

        }
        else{
            dailyUser.setOnlineTime(dailyUser.getOnlineTime()+durationLong);
            int back = dailyUserService.updateDailyUser(dailyUser);
            if(back == 0){
                LOGGER.error("更新用户每天在线时间失败");
                System.out.println("更新用户每天在线时间失败");
                return error("更新用户每天在线时间失败");
            }
            else{
                LOGGER.info("跟新新的用户每天数据");
                return success("更新成功");
            }

        }


    }

    private TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    private TableDataInfo noAuthority()
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.ERROR);
        rspData.setMsg("无权限");
        return rspData;
    }
    private boolean isAuthority(int startI){

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        SysUser user1 = sysUserService.selectUserById(userId);
        String userType = user1.getUserType();

        String type = userType.substring(startI, startI+2);

        if(type.equals("11")){
            return true;
        }

        String ip = IpUtils.getIpAddr();
        LOGGER.info("无权限用户认证,ip:"+ip);

        return false;

    }

}
