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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.ExcelUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
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.chat.GroupChatApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.haoban.manage.web.vo.chat.GroupChatUserQuitVO;
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 org.apache.commons.collections.ArrayStack;
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.RequestParam;
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;

/**
 *
* @ClassName: GroupChatController
* @Description: 群
* @author xugh
* @date 2022年11月26日 上午9:32:56
*
 */
@RestController
@RequestMapping("/chat")
public class GroupChatController {

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

    @Autowired
    private GroupChatApiService groupChatApiService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private EnterpriseService enterpriseService;

    @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
    * @param groupChatIdList
    * @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/quit/excel")
    public RestResponse<Boolean> excel(HttpServletRequest request, HttpServletResponse response,String searchParams,Integer userType,
                                       Date startDate,Date endDate,@RequestParam(defaultValue = "2") Integer status) {
        GroupChatUserSearchQDTO qdto = new GroupChatUserSearchQDTO();
        BasePageInfo basePageInfo = new BasePageInfo();
        int pageNum = 1;
        int pageSize = 1000;
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        qdto.setSearchParams(searchParams);
        qdto.setUserType(userType);
        qdto.setStartDate(startDate);
        qdto.setEndDate(endDate);
        qdto.setStatus(status);
        basePageInfo.setPageSize(pageSize);
        List<GroupChatUserDTO> result = new ArrayList<>();
        while (true) {
            basePageInfo.setPageNum(pageNum);
            ServiceResponse<Page<GroupChatUserDTO>> page = this.groupChatApiService.listUserPage(qdto, basePageInfo);
            List<GroupChatUserDTO> list = page.getResult().getResult();
            if (CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            pageNum++;
        }
        if (CollUtil.isNotEmpty(result)){
            List<GroupChatUserQuitVO> voList = new ArrayList<>() ;
            for (GroupChatUserDTO dto : result) {
                GroupChatUserQuitVO vo = EntityUtil.changeEntityByJSON(GroupChatUserQuitVO.class,dto) ;
                vo.setUserQuitTimeExcel(DateUtil.dateToStr(dto.getUserQuitTime(),"yyyy-MM-dd HH:mm:ss"));
                if(dto.getUserType()==1) {
                    vo.setUserTypeExcel("企业成员");
                }else if(dto.getUserType()==2) {
                    vo.setUserTypeExcel("外部成员");
                }else {
                    vo.setUserTypeExcel("客户");
                }
                voList.add(vo) ;
            }
            String s = DateUtil.formatString(new Date(), DateUtil.FORMAT_DATE_10);
            String fileName = "退群记录"+s;
            List<String> titleList = Arrays.asList("群成员姓名", "群成员昵称", "身份", "群名称", "群主", "退群时间");
            List<String> fileList = Arrays.asList("userName","nickName","userTypeExcel", "chatName", "staffName", "userQuitTimeExcel");
            try {
                ExcelUtils.xls(response, request, fileName, voList, fileList, titleList);
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("导出失败");
            }
            return RestResponse.successResult(true);
        }
        return RestResponse.successResult(false);
    }


    @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());
        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,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", "客户群名称", "群人数", "群客户数", "新增总数", "流失总数","群主","群主在好办小程序关联状态","创建时间");
            List<String> fileList = Arrays.asList("groupChatId", "name", "totalCount", "totalMemberCount", "addCount", "quitCount", "staffName", "clerkRelationExcel", "createTime");
            try {
                ExcelUtils.xls(response, request, fileName, page.getResult().getResult(), fileList, titleList);
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("导出失败");
            }
            return RestResponse.successResult(true);
        }
        return RestResponse.successResult(false);
    }

}
