package com.ruoyi.web.controller.wocom;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.excel.wecom.domain.CorpDepartment;
import com.ruoyi.excel.wecom.domain.CorpUser;
import com.ruoyi.excel.wecom.helper.HandleAllData;
import com.ruoyi.excel.wecom.mapper.CustomerExportDataMapper;
import com.ruoyi.excel.wecom.mapper.CustomerStatisticsDataMapper;
import com.ruoyi.excel.wecom.mapper.DepartmentStatisticsDataMapper;
import com.ruoyi.excel.wecom.model.WecomConfig;
import com.ruoyi.excel.wecom.model.WecomCustomer;
import com.ruoyi.excel.wecom.model.WecomTagGroup;
import com.ruoyi.excel.wecom.service.CustomerExportService;
import com.ruoyi.excel.wecom.service.WecomContactService;
import com.ruoyi.excel.wecom.service.WecomTagService;
import com.ruoyi.excel.wecom.vo.CustomerExportDataVO;
import com.ruoyi.excel.wecom.vo.CustomerStatisticsDataVO;
import com.ruoyi.excel.wecom.vo.DepartmentStatisticsDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 企业微信客户联系Controller
 */
@RestController
@RequestMapping("/wecom/contact")
public class WecomContactController {
    @Autowired
    private WecomTagService wecomTagService;

    @Autowired
    private HandleAllData handleAllData;

    @Autowired
    private CustomerExportService customerExportService;

    @Autowired
    private CustomerExportDataMapper customerExportDataMapper;

    @Autowired
    private DepartmentStatisticsDataMapper departmentStatisticsDataMapper;

    @Autowired
    private CustomerStatisticsDataMapper customerStatisticsDataMapper;
    /**
     * 获取配置了客户联系功能的成员列表
     *
     * @param request HttpServletRequest
     * @return AjaxResult
     */
    @GetMapping("/followUserList")
    public AjaxResult getFollowUserList(HttpServletRequest request) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            List<String> userList = contactService.getFollowUserList();
            return AjaxResult.success("获取成功", userList);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定成员的客户列表
     *
     * @param request HttpServletRequest
     * @param userid  成员ID
     * @return AjaxResult
     */
    @GetMapping("/externalContactList")
    public AjaxResult getExternalContactList(HttpServletRequest request, @RequestParam String userid) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            List<String> customerList = contactService.getExternalContactList(userid);
            return AjaxResult.success("获取成功", customerList);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有成员的客户列表
     *
     * @param request HttpServletRequest
     * @return AjaxResult
     */
    @GetMapping("/allMembersCustomers")
    public AjaxResult getAllMembersCustomers(HttpServletRequest request) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            List<WecomContactService.MemberCustomer> memberCustomerList = contactService.getAllMembersCustomers();
            return AjaxResult.success("获取成功", memberCustomerList);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 批量获取客户详情
     *
     * @param request   HttpServletRequest
     * @return AjaxResult
     */
    @PostMapping("/batchCustomerDetails")
    public AjaxResult batchGetCustomerDetails(HttpServletRequest request, @RequestBody List<String> useridList) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            
            // 解析成员ID列表
            List<WecomCustomer> customerList = contactService.batchGetAllCustomerDetails(useridList);
            
            return AjaxResult.success("获取成功", customerList);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个客户详情
     *
     * @param request        HttpServletRequest
     * @param externalUserid 外部联系人ID
     * @return AjaxResult
     */
    @GetMapping("/customerDetail")
    public AjaxResult getCustomerDetail(HttpServletRequest request, @RequestParam String externalUserid) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            WecomCustomer customer = contactService.getCustomerDetail(externalUserid);
            return AjaxResult.success("获取成功", customer);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取企业标签库
     *
     * @param request HttpServletRequest
     * @return AjaxResult
     */
    @GetMapping("/corpTagList")
    public AjaxResult getCorpTagList(HttpServletRequest request) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            List<WecomTagGroup> tagGroupList = contactService.getCorpTagList();

            // 同步标签库到数据库
            boolean syncResult = wecomTagService.syncCorpTagList(tagGroupList);
            if (syncResult) {
                return AjaxResult.success("获取成功并同步到数据库", tagGroupList);
            } else {
                return AjaxResult.success("获取成功但同步到数据库失败", tagGroupList);
            }
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取企业微信配置
     *
     * @param request HttpServletRequest
     * @return WecomConfig
     */
    private WecomConfig getWecomConfig(HttpServletRequest request) {
        // 这里可以从请求参数、配置文件或数据库中获取配置
        // 暂时使用硬编码的方式，实际使用时应该从配置中获取
        WecomConfig config = new WecomConfig();
        return config;
    }

    /**
     * 获取子部门id列表
     *
     * @param request HttpServletRequest
     * @param departmentId 部门ID，根部门传1
     * @return AjaxResult
     */
    @GetMapping("/departmentList")
    public AjaxResult getDepartmentList(HttpServletRequest request, @RequestParam(required = false) Long departmentId) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            List<CorpDepartment> deptIdList = contactService.getDepartmentList(departmentId);
            return AjaxResult.success("获取成功", deptIdList);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个部门详情
     *
     * @param request HttpServletRequest
     * @param departmentId 部门ID
     * @return AjaxResult
     */
    @GetMapping("/departmentDetail")
    public AjaxResult getDepartmentDetail(HttpServletRequest request, @RequestParam Long departmentId) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            Object deptDetail = contactService.getDepartmentDetail(departmentId);
            return AjaxResult.success("获取成功", deptDetail);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取部门成员详情
     *
     * @param request HttpServletRequest
     * @param departmentId 部门ID
     * @param fetchChild 是否递归获取子部门成员
     * @param status 成员状态，0-全部，1-已激活，2-已禁用，4-未激活，5-退出企业
     * @return AjaxResult
     */
    @GetMapping("/departmentMemberList")
    public AjaxResult getDepartmentMemberList(HttpServletRequest request, @RequestParam Long departmentId, 
                                              @RequestParam(required = false) Integer fetchChild, 
                                              @RequestParam(required = false) Integer status) {
        try {
            WecomConfig config = getWecomConfig(request);
            WecomContactService contactService = new WecomContactService(config);
            List<CorpUser> memberList = contactService.getDepartmentMemberList(departmentId, fetchChild, status);
            return AjaxResult.success("获取成功", memberList);
        } catch (IOException e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    @GetMapping("/init")
    public AjaxResult init(HttpServletRequest request) throws IOException {
        handleAllData.initData();
        return AjaxResult.success();
    }

    @GetMapping("/test")
    public AjaxResult test(HttpServletRequest request) throws IOException {
        handleAllData.handleAllData();
        return AjaxResult.success();
    }

    @GetMapping("/createAllReportData")
    public AjaxResult createAllReportData(HttpServletRequest request) throws IOException {
        handleAllData.createAllReportData();
        return AjaxResult.success();
    }

    @GetMapping("/createAllDepartmentReportData")
    public AjaxResult createAllDepartmentReportData(HttpServletRequest request) throws IOException {
        handleAllData.createAllDepartmentReportData();
        return AjaxResult.success();
    }

    @GetMapping("/createAllDepartmentReportByDate")
    public AjaxResult createAllDepartmentReportByDate(@RequestParam(value = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) throws IOException {
        handleAllData.createDepartmentReportData(date);
        return AjaxResult.success();
    }

    /**
     * 导出客户数据
     *
     * @param response HttpServletResponse
     * @param startDate 开始日期(可选)
     * @param endDate 结束日期(可选)
     */
    @GetMapping("/exportCustomerData")
    public void exportCustomerData(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("客户数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel流式导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), CustomerExportDataVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("客户数据").build();

            // 分批查询并写入,避免内存溢出
            List<CustomerExportDataVO> dataList = customerExportDataMapper.selectCustomerExportDataVOList(startDate, endDate,null);
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println("{\"code\":500,\"msg\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 导出流量看板统计数据
     *
     * @param response HttpServletResponse
     * @param startDate 开始日期(可选)
     * @param endDate 结束日期(可选)
     * @param indicatorName 指标(可选)
     */
    @GetMapping("/exportCustomerStatistics")
    public void exportCustomerStatistics(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String indicatorName) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("部门统计数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel流式导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), CustomerStatisticsDataVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("流量看板统计数据").build();

            // 分批查询并写入,避免内存溢出
            List<CustomerStatisticsDataVO> dataList = customerStatisticsDataMapper.selectCustomerStatisticsDataVOList(
                    startDate, endDate, indicatorName);
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println("{\"code\":500,\"msg\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 导出部门统计数据
     *
     * @param response HttpServletResponse
     * @param startDate 开始日期(可选)
     * @param endDate 结束日期(可选)
     * @param departmentPath 部门路径(可选)
     */
    @GetMapping("/exportDepartmentStatistics")
    public void exportDepartmentStatistics(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String departmentPath) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("部门统计数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel流式导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DepartmentStatisticsDataVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("部门统计数据").build();

            // 分批查询并写入,避免内存溢出
            List<DepartmentStatisticsDataVO> dataList = departmentStatisticsDataMapper.selectDepartmentStatisticsDataVOList(
                    startDate, endDate, departmentPath);
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println("{\"code\":500,\"msg\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
