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.CommonMQDTO;
import com.gic.haoban.manage.api.dto.chat.*;
import com.gic.haoban.manage.api.dto.qdto.chat.GroupChatSearchQDTO;
import com.gic.haoban.manage.api.qdto.StaffSendResultQDTO;
import com.gic.haoban.manage.api.service.HaobanCommonMQApiService;
import com.gic.haoban.manage.api.service.chat.GroupChatApiService;
import com.gic.haoban.manage.web.qo.GroupChatQO;
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.*;

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;

/**
 * 群群发计划
 */
@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 GroupChatApiService groupChatApiService ;
    @Autowired
    private MaterialApiService materialApiService;
    @Autowired
    private HaobanCommonMQApiService haobanCommonMQApiService ;


    /**
     * 群计划列表 - 分页
     * @param clerkId
     * @param wxEnterpriseId
     * @param enterpriseId
     * @param searchParams
     * @param basePageInfo
     * @param clerkTaskStatus  1待处理    2已处理/已失效
     * @return
     */
    @RequestMapping("total-list")
    public RestResponse<Page<ChatOwnerTotalDTO>> totalList(String clerkId, String wxEnterpriseId, String enterpriseId,
            String searchParams, BasePageInfo basePageInfo , @RequestParam(defaultValue = "1") int clerkTaskStatus , String storeId) {
        if (StringUtils.isEmpty(clerkId)) {
            return RestResponse.failure("1", "clerkId为空");
        }
        GroupChatPlanSearchQDTO qdto = new GroupChatPlanSearchQDTO();
        qdto.setWxEnterpriseId(wxEnterpriseId);
        qdto.setEnterpriseId(enterpriseId);
        qdto.setClerkId(clerkId);
        qdto.setStoreId(storeId);
        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);
    }

    /**
     * 好办小程序发送-群列表
     * @return
     */
    @RequestMapping("staff-group-list")
    public RestResponse<Page<GroupChatDTO>> staffGroupList(@RequestBody GroupChatQO qo) {
            logger.info("params={}",JSONObject.toJSONString(qo));
        GroupChatSearchQDTO qdto = new GroupChatSearchQDTO() ;
        qdto.setWxEnterpriseId(qo.getWxEnterpriseId());
        qdto.setStaffId(qo.getStaffId());
        qdto.setEnterpriseId(qo.getEnterpriseId());
        qdto.setSearchParams(qo.getChatName());
        qdto.setStatus(0);
        qdto.setGicFlag(1);
        if(null != qo.getOwnLogId()) {
            ServiceResponse<GroupChatPlanOwnerLogDTO> resp = this.groupChatPlanApiService.getOwnerSendInfo(qo.getOwnLogId());
            GroupChatPlanOwnerLogDTO owner = resp.getResult();
            if (null != owner && owner.getSendStatus()==2) {
                return RestResponse.successResult(new Page<>()) ;
            }
            qdto.setStaffId(owner.getStaffId());
        }
        ServiceResponse<Page<GroupChatDTO>> page = this.groupChatApiService.listPage(qdto, qo);
        return RestResponse.successResult(page.getResult());
    }


    /**
     * 好办小程序发送-成员发送结果
     * @return
     */
    @RequestMapping("staff-send-result")
    public RestResponse<Void> staffSendResult(@RequestBody StaffSendResultQDTO qdto) {
        logger.info("企微返回={}",JSONObject.toJSONString(qdto));
        this.groupChatPlanApiService.staffSendResult(qdto) ;
        return RestResponse.successResult();
    }

    /**
     * 群计划下-群主列表-分页
     * @param qdto
     * @param basePageInfo
     * @return
     */
    @RequestMapping("owner-list")
    public RestResponse<Page<GroupChatPlanOwnerLogDTO>> 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());
    }

    /**
     * 刷新群发结果
     * @param wxEnterpriseId
     * @param enterpriseId
     * @param ownerLogId
     * @return
     */
    @RequestMapping("reflush-send-msg")
    public RestResponse<GroupChatPlanOwnerLogDTO> reflush(String wxEnterpriseId, String enterpriseId, Long ownerLogId) {
        this.groupChatPlanApiService.reflushSendInfo(ownerLogId);
        ServiceResponse<GroupChatPlanOwnerLogDTO> resp = this.groupChatPlanApiService.getOwnerSendInfo(ownerLogId);
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 详情
     * @param planId
     * @param wxEnterpriseId
     * @param ownerLogId
     * @return
     */
    @RequestMapping("detail")
    public RestResponse<Map<String, 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());
                if(materialDTO.getMaterialType() == 4) {
                    materialDTO.setLink(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("clerkId",owner.getClerkId());
            ownerInfo.put("clerkName", owner.getClerkName());
            ownerInfo.put("ownerLogId", owner.getOwnerLogId());
            ownerInfo.put("sendStatus", owner.getSendStatus());
            if(owner.getSendStatus() > 0)  {
                CommonMQDTO mq = new CommonMQDTO() ;
                mq.setType(5) ;
                Map<String,String> map = new HashMap<>() ;
                map.put("ownerLogId",ownerLogId+"") ;
                mq.setParams(map);
                this.haobanCommonMQApiService.putCommonDelayMessage(mq, 15);
            }
            ownerInfo.put("dataGetTime",owner.getDataGetTime());
            retMap.put("ownerInfo", ownerInfo);
        }
        return RestResponse.successResult(retMap);
    }

    /**
     * 群主-执行的群列表-分页
     * @param planId
     * @param wxEnterpriseId
     * @param enterpriseId
     * @param ownLogId
     * @param basePageInfo
     * @return
     */
    @RequestMapping("owner-do-list")
    public RestResponse<Page<GroupChatPlanLogDTO>> ownerDoList(Long planId, String wxEnterpriseId, String enterpriseId, Long ownLogId,
            BasePageInfo basePageInfo,Integer sendStatus) {
        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);
        if(null == sendStatus) {
            sendStatus = 2 ;
        }
        qdto.setSendStatus(sendStatus);
        ServiceResponse<Page<GroupChatPlanLogDTO>> page = this.groupChatPlanApiService.listLogPage(planId, qdto,
                basePageInfo);
        return RestResponse.successResult(page.getResult());
    }


    /**
     * 获取社群群发任务数
     * @param wxEnterpriseId
     * @param enterpriseId
     * @param storeId
     * @param clerkId
     * @return
     */
    @RequestMapping("get-task-num")
    @ResponseBody
    public RestResponse<Integer> getTaskNum(String wxEnterpriseId , String enterpriseId , String storeId , String clerkId , String staffId) {
        return RestResponse.successResult(this.groupChatPlanApiService.getTaskNum(wxEnterpriseId,enterpriseId,storeId,clerkId,staffId)) ;
    }

}
