package cn.chnmuseum.party.web.controller;

import cn.chnmuseum.party.common.util.DateUtil;
import cn.chnmuseum.party.model.*;
import cn.chnmuseum.party.service.TAreaService;
import cn.chnmuseum.party.service.TBoardStatisticService;
import cn.chnmuseum.party.web.controller.base.BaseController;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * 展板统计信息表 前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-25
 */
@Slf4j
@RestController
@RequestMapping("/tBoardStatistic")
@Api(tags = {"展板统计信息表操作接口"})
public class TBoardStatisticController extends BaseController {

    @Resource
    private TBoardStatisticService tBoardStatisticService;

    @Autowired
    TAreaService areaService;

    //    @ApiImplicitParams(value = {
//            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
//            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer")
//    })
    @PostMapping("/getBoardSurvey")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:survey")
    @ApiOperation(value = "获取展板统计概况", notes = "获取展板统计概况")
    public Map<String, Object> getBoardSurvey(TBoardSurvey survey) {
        TUser user = null;
        try {
            user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                survey.setOrganCode(user.getOrgCode());
            }
        } catch (Exception e) {
            survey.setOrganCode(null);
        }
        // 默认当月
        if (StringUtils.isEmpty(survey.getStatisticDate())) {
            survey.setStatisticDate(DateUtil.getCurrentDate("yyyyMM"));
        }
        //加上区域条件
        List<String> areaIds = findAllAreaIdByParentCode(survey.getAreaCode());
        survey.setAreaIds(areaIds);
        TBoardSurvey result = this.tBoardStatisticService.getBoardSurvey(survey);

        return getResult(result);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer")
    })
    @PostMapping("/getBoardRankPageList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:rankPage")
    @ApiOperation(value = "获取展板播放排行", notes = "获取展板播放排行")
    public Map<String, Object> getBoardRankPageList(TBoardPlayRank rank) {
        TUser user = null;
        try {
            user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                rank.setOrganCode(user.getOrgCode());
            }
        } catch (Exception e) {
            rank.setOrganCode(null);
        }
        // 默认当月
        if (StringUtils.isEmpty(rank.getPlayDate())) {
            rank.setPlayDate(DateUtil.getCurrentDate("yyyyMM"));
        }
        //加上区域条件
        List<String> areaIds = findAllAreaIdByParentCode(rank.getAreaCode());
        rank.setAreaIds(areaIds);
        Page<TBoardPlayRank> page = this.tBoardStatisticService.getBoardRankPageList(getPage(), rank);
        return getResult(page);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer")
    })
    @PostMapping("/getBoardTrendPageList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:trendPage")
    @ApiOperation(value = "获取展板播放趋势", notes = "获取展板播放趋势")
    public Map<String, Object> getBoardTrendPageList(TBoardPlayTrend trend) throws ParseException {
        TUser user = null;
        try {
            user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                trend.setOrganCode(user.getOrgCode());
            }
        } catch (Exception e) {
            trend.setOrganCode(null);
        }
        // 如果查询日志为空,则默认当月
        if (StringUtils.isEmpty(trend.getPlayDate())) {
            trend.setPlayDate(DateUtil.getCurrentDate("yyyyMM"));
        }
        //加上区域条件
        List<String> areaIds = findAllAreaIdByParentCode(trend.getAreaCode());
        trend.setAreaIds(areaIds);

        Page<TBoardPlayTrend> page = this.tBoardStatisticService.getBoardTrendPageList(getPage(),trend);

//        List<TBoardPlayTrend> records = this.tBoardStatisticService.getBoardTrendPageList(getPage(), trend);
        // 处理数据为展板趋势图
        Map map = new HashMap();
        List dateList = new ArrayList();
        List cntList = new ArrayList();
        //按照 播放数据统计大屏 中 展板点播趋势图要求返回本月每天的播放量需求 修改接口
        getDateList(trend.getPlayDate(), dateList, cntList);
        for (TBoardPlayTrend t : page.getRecords()) {
//        for (TBoardPlayTrend t : records) {
//            dateList.add(t.getPlayDate());
//            cntList.add(t.getPlayNumber());
            int index = dateList.indexOf(t.getPlayDate());
            if (index >= 0) {
                cntList.set(index, t.getPlayNumber());
            }
        }
//        page.getRecords().sort(Comparator.comparing(TBoardPlayTrend::getPlayNumber).reversed());
        map.put("dateList", dateList);
        map.put("cntList", cntList);
        map.put("page",page);
        return getResult(map);
    }

    /**
     * 按照 播放数据统计大屏 中 展板点播趋势图要求返回本月每天的播放量  新增方法
     *
     * @param dateFormat
     * @param dateList
     * @param cntList
     * @throws ParseException
     */
    private void getDateList(String dateFormat, List dateList, List cntList) throws ParseException {
        Date date;
        Date beginTime;
        Date endTime;
        Date nowDate = new Date();
        if (dateFormat.length() > 4) {
            date = new SimpleDateFormat("yyyyMM").parse(dateFormat);
            beginTime = cn.hutool.core.date.DateUtil.beginOfMonth(date);
            endTime = cn.hutool.core.date.DateUtil.endOfMonth(date);
            //  设置最后时间不能大于当前时间
            if (nowDate.after(beginTime) && nowDate.before(endTime)) {
                endTime = nowDate;
            }
        } else {
            date = new SimpleDateFormat("yyyy").parse(dateFormat);
            beginTime = cn.hutool.core.date.DateUtil.beginOfYear(date);
            endTime = cn.hutool.core.date.DateUtil.endOfYear(date);
            //  设置最后时间不能大于当前时间
            if (nowDate.after(beginTime) && nowDate.before(endTime)) {
                endTime = nowDate;
            }
        }
        //生成范围类的一系列日期
        List<DateTime> dateTimes = cn.hutool.core.date.DateUtil.rangeToList(beginTime, endTime, DateField.DAY_OF_MONTH);
        dateTimes.stream().forEach(dt -> {
            String yyyyMMdd = dt.toString("yyyyMMdd");
            dateList.add(yyyyMMdd);
            //默认初始值0
            cntList.add(0);
        });
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer")
    })
    @PostMapping("/getBoardDistrictPageList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:districtPage")
    @ApiOperation(value = "获取地区展板播统计", notes = "获取地区展板播统计")
    public Map<String, Object> getBoardDistrictPageList(TDistrictBoardStatistic district) {
        TUser user = null;
        try {
            user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                district.setOrganCode(user.getOrgCode());
            }
        } catch (Exception e) {
            district.setOrganCode(null);
        }
        // 默认当月
        if (StringUtils.isEmpty(district.getPlayDate())) {
            district.setPlayDate(DateUtil.getCurrentDate("yyyyMM"));
        }
        //加上区域条件
        List<String> areaIds = findAllAreaIdByParentCode(district.getAreaCode());
        district.setAreaIds(areaIds);
        Page<TDistrictBoardStatistic> page = this.tBoardStatisticService.getBoardDistrictPageList(getPage(), district);
        return getResult(page);
    }

    /**
     * 根据父地区code查询查询所有子下级  返回包含本机id以及所有的子集id
     *
     * @param areaCode
     * @return
     */
    private List<String> findAllAreaIdByParentCode(String areaCode) {
        List<String> areaIds = new ArrayList<>();
        if (StringUtils.isBlank(areaCode)) {
            return areaIds;
        }
        LambdaQueryWrapper<TArea> wrapper = new QueryWrapper<TArea>().lambda()
                .eq(TArea::getCode, areaCode);
        TArea one = areaService.getOne(wrapper, false);
        if (one == null) {
            return areaIds;
        }
        List<String> parentAreaIds = new ArrayList<>();
        String valueOf = String.valueOf(one.getId());
        parentAreaIds.add(valueOf);
        //加上自己本身的id
        areaIds.add(valueOf);
        //循环调用数据库,但实际只会调用3到4次,区域级别无非三四级
        while (!CollectionUtils.isEmpty(parentAreaIds)) {
            wrapper.clear();
            wrapper.in(TArea::getParentId, parentAreaIds)
                    .select(TArea::getId, TArea::getParentId);
            List<TArea> list = areaService.list(wrapper);
            if (CollectionUtils.isEmpty(list)) {
                //为空跳出循环
                break;
            }
            List<String> ids = list.stream().map(l -> String.valueOf(l.getId())).collect(Collectors.toList());
            parentAreaIds = ids;
            areaIds.addAll(parentAreaIds);
        }
        return areaIds;
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "organId", value = "统计机构", paramType = "query", dataType = "String")
    })
    @PostMapping("/getBoardProvincePlayTotalList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:provPlayList")
    @ApiOperation(value = "获取省级展板播放统计", notes = "获取省级展板播放统计")
    public Map<String, Object> getBoardProvincePlayTotalList(String organId) {
        String orgCode = null;
        try {
            TUser user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                orgCode = user.getOrgCode();
            }
        } catch (Exception e) {
            orgCode = null;
        }
        List list = this.tBoardStatisticService.getBoardProvincePlayTotalList(organId, orgCode);
        return getResult(list);
    }


    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "areaCode", value = "区域编码", paramType = "query", dataType = "String")
    })
    @PostMapping("/getBoardCityPlayTotalList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:provPlayList")
    @ApiOperation(value = "获取下级区域展板播放统计", notes = "获取下级展板播放统计")
    public Map<String, Object> getBoardCityPlayTotalList(String areaCode) {
        String orgCode = null;
        try {
            TUser user = getcurUser();
            if (user.getRoleList().size()>0&&!user.getRoleList().contains("1")) {
                orgCode = user.getOrgCode();
            }
        } catch (Exception e) {
            orgCode = null;
        }
        List list = this.tBoardStatisticService.getBoardCityPlayTotalList(areaCode,orgCode);
        return getResult(list);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "frequencyDate", value = "互动统计时间 年:yyyy 月:yyyyMM,默认当月", paramType = "query", dataType = "String")
    })
    @PostMapping("/getInteractionFrequencyPageList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:districtPage")
    @ApiOperation(value = "获取互动频次统计信息", notes = "获取互动频次统计信息")
    public Map<String, Object> getInteractionFrequencyPageList(String frequencyDate,String areaCode) {
        String orgCode = null;
        try {
            TUser user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                orgCode = user.getOrgCode();
            }
        } catch (Exception e) {
            orgCode = null;
        }
        if (StringUtils.isEmpty(frequencyDate)) {
            frequencyDate = DateUtil.getCurrentDate("yyyyMM");
        }
        //加上区域条件
        List<String> areaIds = findAllAreaIdByParentCode(areaCode);

        Page page = this.tBoardStatisticService.getInteractionFrequency(getPage(), frequencyDate, orgCode,areaIds);
        //
        Map map = new HashMap();
        List organList = new ArrayList<>();
        List cntList = new ArrayList();
        for (Object o : page.getRecords()) {
            Map m = (HashMap) o;
            organList.add(m.get("organName"));
            cntList.add(m.get("frequencyCnt"));
        }
        map.put("organList", organList);
        map.put("cntList", cntList);
        map.put("page", page);
        return getResult(map);
    }


    /**
     * 以下两个接口是pc端专用
     *
     * @param trend
     * @return
     */
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer")
    })
    @PostMapping("/getBoardPageList")
//    @RequiresAuthentication  //@RequiresPermissions("t:board:statistic:Page")
    @ApiOperation(value = "获取展板播放趋势Pc", notes = "获取展板播放趋势Pc")
//    @MethodLog(operModule = OperModule.TEND, operType = OperType.SELECT)
    public Map<String, Object> getBoardPageList(TBoardPlayTrend trend) throws ParseException {
        TUser user = null;
        try {
            user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                trend.setOrganCode(user.getOrgCode());
            }
        } catch (Exception e) {
            trend.setOrganCode(null);
        }
        // 如果查询日志为空,则默认当月
        if (StringUtils.isEmpty(trend.getBeginDate())) {
            trend.setBeginDate(DateUtil.getCurrentDate("yyyy") + "01");
            trend.setEndDate(DateUtil.getCurrentDate("yyyyMM"));
        }
        Page<TBoardPlayTrend> page = this.tBoardStatisticService.getBoardPageList(getPage(), trend);
        // 处理数据为展板趋势图
        Map map = new HashMap();
        List dateList = new ArrayList();
        List cntList = new ArrayList();

        for (TBoardPlayTrend t : page.getRecords()) {
            dateList.add(t.getPlayDate());
            cntList.add(t.getPlayNumber());
        }
        List<TBoardPlayTrend> list = page.getRecords();
        list.sort(Comparator.comparing(TBoardPlayTrend::getPlayNumber, Comparator.reverseOrder()).thenComparing(TBoardPlayTrend::getPlayDate, Comparator.reverseOrder()));
        if (list.size() >= 10) {
            list = list.subList(0, 10);
        }
        page.setRecords(list);
        map.put("dateList", dateList);
        map.put("cntList", cntList);
        map.put("page", page);
        return getResult(map);
    }


    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "frequencyDate", value = "互动统计时间 年:yyyy 月:yyyyMM,默认当月", paramType = "query", dataType = "String")
    })
    @PostMapping("/getInteractionPageList")
//    @RequiresAuthentication  //@RequiresPermissions("t:interaction:statistic:districtPage")
    @ApiOperation(value = "获取互动频次统计信息pc", notes = "获取互动频次统计信息pc")
//    @MethodLog(operModule = OperModule.INTERACTION, operType = OperType.SELECT)
    public Map<String, Object> getInteractionPageList(String frequencyDate) {
        String orgCode = null;
        try {
            TUser user = getcurUser();
            if (user.getRoleList().size() > 0 && !user.getRoleList().contains("1")) {
                orgCode = user.getOrgCode();
            }
        } catch (Exception e) {
            orgCode = null;
        }
        if (StringUtils.isEmpty(frequencyDate)) {
            frequencyDate = DateUtil.getCurrentDate("yyyyMM");
        }

        Page page = this.tBoardStatisticService.getInteractionFrequency(getPage(), frequencyDate, orgCode);
        //
        Map map = new HashMap();
        List organList = new ArrayList<>();
        List cntList = new ArrayList();
        for (Object o : page.getRecords()) {
            Map m = (HashMap) o;
            organList.add(m.get("organName"));
            cntList.add(m.get("frequencyCnt"));
        }
        map.put("organList", organList);
        map.put("cntList", cntList);
        map.put("page", page);
        return getResult(map);
    }
}