package com.gic.haoban.manage.web.controller.chat;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.ExcelUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.dto.EnterpriseDetailDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatOwnerDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatOwnerHistoryDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatUserDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.GroupChatSearchQDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.GroupChatUserSearchQDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.OwnerSearchQDTO;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.api.service.chat.GroupChatApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.log.record.anno.GicLogRecord;
import com.gic.log.record.util.GicLogRecordCategoryEnum;
import com.gic.log.record.util.GicLogRecordEvaluationContext;
import com.gic.log.record.util.GicLogRecordOptTypeEnum;
import com.gic.qcloud.BucketNameEnum;
import com.gic.web.common.download.DownloadTask;
import com.gic.web.common.download.DownloadTaskUtil;
import com.gic.web.common.download.constants.TaskTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 企微群
*
 */
@RestController
@RequestMapping("/chat")
public class GroupChatController {

    private static Logger logger = LogManager.getLogger(GroupChatController.class);

    @Autowired
    private GroupChatApiService groupChatApiService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private GroupChatUserExcelHandler groupChatUserExcelHandler;
    @Autowired
    private GroupChatUserQuitExcelHandler groupChatUserQuitExcelHandler ;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService ;

    @RequestMapping("get-set-gic-flag")
    public RestResponse<Object> getFlag() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        ServiceResponse<Boolean> resp = this.groupChatApiService.getSetGicFlag(wxEnterpriseId);
        logger.info("是否需要认领gic={},{}", resp.getResult(), wxEnterpriseId);
        return RestResponse.successResult(resp.getResult());
    }

    /**
     *
    * @Title: save
    * @Description: 认领gic
    * @author xugh
    * @return
    * @throws
     */
    @RequestMapping("set-gic-enterprise")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_CHAT, optType = GicLogRecordOptTypeEnum.HB_1001_02, userFunc = LogRecordUserServiceImpl.class, optPage = "客户群列表-客户群认领")
    public RestResponse<Object> save(@RequestBody GroupChatSearchQDTO qdto) {
        List<Long> groupChatIdList = qdto.getGroupChatIdList();
        if (CollectionUtils.isEmpty(groupChatIdList)) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("1", "请选择认领的群");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        String enterpriseId = loginUser.getEnterpriseId();
        this.groupChatApiService.updateChatEnterpriseId(wxEnterpriseId, enterpriseId, groupChatIdList);
        String logContent = "认领【" + this.getChatNames(wxEnterpriseId, groupChatIdList) + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        return RestResponse.successResult();
    }

    private String getChatNames(String wxEnterpriseId, List<Long> groupChatIdList) {
        ServiceResponse<List<GroupChatDTO>> chatResp = this.groupChatApiService.listChatByIdList(wxEnterpriseId,
                groupChatIdList);
        List<GroupChatDTO> chatList = chatResp.getResult();
        StringBuilder content = new StringBuilder();
        for (GroupChatDTO item : chatList) {
            content.append(item.getWxChatId()).append("-").append(item.getName()).append(",");
        }
        return content.toString().substring(0,content.length()-1);
    }

    @RequestMapping("page")
    public RestResponse<Object> page(@RequestBody GroupChatSearchQDTO qdto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String sortColumn = qdto.getSortColumn();
        if (StringUtils.isBlank(sortColumn)) {
            sortColumn = null;
        } else if ("totalCount".equals(sortColumn)) {
            sortColumn = "total_count";
        } else if ("totalMemberCount".equals(sortColumn)) {
            sortColumn = "total_member_count";
        } else if ("addMemberCount".equals(sortColumn)) {
            sortColumn = "add_member_count";
        } else if ("addCount".equals(sortColumn)) {
            sortColumn = "add_count";
        } else if ("quitCount".equals(sortColumn)) {
            sortColumn = "quit_count";
        } else if ("quitMemberCount".equals(sortColumn)) {
            sortColumn = "quit_member_count";
        }
        BasePageInfo basePageInfo = new BasePageInfo() ;
        basePageInfo.setPageNum(qdto.getPageNum());
        basePageInfo.setPageSize(qdto.getPageSize());
        qdto.setSortColumn(sortColumn);
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        ServiceResponse<Page<GroupChatDTO>> page = this.groupChatApiService.listPage(qdto, basePageInfo);
        return RestResponse.successResult(page.getResult());
    }

    @RequestMapping("user/page")
    public RestResponse<Object> userPage(GroupChatUserSearchQDTO qdto, BasePageInfo basePageInfo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        ServiceResponse<Page<GroupChatUserDTO>> page = this.groupChatApiService.listUserPage(qdto, basePageInfo);
        return RestResponse.successResult(page.getResult());
    }

    /**
     * 群详情导出
     */
    @RequestMapping("user/detail/excel")
    public RestResponse<String> detailExcel(@RequestBody GroupChatUserSearchQDTO qdto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        BasePageInfo basePageInfo = new BasePageInfo() ;
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(1);
        ServiceResponse<Page<GroupChatUserDTO>> resp = this.groupChatApiService.listUserPage(qdto, basePageInfo);
        List<GroupChatUserDTO> list = resp.getResult().getResult() ;
        if(CollectionUtils.isEmpty(list)) {
            return RestResponse.failure("9999","无群成员数据");
        }
        Long groupChatId = qdto.getGroupChatId() ;
        int  totalCount = resp.getResult().getTotalCount();
        ServiceResponse<GroupChatDTO>  detailResp = this.groupChatApiService.detail(loginUser.getWxEnterpriseId(),groupChatId);
        String s = DateUtil.formatString(new Date(), DateUtil.FORMAT_DATE_10);
        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        String fileName = "客户群成员-"+detailResp.getResult().getName()+"-"+s;
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_GROUP_CHAT_USER);
        task.setUser(user);
        task.setDataType(qdto.getDataType());
        task.setTotalCount(totalCount);
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_GROUP_CHAT_USER.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(groupChatUserExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999", jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }


    @RequestMapping("user/quit/excel")
    public RestResponse<String> excel(@RequestBody GroupChatUserSearchQDTO qdto) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        Date startDate = qdto.getStartDate() ;
        Date endDate = qdto.getEndDate() ;
        if(null == startDate || null == endDate) {
            return RestResponse.failure("9999","时间不能为空");
        }
        if(DateUtil.daysBetween(startDate,endDate) >= 180) {
            return RestResponse.failure("9999","导出区间不能超过半年");
        }
        qdto.setStatus(2);
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageSize(1);
        basePageInfo.setPageNum(1);
        ServiceResponse<Page<GroupChatUserDTO>> resp = this.groupChatApiService.listUserPage(qdto, basePageInfo);
        List<GroupChatUserDTO> list = resp.getResult().getResult() ;
        if(CollectionUtils.isEmpty(list)) {
            return RestResponse.failure("9999","无群成员数据");
        }

        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        String s = DateUtil.formatString(new Date(), DateUtil.FORMAT_DATE_10);
        String fileName = "退群记录"+s;
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_GROUP_CHAT_USER);
        task.setUser(user);
        task.setDataType(qdto.getDataType());
        task.setTotalCount(resp.getResult().getTotalCount());
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_GROUP_CHAT_USER.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(groupChatUserQuitExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999", jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }


    @RequestMapping("detail")
    public RestResponse<Object> detail(Long groupChatId) {
        if (null == groupChatId) {
            return RestResponse.failure("1", "群ID空");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        ServiceResponse<GroupChatDTO> resp = this.groupChatApiService.detail(loginUser.getWxEnterpriseId(),
                groupChatId);
        if (!resp.isSuccess()) {
            return RestResponse.failure("1", "群不存在");
        }
        GroupChatDTO dto = resp.getResult();
        return RestResponse.successResult(dto);
    }

    @RequestMapping("owner-page")
    public RestResponse<Object> ownerPage(OwnerSearchQDTO qdto, BasePageInfo basePageInfo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        // 是否需要显示门店名称
        String paramsEnterpriseId = qdto.getParamsEnterpriseId() ;
        if(StringUtils.isNotBlank(paramsEnterpriseId)) {
            qdto.setShowStoreNames(1);
        }else {
            List<EnterpriseDetailDTO> list = this.wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(loginUser.getWxEnterpriseId(),loginUser.getPhoneNumber(),false) ;
            if(CollectionUtils.isEmpty(list)) {
                return RestResponse.failure("-1", "未关联gic商户");
            }
            if(list.size()==1) {
              qdto.setShowStoreNames(1);
            }
            qdto.setParamsEnterpriseId(list.get(0).getEnterpriseId());
        }
        ServiceResponse<Page<GroupChatOwnerDTO>> resp = this.groupChatApiService.listOwnerPage(qdto, basePageInfo);
        return RestResponse.successResult(resp.getResult());
    }

    @RequestMapping("owner-history")
    public RestResponse<Object> ownerHistory(Long groupChatId) {
        if (null == groupChatId) {
            return RestResponse.failure("1", "群ID空");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        ServiceResponse<List<GroupChatOwnerHistoryDTO>> resp = this.groupChatApiService.listOwnerHistory(groupChatId,
                wxEnterpriseId);
        return RestResponse.successResult(resp.getResult());
    }

    @RequestMapping("transfer")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_CHAT, optType = GicLogRecordOptTypeEnum.HB_1001_01, userFunc = LogRecordUserServiceImpl.class, optPage = "客户群列表")
    public RestResponse<Object> transfer(String staffId, String groupChatIdList) {
        if (StringUtils.isEmpty(staffId)) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("1", "请选择继承的群主");
        }
        if (StringUtils.isEmpty(groupChatIdList)) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("1", "请选择继承的群");
        }
        String[] arr = groupChatIdList.split(",");
        List<Long> idList = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            if (StringUtils.isNotBlank(arr[i])) {
                idList.add(Long.valueOf(arr[i]));
            }
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        ServiceResponse<Void> resp = this.groupChatApiService.transfer(wxEnterpriseId, staffId, idList);
        if(!resp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", resp.getMessage());
        }
        StaffDTO staff = this.staffApiService.selectById(staffId);
        String logContent = "将【" + this.getChatNames(wxEnterpriseId, idList) + "】分配给【" + staff.getStaffName() + "】继承";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        return RestResponse.successResult(resp.getResult());
    }
    /**
     * 客户群列表数据明细导出
     */
    @RequestMapping("customer-group-export")
    public RestResponse<Boolean> customerGroupExport(HttpServletRequest request, HttpServletResponse response,@RequestBody GroupChatSearchQDTO qdto) {
        // 登录校验
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (loginUser == null || StringUtils.isBlank(loginUser.getEnterpriseId())) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_4.getCode()), HaoBanErrCode.ERR_4.getMsg());
        }
        String sortColumn = qdto.getSortColumn();
        if (StringUtils.isBlank(sortColumn)) {
            sortColumn = null;
        } else if ("totalCount".equals(sortColumn)) {
            sortColumn = "total_count";
        } else if ("totalMemberCount".equals(sortColumn)) {
            sortColumn = "total_member_count";
        } else if ("addMemberCount".equals(sortColumn)) {
            sortColumn = "add_member_count";
        } else if ("addCount".equals(sortColumn)) {
            sortColumn = "add_count";
        } else if ("quitCount".equals(sortColumn)) {
            sortColumn = "quit_count";
        } else if ("quitMemberCount".equals(sortColumn)) {
            sortColumn = "quit_member_count";
        }
        BasePageInfo basePageInfo = new BasePageInfo() ;
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(99999);
        qdto.setSortColumn(sortColumn);
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        ServiceResponse<Page<GroupChatDTO>> page = this.groupChatApiService.listPage(qdto, basePageInfo);
        if (page.isSuccess() && CollUtil.isNotEmpty(page.getResult().getResult())){
            String fileName = "客户群列表数据";
            List<String> titleList = Arrays.asList("客户群ID", "企微群ID","客户群名称", "群人数", "群客户数", "新增总数", "流失总数","群主","群主在好办小程序关联状态","门店名称","门店code","创建时间");
            List<String> fileList = Arrays.asList("groupChatId", "wxChatId", "name", "totalCount", "totalMemberCount", "addCount", "quitCount", "staffName", "clerkRelationExcel", "ownerStoreName","ownerStoreCode", "createTime");
            try {
                ExcelUtils.xls(response, request, fileName, page.getResult().getResult(), fileList, titleList);
            } catch (Exception e) {
                logger.info("异常",e);
                logger.info("导出失败");
            }
            return RestResponse.successResult(true);
        }
        return RestResponse.successResult(false);
    }

}
