package com.winsun.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.bean.HhrSupervisorSchool;
import com.winsun.bean.HhrUser;
import com.winsun.bean.UserSchool;
import com.winsun.mapper.HhrSupervisorSchoolMapper;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.mapper.UserSchoolMapper;
import com.winsun.service.AccessStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 首页数据获取
 */
@RequestMapping(("/analysis"))
@RestController
@Slf4j
public class AnalysisController extends BaseController {

    private HhrUserMapper hhrUserMapper;

    private SysUserMapper sysUserMapper;

    private HhrSupervisorSchoolMapper hhrSupervisorSchoolMapper;

    private UserSchoolMapper userSchoolMapper;

    private AccessStatisticService accessStatisticService;

    @Autowired
    public AnalysisController(SysUserMapper sysUserMapper, HhrUserMapper hhrUserMapper,
                              HhrSupervisorSchoolMapper hhrSupervisorSchoolMapper,
                              UserSchoolMapper userSchoolMapper,
                              AccessStatisticService accessStatisticService) {
        this.sysUserMapper = sysUserMapper;
        this.hhrUserMapper = hhrUserMapper;
        this.hhrSupervisorSchoolMapper = hhrSupervisorSchoolMapper;
        this.userSchoolMapper = userSchoolMapper;
        this.accessStatisticService = accessStatisticService;
    }

    /**
     * 获取用户信息
     * @return
     */
    @Permission(menuname="获取用户信息", value="/getInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getInfo() {
        ShiroUser shiroUser = getShiroUser();
        String account = shiroUser.getAccount();
        log.info("当前登录用户信息：" + account);
        Map<String, Object> result = new HashMap<>();
        result.put("name", shiroUser.getName());
        result.put("phone", shiroUser.getPhone());
        StringBuffer sb = new StringBuffer();
        for(String str : shiroUser.getRoleNames()) {
            sb.append(str + " ");
        }
        result.put("roleNames", sb.toString());
        result.put("deptName", shiroUser.getDeptName());
        return ResponseData.success(result);
    }

    /**
     * 获取业务数据
     * @return
     */
    @Permission(menuname="获取订单统计", value="/getOrderStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getOrderStatistic() {

        Map<String, Object> resultMap = new HashMap<>();

        ShiroUser shiroUser = getShiroUser();
        Integer id = shiroUser.getId();
        List<Integer> userIds = getUserIds(shiroUser.getId(), shiroUser.getRoleNames());

        String today, toWeekStart, toWeekEnd, toMonthStart, toMonthEnd;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar nowDate = Calendar.getInstance();
        Calendar weekDate = Calendar.getInstance();

        // 统计已有订单当日、周、月的情况
        today = sdf.format(nowDate.getTime());
        
        // 获取本周
        int i = weekDate.get(Calendar.DAY_OF_WEEK);
        weekDate.add(Calendar.DATE, -8 + i);
        toWeekStart = sdf.format(weekDate.getTime());
        weekDate.add(Calendar.DATE, 7);
        toWeekEnd = sdf.format(weekDate.getTime());
        
        // 获取当月
        nowDate.set(Calendar.DATE, 1);
        toMonthStart = sdf.format(nowDate.getTime());
        nowDate.add(Calendar.MONTH, 1);
        toMonthEnd = sdf.format(nowDate.getTime());
        Map<String, Object> allOrders = hhrUserMapper.statisticAllOrderNum(userIds, today, toWeekStart, toWeekEnd, toMonthStart, toMonthEnd, false);
        resultMap.put("allOrders", allOrders);
        // 统计订单完成日、周、月情况
        Map<String, Object> completeOrders = hhrUserMapper.statisticAllOrderNum(userIds, today, toWeekStart, toWeekEnd, toMonthStart, toMonthEnd, true);
        resultMap.put("completeOrders", completeOrders);

        // TODO 查询订单排名

        return ResponseData.success(resultMap);
    }

    // 获取pv
    @Permission(menuname="获取pv", value="getPvStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getPvStatistic(String startDate, String endDate, String type) {
        // 判断身份
        ShiroUser shiroUser = getShiroUser();
        log.info("获取当前登录信息" + JSON.toJSONString(shiroUser));
        List<Integer> userIds = getUserIds(shiroUser.getId(), shiroUser.getRoleNames());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> pvStatisticsEchartData = null;
        try {
            // 督导查询合伙人id去匹配
            pvStatisticsEchartData = accessStatisticService.getPvStatisticsEchartData(sdf.parse(startDate), sdf.parse(endDate), type, userIds);
        }catch(ParseException e) {
            return ResponseData.error("日期格式错误");
        }

        return ResponseData.success(pvStatisticsEchartData);
    }

    // 获取uv
    @Permission(menuname="获取uv", value="getUvStatistic", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getUvStatistic(String startDate, String endDate, String type) {
        // 判断身份
        ShiroUser shiroUser = getShiroUser();
        log.info("获取当前登录信息" + JSON.toJSONString(shiroUser));
        List<Integer> userIds = getUserIds(shiroUser.getId(), shiroUser.getRoleNames());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 督导查询合伙人id去匹配
        Map<String, Object> uvStatisticsEchartData = null;
        try {
            // 督导查询合伙人id去匹配
            uvStatisticsEchartData = accessStatisticService.getUvStatisticsEchartData(sdf.parse(startDate), sdf.parse(endDate), type, userIds);
        }catch(ParseException e) {
            return ResponseData.error("日期格式错误");
        }

        return ResponseData.success(uvStatisticsEchartData);

    }

    /**
     * 获取管辖内用户id
     * @return
     */
    public List<Integer> getUserIds (Integer userId, List<String> roles) {
        List<Integer> resultList = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        for(String role : roles) {
            sb.append(role);
        }
        String rolesStr = sb.toString();
        if (rolesStr.indexOf("超级管理员") != -1) {
            return resultList;
        }else if(rolesStr.indexOf("县分管理员") != -1){
            // 县分管理员(查询管辖内的学校用户)
            resultList = this.getSubNameUser(userId);
        }else if(rolesStr.indexOf("督导") != -1 || rolesStr.indexOf("楼长") != -1) {
            // 合伙人（督导、楼长，查询本人及下级信息）
            resultList = this.getChildrenUser(userId);
        }else{
            // 合伙人（成员，查询本人信息）
        }
        resultList.add(userId);
        return resultList;
    }

    /**
     * 获取所有用户
     * @param userId
     * @return
     */
    public List<Integer> getAllUser(Integer userId) {
        Wrapper<HhrUser> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id");
        wrapper.isNotNull("id");
        List<HhrUser> hhrUsers = hhrUserMapper.selectList(wrapper);
        List<Integer> resultList = new ArrayList<>();
        hhrUsers.forEach(hhrUser -> {
            resultList.add(Integer.parseInt(hhrUser.getId()));
        });
        return resultList;
    }

    /**
     * 获取县分用户
     * @param userId
     * @return
     */
    public List<Integer> getSubNameUser(Integer userId) {
        Wrapper<HhrSupervisorSchool> wrapper = new EntityWrapper<>();
        wrapper.eq("userId", userId);
        List<HhrSupervisorSchool> hhrSupervisorSchools = hhrSupervisorSchoolMapper.selectList(wrapper);
        if (hhrSupervisorSchools == null || hhrSupervisorSchools.size() == 0) {
            return new ArrayList<>();
        }

        String[] school = new String[hhrSupervisorSchools.size()];
        for(int i = 0; i < hhrSupervisorSchools.size(); ++i) {
            school[i] = hhrSupervisorSchools.get(i).getSchool();
        }

        Wrapper<UserSchool> userSchoolWrapper = new EntityWrapper<>();
        userSchoolWrapper.in("school_id", school);
        List<UserSchool> userSchools = userSchoolMapper.selectList(userSchoolWrapper);
        List<Integer> resultList = new ArrayList<>();
        userSchools.forEach(userSchool -> {
            resultList.add(Integer.parseInt(userSchool.getUserId()));
        });
        return resultList;
    }

    /**
     * 获取子用户
     * @param userId
     * @return
     */
    public List<Integer> getChildrenUser(Integer userId) {

        Wrapper<HhrUser> wrapper = new EntityWrapper<>();
        wrapper.like("parent_ids", userId + "");
        List<HhrUser> hhrUsers = hhrUserMapper.selectList(wrapper);
        List<Integer> resultList = new ArrayList<>();
        hhrUsers.forEach(hhrUser -> {
            resultList.add(Integer.parseInt(hhrUser.getId()));
        });
        return resultList;
    }

}
