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

import java.util.ArrayList;
import java.util.List;

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 com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
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.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.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;

/**
 * 
* @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;

    @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("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());
    }

}
