package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.service.*;
import com.ruoyi.business.service.impl.TbUserServiceImpl;
import com.ruoyi.web.util.EsUtil;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.CookieUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 首页 业务处理
 * 
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        Boolean footer = Convert.toBool(configService.selectConfigByKey("sys.index.footer"), true);
        Boolean tagsView = Convert.toBool(configService.selectConfigByKey("sys.index.tagsView"), true);
        mmap.put("footer", footer);
        mmap.put("tagsView", tagsView);
        mmap.put("mainClass", contentMainClass(footer, tagsView));
        mmap.put("copyrightYear", RuoYiConfig.getCopyrightYear());
        mmap.put("demoEnabled", RuoYiConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登录");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }


    public static void main(String[] args) {
        DateTime today = DateUtil.beginOfDay(DateUtil.date());
        DateTime yestoday = today.offsetNew(DateField.DAY_OF_YEAR,-1);
        System.out.println(today);
        System.out.println(yestoday);
    }

    @Autowired
    private ITbUserService tbUserService;

    @Autowired
    private ITbUserMemberService memberService;

    @Autowired
    private ITbPaymentService paymentService;

    @Autowired
    private IReRewardService reRewardService;

    @Autowired
    private RestHighLevelClient esRestClient;

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap) throws IOException {
        mmap.put("version", RuoYiConfig.getVersion());

        DateTime endTime = DateUtil.beginOfDay(DateUtil.date());
        DateTime startTime = endTime.offsetNew(DateField.DAY_OF_YEAR,-1);
        int userTotal = tbUserService.selectCount(null , null);
        int userYesTodayTotal = tbUserService.selectCount(startTime, endTime);
        //

        int vipTotal = memberService.selectCount(null, null);
        int vipYesTodayTotal = memberService.selectCount(startTime, endTime);

        int paymentTotal = paymentService.selectCount(null, null);
        int paymentYesTodayTotal = paymentService.selectCount(startTime, endTime);

        Double paymentSumAmt = paymentService.selectSumAmt(null, null);
        Double paymentYesTodaySumAmt = paymentService.selectSumAmt(startTime, endTime);

        int reRewardTotal  = reRewardService.selectCount(null, null);
        int reRewardYesTodayTotal  = reRewardService.selectCount(startTime, endTime);


        HashMap<String, Object> map = new HashMap<>();

        map.put("userTotal",userTotal);
        map.put("userYesTodayTotal",userYesTodayTotal);

        map.put("vipTotal",vipTotal);
        map.put("vipYesTodayTotal",vipYesTodayTotal);

        map.put("paymentTotal",paymentTotal);
        map.put("paymentYesTodayTotal",paymentYesTodayTotal);
        map.put("paymentSumAmt",paymentSumAmt);
        map.put("paymentYesTodaySumAmt",paymentYesTodaySumAmt);

        map.put("reRewardTotal",reRewardTotal);
        map.put("reRewardYesTodayTotal",reRewardYesTodayTotal);



        CountRequest countRequest = EsUtil.EsEnum.BID.getCountRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        countRequest.source(searchSourceBuilder);

        // 招标项目数
        searchSourceBuilder.query(new BoolQueryBuilder().filter(QueryBuilders.termQuery("bidState", 0)));
        CountResponse count = esRestClient.count(countRequest, RequestOptions.DEFAULT);
        long bidCount = count.getCount();

        // 中标项目数
        searchSourceBuilder.query(new BoolQueryBuilder().filter(QueryBuilders.termQuery("bidState", 1)));
        CountResponse winBidCountResponse = esRestClient.count(countRequest, RequestOptions.DEFAULT);
        long winBidCount = winBidCountResponse.getCount();

        BoolQueryBuilder bidState = new BoolQueryBuilder()
                .filter(QueryBuilders.termQuery("bidState", 0))
                .filter(QueryBuilders.rangeQuery("creatTime").gte(startTime.getTime() / 1000L).lt(endTime.getTime() / 1000L));
        searchSourceBuilder.query(bidState);
        CountResponse yesTodayBidCountResponse = esRestClient.count(countRequest, RequestOptions.DEFAULT);
        long yesTodayBidCount = yesTodayBidCountResponse.getCount();

        BoolQueryBuilder winBidState = new BoolQueryBuilder()
                .filter(QueryBuilders.termQuery("bidState", 1))
                .filter(QueryBuilders.rangeQuery("creatTime").gte(startTime.getTime() / 1000L).lt(endTime.getTime() / 1000L));
        searchSourceBuilder.query(winBidState);
        CountResponse yesTodayWinBidCountResponse = esRestClient.count(countRequest, RequestOptions.DEFAULT);
        long yesTodayWinBidCount = yesTodayWinBidCountResponse.getCount();

        map.put("bidCount",  bidCount);
        map.put("yesTodayBidCount",  yesTodayBidCount);

        map.put("winBidCount",  winBidCount);
        map.put("yesTodayWinBidCount",  yesTodayWinBidCount);


        mmap.put("statisMap", map);

        System.out.println(JSONObject.toJSONString(map));

        return "main_v1";
    }

    // content-main class
    public String contentMainClass(Boolean footer, Boolean tagsView)
    {
        if (!footer && !tagsView)
        {
            return "tagsview-footer-hide";
        }
        else if (!footer)
        {
            return "footer-hide";
        }
        else if (!tagsView)
        {
            return "tagsview-hide";
        }
        return StringUtils.EMPTY;
    }

    // 检查初始密码是否提醒修改
    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;
    }
}
