package com.huiju.estateagents.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TdWxDict;
import com.huiju.estateagents.excel.IntentionUser;
import com.huiju.estateagents.excel.StatsBuilding;
import com.huiju.estateagents.excel.StatsTimeBuilding;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.service.IStatisticalService;
import com.huiju.estateagents.statistic.entity.TsPersonFromStatistic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据统计
 */
@RestController
@RequestMapping("/api")
public class StatisticalController extends BaseController {

    @Autowired
    private IStatisticalService iStatisticalService;

    /**
     * 首页统计
     * @return
     */
    @GetMapping(value = "/admin/indexStatistical")
    public ResponseBean indexStatistical(HttpServletRequest request) {
        return iStatisticalService.indexStatistical(getOrgId(request));
    }

    /**
     * 活跃用户数
     * @return
     */
    @GetMapping(value = "/admin/selectActiveUserCount")
    public ResponseBean selectActiveUserCount(@RequestParam String dateType,
                                              @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                              @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                              HttpServletRequest request) {
        return iStatisticalService.selectActiveUserCount(getOrgId(request), dateType, startDate,endDate);
    }

    /**
     * 新增用户数
     * @return
     */
    @GetMapping(value = "/admin/selectNewsUserCount")
    public ResponseBean selectNewsUserCount(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                            HttpServletRequest request) {
        return iStatisticalService.selectNewsUserCount(getOrgId(request), startDate, endDate);
    }

    /**
     * 新增用户数
     * @return
     */
    @GetMapping(value = "/admin/changeNewsUserCount")
    public ResponseBean changeNewsUserCount(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                            HttpServletRequest request) {
        return iStatisticalService.changeNewsUserCount(getOrgId(request), startDate, endDate);
    }

    /**
     * 转化率 统计
     * @return
     */
    @GetMapping(value = "/admin/selectConversion")
    public ResponseBean selectConversion(@RequestParam("conversion") String conversion,
                                         HttpServletRequest request) {
        return iStatisticalService.selectConversion(getOrgId(request), conversion);
    }

    /**
     * 用户行为
     * @return
     */
    @GetMapping(value = "/admin/selectUserBehavior")
    public ResponseBean selectUserBehavior(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                           @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                           @RequestParam(value = "buildingId", required = false) String buildingId,
                                           @RequestParam(value = "eventType", required = false) String eventType,
                                           @RequestParam(value = "event", required = false) String event,
                                           @RequestParam(value = "activity", required = false) String activity,
                                           HttpServletRequest request) {
        return iStatisticalService.selectUserBehavior(pageNum, pageSize, getOrgId(request), startDate, endDate, buildingId, eventType, event, activity);
    }

    /**
     * 行为分析的 具体事件数据列表
     * @return
     */
    @GetMapping(value = "/admin/selectEventAll")
    public ResponseBean selectEventAll(@RequestParam(required = false) String event,
                                       @RequestParam(required = false) String personId,
                                       HttpServletRequest request) {
        return iStatisticalService.selectEventAll(getOrgId(request), event, personId);
    }


    /**
     * 用户来源
     * @return
     */
    @GetMapping(value = "/admin/selectUserResource")
    public ResponseBean selectUserResource(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                           @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                           HttpServletRequest request) {
        return iStatisticalService.selectUserResource(getOrgId(request), startDate, endDate);
    }


    /**
     * 用户总数
     * @return
     */
    @GetMapping(value = "/admin/selectUserCount")
    public ResponseBean selectUserResource(HttpServletRequest request) {
        return iStatisticalService.selectUserCount(getOrgId(request));
    }

    /**
     * 用户注册数
     * @return
     */
    @GetMapping(value = "/admin/selectRegisteredCount")
    public ResponseBean selectRegisteredCount(HttpServletRequest request) {
        return iStatisticalService.selectRegisteredCount(getOrgId(request));
    }

    /**
     * 用户最近七天
     * @return
     */
    @GetMapping(value = "/admin/selectRecentlyCount")
    public ResponseBean selectRecentlyCount(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                            HttpServletRequest request) {
        return iStatisticalService.selectRecentlyCount(getOrgId(request), startDate, endDate);
    }

    /**
     * 性别比例
     * @return
     */
    @GetMapping(value = "/admin/selectSexUser")
    public ResponseBean selectSexUser(HttpServletRequest request) {
        return iStatisticalService.selectSexUser(getOrgId(request));
    }

    /**
     * 城市比例
     * @return
     */
    @GetMapping(value = "/admin/selectCityUser")
    public ResponseBean selectCityUser(HttpServletRequest request) {
        Integer orgId = getOrgId(request);
        return iStatisticalService.selectCityUser(orgId);
    }

    /**
     * 人员分布城市比例
     * @return
     */
    @GetMapping(value = "/admin/selectCityPerson")
    public ResponseBean selectCityPerson(HttpServletRequest request) {
        Integer orgId = getOrgId(request);
        return iStatisticalService.selectCityPerson(orgId);
    }

    /**
     * 意向用户  首页
     * @return
     */
    @GetMapping(value = "/admin/selectIntentionUser")
    public ResponseBean selectIntentionUser(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize,
                                            @RequestParam(value = "buildingId", required = false) String buildingId,
                                            HttpServletRequest request) {
        return iStatisticalService.selectIntentionUser(pageNum, pageSize, getOrgId(request), buildingId, getTaPersonBuildingListByUserId(request));
    }

    /**
     * 意向用户 导出
     * @return
     */
    @GetMapping(value = "/admin/exportIntentionUser")
    public void getBuildingTimeTableList(@RequestParam(value = "buildingId", required = false) String buildingId,
                                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=意向客户.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), IntentionUser.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("项目详情统计").build();
        List<IntentionUser> list = iStatisticalService.getExportIntentionUser(getOrgId(request), buildingId, getTaPersonBuildingListByUserId(request));
        excelWriter.write(list, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 用户来源  首页
     * @return
     */
    @GetMapping(value = "/admin/selectPersonFrom")
    public ResponseBean selectPersonFrom(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                         @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                            HttpServletRequest request) {
        return iStatisticalService.selectPersonFrom(getOrgId(request), startDate,endDate);
    }

    /**
     * 用户来源  折线图 首页
     * @return
     */
    @GetMapping(value = "/admin/selectPersonFromGroupByDay")
    public ResponseBean selectPersonFromGroupByDay(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                         @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                         HttpServletRequest request) {
        return iStatisticalService.selectPersonFromGroupByDay(getOrgId(request), startDate,endDate);
    }

    /**
     * 项目排行统计图
     * @return
     */
    @GetMapping(value = "/admin/stats/barList")
    public ResponseBean selectBuildingBar(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                           @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                           HttpServletRequest request) {
        return iStatisticalService.getStatsBarList(getOrgId(request), startDate, endDate, getTaPersonBuildingListByUserId(request));
    }


    /**
     * 项目排行统计图
     * @return
     */
    @GetMapping(value = "/admin/stats/tableList")
    public ResponseBean selectBuildingTableList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                                @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                                @RequestParam(value = "buildingId", required = false) String buildingId,
                                                @RequestParam(value = "sortField", required = false) String sortField,
                                                @RequestParam(value = "sortOrder", required = false) String sortOrder,
                                                HttpServletRequest request) {
        return iStatisticalService.getStatsTableList(pageNum,pageSize,getOrgId(request), startDate, endDate,buildingId, getTaPersonBuildingListByUserId(request),sortField,sortOrder);
    }

    /**
     * 项目排行统计图
     * @return
     */
    @GetMapping(value = "/admin/stats/buildingExport")
    public void getBuildingTableList(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                             @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                             @RequestParam(value = "buildingId", required = false) String buildingId,
                                             HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=项目统计.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), StatsBuilding.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("项目统计").build();
        List<StatsBuilding> list = iStatisticalService.getExportTableList(getOrgId(request), startDate, endDate,buildingId, getTaPersonBuildingListByUserId(request));
        excelWriter.write(list, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 项目排行统计图
     * @return
     */
    @GetMapping(value = "/admin/stats/timeBarList")
    public ResponseBean selectBuildingTimeBar(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                          @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                          @RequestParam(value = "buildingId", required = false) String buildingId,
                                          HttpServletRequest request) {
        return iStatisticalService.getStatsTimeBarList(getOrgId(request), startDate, endDate, buildingId, getTaPersonBuildingListByUserId(request));
    }

    /**
     * 项目排行统计图
     * @return
     */
    @GetMapping(value = "/admin/stats/timeTableList")
    public ResponseBean selectBuildingTimeTableList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                                @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                                @RequestParam(value = "buildingId", required = false) String buildingId,
                                                @RequestParam(value = "sortField", required = false) String sortField,
                                                @RequestParam(value = "sortOrder", required = false) String sortOrder,
                                                HttpServletRequest request) {
        return iStatisticalService.getStatsTimeTableList(pageNum,pageSize,getOrgId(request), startDate, endDate,buildingId, getTaPersonBuildingListByUserId(request),sortField,sortOrder);
    }

    /**
     * 项目排行统计图
     * @return
     */
    @GetMapping(value = "/admin/stats/buildingTimeExport")
    public void getBuildingTimeTableList(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                     @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                     @RequestParam(value = "buildingId", required = false) String buildingId,
                                     HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=项目详情统计.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), StatsTimeBuilding.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("项目详情统计").build();
        List<StatsTimeBuilding> list = iStatisticalService.getExportTimeTableList(getOrgId(request), startDate, endDate,buildingId, getTaPersonBuildingListByUserId(request));
        excelWriter.write(list, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }



    /**
     * 新增用户导出
     * @return
     */
    @GetMapping(value = "/admin/exportUserStats")
    public void exportUserStats(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                         @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDate endDate,
                                         @RequestParam(value = "userType", required = false) String userType,
                                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=新增用户.xlsx");
        ResponseBean responseBean = iStatisticalService.selectPersonFrom(getOrgId(request), startDate, endDate);
        List<List<String>> headerList = headerList(responseBean.getData());
        List<List<String>> dataList = dataList(responseBean.getData(),userType);
        EasyExcel.write(response.getOutputStream()).head(headerList).sheet("新增用户").doWrite(dataList);
    }

    /**
     * 构建表数据
     * @param data
     * @return
     */
    private List<List<String>> dataList(Object data,String userType) {
        Map<String, Object> map = (Map<String, Object>) data;
        List<TsPersonFromStatistic> list = (List<TsPersonFromStatistic>) map.get("list");
        List<List<String>> dataList = new ArrayList<>();
        List<TdWxDict> tdWxDicts = (List<TdWxDict>) map.get("tdWxDicts");
        list.forEach(l -> {
            List<String> columlist = new ArrayList<>();
            columlist.add(l.getCreateTime());
            tdWxDicts.forEach(e -> {
                if (e.getSceneType().equals(l.getSceneType())){
                    if (userType.equals("registered")){
                        columlist.add(l.getRegisteredNum().toString());
                    }else {
                        columlist.add(l.getFromNum().toString());
                    }
                }else {
                    columlist.add("0");
                }
            });
            dataList.add(columlist);
        });
        return dataList;
    }

    /**
     * 构造表头
     * @param data
     * @return
     */
    private List<List<String>> headerList(Object data) {
        Map<String, Object> map = (Map<String, Object>) data;
        List<TdWxDict> tdWxDicts = (List<TdWxDict>) map.get("tdWxDicts");
        List<List<String>> headerList = new ArrayList<>();
        List<String> rqHeader = new ArrayList<>();
        rqHeader.add("日期");
        headerList.add(rqHeader);
        tdWxDicts.forEach(e -> {
            List<String> header = new ArrayList<>();
            header.add(e.getSceneAlias());
            headerList.add(header);
        });
        return headerList;
    }

}
