package com.huiju.estateagents.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.common.DateUtils;
import com.huiju.estateagents.common.ExcelUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.excel.ConsultantKPIExport;
import com.huiju.estateagents.excel.TaActivityDynamicEnlistExport;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.huiju.estateagents.service.ITsConsultantKpiService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 置业顾问KPI  前端控制器
 * </p>
 *
 * @author yansen
 * @since 2020-04-14
 */
@RestController
@RequestMapping("/api/admin/stats")
public class TsConsultantKpiController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TsConsultantKpiController.class);

    @Autowired
    public ITsConsultantKpiService iTsConsultantKpiService;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @param startDate
     * @param endDate
     * @param buildingId
     * @param asc
     * @param desc
     * @param request
     * @return
     */
    @RequestMapping(value = "/consultant/kpi", method = RequestMethod.GET)
    public ResponseBean stsConsultantKpiList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             // startDate 默认格式 YYYYMMDD
                                             @RequestParam(value = "startDate", required = false) String startDate,
                                             @RequestParam(value = "endDate", required = false) String endDate,
                                             @RequestParam(value = "buildingId", required = false) String buildingId,
                                             @RequestParam(value = "asc", required = false) String asc,
                                             @RequestParam(value = "desc", required = false) String desc,
                                             @RequestParam(value = "org", required = false) String org,
                                             HttpServletRequest request) {
        if (null == startDate || "".equals(startDate)) {
            return ResponseBean.error("开始日期不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        if (null == endDate || "".equals(endDate)) {
            endDate = DateUtils.today();
        }

        Integer orgId = StringUtils.isEmpty(org) ? getOrgId(request) : Integer.valueOf(org);
        Integer userId = getUserId(request);
        try {
            // 汇总明细
            IPage<TsConsultantKpi> result = iTsConsultantKpiService.stsKPIDaily(pageNum, pageSize, orgId, userId, buildingId, startDate, endDate, StringUtils.humpToLine(asc), StringUtils.humpToLine(desc));
            // 汇总
            TsConsultantKpi total = iTsConsultantKpiService.stsKPITotalByOrg(orgId, userId, buildingId, startDate, endDate);
            return ResponseBean.success(new HashMap<String, Object>() {{
                put("paged", result);
                put("total", total);
            }});
        } catch (Exception e) {
            logger.error("stsConsultantKpiList 异常：", e);
            return ResponseBean.error("查询出错, 请重试 : " + e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }


    /**
     * 导出
     *
     * @param startDate
     * @param endDate
     * @param buildingId
     * @param request
     * @return
     */
    @RequestMapping(value = "/consultant/kpi", method = RequestMethod.POST)
    public ResponseBean stsConsultantKpiExport(// startDate 默认格式 YYYYMMDD
                                               @RequestParam(value = "startDate", required = false) String startDate,
                                               @RequestParam(value = "endDate", required = false) String endDate,
                                               @RequestParam(value = "buildingId", required = false) String buildingId,
                                               HttpServletRequest request,
                                               HttpServletResponse response
    ) {
        if (null == startDate || "".equals(startDate)) {
            return ResponseBean.error("开始日期不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        if (null == endDate || "".equals(endDate)) {
            endDate = DateUtils.today();
        }

        Integer orgId = getOrgId(request);
        Integer userId = getUserId(request);
        try {

            // 汇总明细
            List<ConsultantKPIExport> result = iTsConsultantKpiService.stsKPIDailyExport(orgId, userId, buildingId, startDate, endDate);
            ExcelUtils.flush(response, ConsultantKPIExport.class, result, "置业顾问KPI统计" + DateUtils.today());
        } catch (Exception e) {
//            e.printStackTrace();
            return ResponseBean.error("导出Excel出错, 请重试 : " + e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }

        return null;
    }

    private LocalDateTime[] getLocalTimeRangeBy(String startDate, String endDate) throws Exception {
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;

        if (!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
            if (startDate.length() != 8 && endDate.length() != 8) {
                throw new Exception("日期格式必须为YYYYMMDD");
            }

            startTime = DateUtils.day2LocalDateime(startDate.substring(0, 4) + "-" + startDate.substring(4, 6) + "-" + startDate.substring(6, 8));
            endTime = DateUtils.dayToLocalDateime(endDate.substring(0, 4) + "-" + endDate.substring(4, 6) + "-" + endDate.substring(6, 8) + " 23:59:59");
        }

        return new LocalDateTime[]{startTime, endTime};
    }

    /**
     * 查询置业的客户
     * startDate 存在则统计新增客户, 不存在则统计所有
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/customer")
    public ResponseBean getConsultantCustomers(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                               @RequestParam(value = "buildingId", required = false) String buildingId,
                                               @RequestParam(value = "userId") String userId,
                                               @RequestParam(value = "startDate", required = false) String startDate,
                                               @RequestParam(value = "endDate", required = false) String endDate,
                                               HttpServletRequest request
    ) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaRecommendCustomer> page = new Page<>(pageNum, pageSize);
        IPage<TaRecommendCustomer> result = iTsConsultantKpiService.getCustomerListOfConsultant(page, orgId, userId, buildingId, dateRange[0], dateRange[1]);
        return ResponseBean.success(result);
    }

    /**
     * 置业分享拓客
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/share/customer")
    public ResponseBean getConsultantShareCustomers(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                    @RequestParam(value = "buildingId", required = false) String buildingId,
                                                    @RequestParam(value = "userId") String userId,
                                                    @RequestParam(value = "startDate", required = false) String startDate,
                                                    @RequestParam(value = "endDate", required = false) String endDate,
                                                    HttpServletRequest request) {

        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantShareCustomers(page, orgId, userId, buildingId, dateRange[0], dateRange[1]);
        return ResponseBean.success(result);
    }

    /**
     * 置业首页访问人数
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/homepage/persons")
    public ResponseBean getConsultantHomePagePersons(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                     @RequestParam(value = "buildingId", required = false) String buildingId,
                                                     @RequestParam(value = "userId") String userId,
                                                     @RequestParam(value = "startDate", required = false) String startDate,
                                                     @RequestParam(value = "endDate", required = false) String endDate,
                                                     HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantHomePagePersons(page, orgId, userId, buildingId, dateRange[0], dateRange[1]);
        return ResponseBean.success(result);
    }

    /**
     * 置业首页访问次数
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/homepage/times")
    public ResponseBean getConsultantHomePageTimes(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                   @RequestParam(value = "buildingId", required = false) String buildingId,
                                                   @RequestParam(value = "userId") String userId,
                                                   @RequestParam(value = "startDate", required = false) String startDate,
                                                   @RequestParam(value = "endDate", required = false) String endDate,
                                                   @RequestParam(value = "personId", required = false) String personId,
                                                   HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantHomePageTimes(page, orgId, userId, buildingId, dateRange[0], dateRange[1], personId);
        return ResponseBean.success(result);
    }

    /**
     * 咨询置业次数
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/chat/persons")
    public ResponseBean getConsultantChatPersons(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                 @RequestParam(value = "buildingId", required = false) String buildingId,
                                                 @RequestParam(value = "userId") String userId,
                                                 @RequestParam(value = "startDate", required = false) String startDate,
                                                 @RequestParam(value = "endDate", required = false) String endDate,
                                                 HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantChatPersons(page, orgId, userId, buildingId, dateRange[0], dateRange[1]);
        return ResponseBean.success(result);
    }

    /**
     * 点赞详情
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/favor")
    public ResponseBean getConsultantFavor(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           @RequestParam(value = "buildingId", required = false) String buildingId,
                                           @RequestParam(value = "userId") String userId,
                                           @RequestParam(value = "startDate", required = false) String startDate,
                                           @RequestParam(value = "endDate", required = false) String endDate,
                                           HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantFavor(page, orgId, userId, buildingId, dateRange[0], dateRange[1]);
        return ResponseBean.success(result);
    }

    /**
     * 置业分享次数
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param targetType
     * @param targetName
     * @param request
     * @return
     */
    @GetMapping("/consultant/share/targets")
    public ResponseBean getConsultantShareTargets(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                  @RequestParam(value = "buildingId", required = false) String buildingId,
                                                  @RequestParam(value = "userId") String userId,
                                                  @RequestParam(value = "startDate", required = false) String startDate,
                                                  @RequestParam(value = "endDate", required = false) String endDate,
                                                  @RequestParam(value = "targetType", required = false) String targetType,
                                                  @RequestParam(value = "targetName", required = false) String targetName,
                                                  HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantShareTargets(page, orgId, userId, buildingId, dateRange[0], dateRange[1], targetType, targetName);
        return ResponseBean.success(result);
    }

    /**
     * 置业分享访问人数
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param request
     * @return
     */
    @GetMapping("/consultant/share/persons")
    public ResponseBean getConsultantSharePersons(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                  @RequestParam(value = "buildingId", required = false) String buildingId,
                                                  @RequestParam(value = "userId") String userId,
                                                  @RequestParam(value = "startDate", required = false) String startDate,
                                                  @RequestParam(value = "endDate", required = false) String endDate,
                                                  HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantSharePersons(page, orgId, userId, buildingId, dateRange[0], dateRange[1]);
        return ResponseBean.success(result);
    }

    /**
     * 置业分享访问次数
     *
     * @param pageNum
     * @param pageSize
     * @param buildingId
     * @param userId
     * @param startDate
     * @param endDate
     * @param targetType
     * @param targetName
     * @param request
     * @return
     */
    @GetMapping("/consultant/share/times")
    public ResponseBean getConsultantShareTimes(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "buildingId", required = false) String buildingId,
                                                @RequestParam(value = "userId") String userId,
                                                @RequestParam(value = "startDate", required = false) String startDate,
                                                @RequestParam(value = "endDate", required = false) String endDate,
                                                @RequestParam(value = "targetType", required = false) String targetType,
                                                @RequestParam(value = "targetName", required = false) String targetName,
                                                @RequestParam(value = "userName", required = false) String userName,
                                                @RequestParam(value = "personId", required = false) String personId,
                                                HttpServletRequest request) {
        LocalDateTime[] dateRange = {null, null};
        try {
            dateRange = getLocalTimeRangeBy(startDate, endDate);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        // 如果 personId 与 userName 同时存在, 以 personId 为准
        if (!StringUtils.isEmpty(personId)) {
            userName = null;
        }

        Integer orgId = getOrgId(request);
        IPage<TaPerson> page = new Page<>(pageNum, pageSize);
        IPage<TaPerson> result = iTsConsultantKpiService.getConsultantShareTimes(page, orgId, userId, buildingId, dateRange[0], dateRange[1], targetType, targetName, userName, personId);
        return ResponseBean.success(result);
    }


}
