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

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.gic.haoban.manage.api.dto.chat.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.manage.api.dto.MaterialDTO;
import com.gic.haoban.manage.api.dto.qdto.chat.GroupChatPlanSearchQDTO;
import com.gic.haoban.manage.api.service.MaterialApiService;
import com.gic.haoban.manage.api.service.chat.GroupChatPlanApiService;

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

    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(GroupChatPlanController.class);

    @Autowired
    private GroupChatPlanApiService groupChatPlanApiService;
    @Autowired
    private MaterialApiService materialApiService;

    // clerkTaskStatus  1待处理    2已处理/已失效
    @RequestMapping("total-list")
    public RestResponse<Object> totalList(String clerkId, String wxEnterpriseId, String enterpriseId,
            String searchParams, BasePageInfo basePageInfo , @RequestParam(defaultValue = "1") int clerkTaskStatus) {
        if (StringUtils.isEmpty(clerkId)) {
            return RestResponse.failure("1", "clerkId为空");
        }
        GroupChatPlanSearchQDTO qdto = new GroupChatPlanSearchQDTO();
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setEnterpriseId(enterpriseId);
        qdto.setClerkId(clerkId);
        if (StringUtils.isNotBlank(searchParams)) {
            qdto.setSearchParams("%" + searchParams + "%");
        }
        qdto.setClerkTaskStatus(clerkTaskStatus);
        ServiceResponse<Page<ChatOwnerTotalDTO>> pageResp = this.groupChatPlanApiService
                .listOwnerLogPageForWxaTotal(qdto, basePageInfo);
        Page<ChatOwnerTotalDTO> page = pageResp.getResult();
        if (null != page.getResult()) {
            page.getResult().forEach(dto -> {
                if (dto.getEndTime().before(new Date())) {
                    dto.setPlanStatus(2);
                } else {
                    dto.setPlanStatus(1);
                }
            });
        }
        return RestResponse.successResult(page);
    }

    @RequestMapping("owner-list")
    public RestResponse<Object> ownerList(GroupChatPlanSearchQDTO qdto, BasePageInfo basePageInfo) {
        if (null == qdto.getPlanId()) {
            return RestResponse.failure("1", "planid为空");
        }
        ServiceResponse<Page<GroupChatPlanOwnerLogDTO>> page = this.groupChatPlanApiService.listOwnerLogPageForWxa(qdto,
                basePageInfo);
        return RestResponse.successResult(page.getResult());
    }

    @RequestMapping("reflush-send-msg")
    public RestResponse<Object> reflush(String wxEnterpriseId, String enterpriseId, Long ownerLogId) {
        this.groupChatPlanApiService.reflushSendInfo(ownerLogId);
        ServiceResponse<GroupChatPlanOwnerLogDTO> resp = this.groupChatPlanApiService.getOwnerSendInfo(ownerLogId);
        return RestResponse.successResult(resp.getResult());
    }

    @RequestMapping("detail")
    public RestResponse<Object> detail(Long planId, String wxEnterpriseId, Long ownerLogId) {
        if (null == planId) {
            return RestResponse.failure("1", "planid为空");
        }
        ServiceResponse<GroupChatPlanDTO> linkResp = this.groupChatPlanApiService.detail(planId);
        if (!linkResp.isSuccess() || null == linkResp.getResult()) {
            return RestResponse.failure("1", "计划不存在");
        }
        GroupChatPlanDTO plan = linkResp.getResult();
        String content = plan.getChatContent();
        // 查询素材列表
        List<MaterialDTO> materials = new ArrayList<>();
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("plan", plan);
        Integer materialFrom = plan.getMaterialFrom();
        if (materialFrom == null || materialFrom == 1) {
            JSONArray array = JSONArray.parseArray(content);
            List<String> materialIdList = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject json = array.getJSONObject(i);
                materialIdList.add(json.getString("relation_id"));
            }
            materials = materialApiService.listMaterialByIds(materialIdList);
        }else {
            List<ChatContentDTO> contentDTOList = JSONArray.parseArray(content, ChatContentDTO.class);
            materials = contentDTOList.stream().map(x -> {
                MaterialDTO materialDTO = new MaterialDTO();
                materialDTO.setMaterialType(x.getType());
                materialDTO.setMaterialContent(x.getContent());
                materialDTO.setImgUrl(x.getImg());
                return materialDTO;
            }).collect(Collectors.toList());
        }
        retMap.put("materialList", materials);
        if (null != ownerLogId) {
            ServiceResponse<GroupChatPlanOwnerLogDTO> resp = this.groupChatPlanApiService.getOwnerSendInfo(ownerLogId);
            GroupChatPlanOwnerLogDTO owner = resp.getResult();
            if (!resp.isSuccess() || null == owner) {
                return RestResponse.failure("1", "记录不存在");
            }
            Map<String, Object> ownerInfo = new HashMap<>();
            ownerInfo.put("clerkName", owner.getClerkName());
            ownerInfo.put("ownerLogId", owner.getOwnerLogId());
            ownerInfo.put("sendStatus", owner.getSendStatus());
            retMap.put("ownerInfo", ownerInfo);
        }
        return RestResponse.successResult(retMap);
    }

    @RequestMapping("owner-do-list")
    public RestResponse<Object> ownerDoList(Long planId, String wxEnterpriseId, String enterpriseId, Long ownLogId,
            BasePageInfo basePageInfo) {
        if (null == planId || null == ownLogId) {
            return RestResponse.failure("1", "参数未传");
        }
        GroupChatPlanSearchQDTO qdto = new GroupChatPlanSearchQDTO();
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setEnterpriseId(enterpriseId);
        qdto.setPlanId(planId);
        qdto.setOwnLogId(ownLogId);
        ServiceResponse<Page<GroupChatPlanLogDTO>> page = this.groupChatPlanApiService.listLogPage(planId, qdto,
                basePageInfo);
        return RestResponse.successResult(page.getResult());
    }

}
