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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.gic.haoban.manage.api.dto.chat.ChatContentDTO;
import org.apache.commons.collections.CollectionUtils;
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.RequestBody;
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.JSON;
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.util.DateUtil;
import com.gic.commons.util.EntityUtil;
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.MaterialDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatPlanDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatPlanLogDTO;
import com.gic.haoban.manage.api.dto.chat.GroupChatPlanOwnerLogDTO;
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.StaffApiService;
import com.gic.haoban.manage.api.service.chat.GroupChatPlanApiService;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.haoban.manage.web.utils.CreatorUtils;
import com.gic.haoban.manage.web.vo.chat.ChatOwnerVO;
import com.gic.haoban.manage.web.vo.chat.GroupChatPlanVO;
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: 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;
    @Autowired
    private StaffApiService staffApiService;

    @RequestMapping("add")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_QQF, optType = GicLogRecordOptTypeEnum.HB_1000_01, userFunc = LogRecordUserServiceImpl.class, optPage = "客户群群发")
    public RestResponse<Object> save(@RequestBody GroupChatPlanDTO dto) {
        if (StringUtils.isBlank(dto.getStaffIdList())) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", "请选择群主");
        }
        logger.info("新增参数={}", JSON.toJSONString(dto));
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        dto.setCreatorId(loginUser.getClerkId());
        dto.setCreatorName(loginUser.getClerkName());
        dto.setModifierId(loginUser.getClerkId());
        dto.setModifierName(loginUser.getClerkName());
        dto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        dto.setEnterpriseId(loginUser.getEnterpriseId());
        this.groupChatPlanApiService.save(dto);
        String logContent = "新增客户群群发【" + dto.getName() + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        return RestResponse.successResult();
    }

    @RequestMapping("del")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_QQF, optType = GicLogRecordOptTypeEnum.HB_1000_04, userFunc = LogRecordUserServiceImpl.class, optPage = "客户群群发")
    public RestResponse<Object> del(Long planId) {
        if (null == planId) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", "任务ID空");
        }
        ServiceResponse<GroupChatPlanDTO> planResp = this.groupChatPlanApiService.detail(planId);
        if (!planResp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("1", "任务不存在");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        this.groupChatPlanApiService.del(loginUser.getClerkId(), loginUser.getClerkName(), planId);
        String logContent = "删除客户群群发【" + planResp.getResult().getName() + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        return RestResponse.successResult();
    }

    /**
     * 
    * @Title: stop
    * @Description: 终止
    * @author xugh
    * @param planId
    * @return
    * @throws
     */
    @RequestMapping("stop")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_QQF, optType = GicLogRecordOptTypeEnum.HB_1000_03, userFunc = LogRecordUserServiceImpl.class, optPage = "客户群群发")
    public RestResponse<Object> stop(Long planId) {
        if (null == planId) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", "任务ID空");
        }
        ServiceResponse<GroupChatPlanDTO> planResp = this.groupChatPlanApiService.detail(planId);
        if (!planResp.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("1", "任务不存在");
        }
        GroupChatPlanDTO plan = planResp.getResult();
        if (plan.getEndTime().getTime() <= new Date().getTime()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("1", "任务已结束");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        this.groupChatPlanApiService.stop(loginUser.getClerkId(), loginUser.getClerkName(), planId);
        String logContent = "终止客户群群发【" + plan.getName() + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        return RestResponse.successResult();
    }

    @RequestMapping("update")
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.HB_QQF, optType = GicLogRecordOptTypeEnum.HB_1000_02, userFunc = LogRecordUserServiceImpl.class, optPage = "客户群群发")
    public RestResponse<Object> update(@RequestBody GroupChatPlanDTO dto) {
        logger.info("更新参数={}", JSON.toJSONString(dto));
        ServiceResponse<GroupChatPlanDTO> oldResp = this.groupChatPlanApiService.detail(dto.getPlanId());
        GroupChatPlanDTO oldPlan = oldResp.getResult();
        if (null == oldPlan) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", "任务不存在");
        }
        long now = System.currentTimeMillis();
        if (oldPlan.getEndTime().getTime() <= now || oldPlan.getStatusFlag() == 0) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999", "任务已结束");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        dto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        dto.setEnterpriseId(loginUser.getEnterpriseId());
        dto.setModifierId(loginUser.getClerkId());
        dto.setModifierName(loginUser.getClerkName());
        ServiceResponse<GroupChatPlanDTO> resp = null;
        // 任务进行中只能编辑备注
        if (oldPlan.getStartTime().getTime() <= now && oldPlan.getEndTime().getTime() >= now) {
            resp = this.groupChatPlanApiService.updateRemark(dto);
        } else {
            resp = this.groupChatPlanApiService.save(dto);
        }
        if (resp.isSuccess()) {
            String logContent = this.getUpdateLog(oldPlan, dto);
            if (StringUtils.isNotBlank(logContent)) {
                GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
                GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
            }else {
                GicLogRecordEvaluationContext.noWriteLog();
            }
            return RestResponse.successResult();
        }
        return RestResponse.successResult();
    }

    private String getUpdateLog(GroupChatPlanDTO oldDTO, GroupChatPlanDTO newDTO) {
        String wxEnterpriseId = newDTO.getWxEnterpriseId();
        String enterpriseId = newDTO.getEnterpriseId();
        StringBuilder content = new StringBuilder();
        String a = comp(wxEnterpriseId, enterpriseId, "任务标题", oldDTO.getName(), newDTO.getName(), 0);
        if (null != a) {
            content.append(a);
        }
        String b = comp(wxEnterpriseId, enterpriseId, "任务描述", oldDTO.getRemark(), newDTO.getRemark(), 0);
        if (null != b) {
            content.append(b);
        }
        // 新增群主
        String c = null;
        if (StringUtils.isNotBlank(newDTO.getStaffIdList())) {
            StringBuilder sb = new StringBuilder();
            String[] arr = newDTO.getStaffIdList().split(",");
            List<String> staffIds = Arrays.asList(arr);
            List<StaffDTO> dtoList = this.staffApiService.listByIds(staffIds);
            if (CollectionUtils.isNotEmpty(dtoList)) {
                sb.append("新增群主「");
                dtoList.forEach(dto -> {
                    sb.append(dto.getStaffName()).append(",");
                });
                c = sb.substring(0, sb.length() - 1) + "」";
                content.append(c);
            }
        }
        // 删除群主
        String d = null;
        if (StringUtils.isNotBlank(newDTO.getDelStaffIdList())) {
            StringBuilder sb = new StringBuilder();
            String[] arr = newDTO.getDelStaffIdList().split(",");
            List<String> staffIds = Arrays.asList(arr);
            List<StaffDTO> dtoList = this.staffApiService.listByIds(staffIds);
            if (CollectionUtils.isNotEmpty(dtoList)) {
                sb.append("删除群主「");
                dtoList.forEach(dto -> {
                    sb.append(dto.getStaffName()).append(",");
                });
                d = sb.substring(0, sb.length() - 1) + "」";
                content.append(d);
            }
        }

        String e = null;
        if (oldDTO.getSendType() != newDTO.getSendType()) {
            if (newDTO.getSendType() == 1) {
                StringBuilder sb = new StringBuilder();
                String date = DateUtil.dateToStr(oldDTO.getSendTime(), "yyyy-MM-dd HH:mm:ss");
                sb.append("发送时间").append("「定时发送,").append(date).append("」变更为「").append("立即发送」");
                e = sb.toString();
                content.append(e);
            }
        } else {
            String date1 = DateUtil.dateToStr(oldDTO.getSendTime(), "yyyy-MM-dd HH:mm:ss");
            String date2 = DateUtil.dateToStr(newDTO.getSendTime(), "yyyy-MM-dd HH:mm:ss");
            if (!date1.equals(date2)) {
                StringBuilder sb = new StringBuilder();
                sb.append("发送时间").append("「定时发送,").append(date1).append("」变更为「").append("定时发送,").append(date2)
                        .append("」");
                e = sb.toString();
                content.append(e);
            }
        }
        // 结束时间
        String f = null;
        if (!oldDTO.getExpireDays().equals(newDTO.getExpireDays())) {
            StringBuilder sb = new StringBuilder();
            sb.append("结束时间").append("「").append(oldDTO.getExpireDays()).append("天后").append("").append("」变更为「")
                    .append(newDTO.getExpireDays()).append("天后").append("").append("」");
            f = sb.toString();
            content.append(f);
        }
        if (org.apache.commons.lang3.StringUtils.isAllBlank(a, b, c, d, e, f)) {
            return null;
        }

        StringBuilder sb = new StringBuilder("编辑客户群群发").append("【").append(oldDTO.getName()).append("】：");
        return sb.append(content).toString();
    }

    public String comp(String wxEnterpriseId, String enterpriseId, String title, String oldValue, String newValue,
            int type) {
        StringBuilder sb = new StringBuilder();
        if (null == oldValue) {
            oldValue = "";
        }
        if (null == newValue) {
            newValue = "";
        }
        if (type == 0 && !oldValue.equals(newValue)) {
            sb.append(title).append("「").append(oldValue).append("」变更为「").append(newValue).append("」");
            return sb.toString();
        }
        return null;
    }

    @RequestMapping("page")
    public RestResponse<Object> page(GroupChatPlanSearchQDTO qdto, BasePageInfo basePageInfo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        List<String> creatorIdList = CreatorUtils.getCreatorIdList(0);
        if (CollectionUtils.isNotEmpty(creatorIdList)) {
            qdto.setCreatorIdList(creatorIdList);
        }
        ServiceResponse<Page<GroupChatPlanDTO>> page = this.groupChatPlanApiService.listPage(qdto, basePageInfo);
        return RestResponse.successResult(page.getResult());
    }

    @RequestMapping("detail")
    public RestResponse<Object> detail(Long planId, @RequestParam(defaultValue = "0") int updteFlag) {
        ServiceResponse<GroupChatPlanDTO> planResp = this.groupChatPlanApiService.detail(planId);
        if (!planResp.isSuccess()) {
            return RestResponse.failure("1", "任务不存在");
        }
        GroupChatPlanDTO plan = planResp.getResult();
        plan.getStaffIdList();
        String content = plan.getChatContent();
        Integer materialFrom = plan.getMaterialFrom();
        List<MaterialDTO> materials = new ArrayList<>();
        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.setMaterialTitle(x.getTitle());
                materialDTO.setMaterialType(x.getType());
                materialDTO.setMaterialContent(x.getContent());
                materialDTO.setImgUrl(x.getImg());
                return materialDTO;
            }).collect(Collectors.toList());
        }
        // 查询素材列表
        GroupChatPlanVO vo = EntityUtil.changeEntityByJSON(GroupChatPlanVO.class, plan);
        vo.setMaterialIdList(materials);
        GroupChatPlanSearchQDTO qdto = new GroupChatPlanSearchQDTO();
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        BasePageInfo basePageInfo = new BasePageInfo();
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(10000);
        ServiceResponse<Page<GroupChatPlanOwnerLogDTO>> ownerResp = this.groupChatPlanApiService
                .listOwnerLogPage(planId, qdto, basePageInfo);
        if (ownerResp.isSuccess()) {
            List<GroupChatPlanOwnerLogDTO> list = ownerResp.getResult().getResult();
            if (CollectionUtils.isNotEmpty(list)) {
                List<ChatOwnerVO> ownerList = list.stream().map(dto -> {
                    ChatOwnerVO owner = new ChatOwnerVO();
                    owner.setStaffId(dto.getStaffId());
                    owner.setStaffName(dto.getStaffName());
                    return owner;
                }).collect(Collectors.toList());
                vo.setOwnerList(ownerList);
            }
        }
        return RestResponse.successResult(vo);
    }

    @RequestMapping("owner-log")
    public RestResponse<Object> ownerLog(Long planId, GroupChatPlanSearchQDTO qdto, BasePageInfo basePageInfo) {
        if (null == planId) {
            return RestResponse.failure("9999", "任务ID空");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        ServiceResponse<Page<GroupChatPlanOwnerLogDTO>> resp = this.groupChatPlanApiService.listOwnerLogPage(planId,
                qdto, basePageInfo);
        if (!resp.isSuccess()) {
            return RestResponse.failure("1", "任务不存在");
        }
        return RestResponse.successResult(resp.getResult());
    }

    @RequestMapping("log")
    public RestResponse<Object> log(Long planId, GroupChatPlanSearchQDTO qdto, BasePageInfo basePageInfo) {
        if (null == planId) {
            return RestResponse.failure("9999", "任务ID空");
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        ServiceResponse<Page<GroupChatPlanLogDTO>> resp = this.groupChatPlanApiService.listLogPage(planId, qdto,
                basePageInfo);
        if (!resp.isSuccess()) {
            return RestResponse.failure("1", "任务不存在");
        }
        return RestResponse.successResult(resp.getResult());
    }

}
