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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Constant;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.commons.util.ToolUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.content.api.dto.material.ContentMaterialDTO;
import com.gic.content.api.dto.setting.ContentSettingDTO;
import com.gic.content.api.enums.*;
import com.gic.content.api.qdto.material.ContentMaterialPageQDTO;
import com.gic.content.api.qdto.material.ContentMaterialQDTO;
import com.gic.content.api.qdto.producer.ContentProducerClerkRandomQDTO;
import com.gic.content.api.service.ContentMaterialApiService;
import com.gic.content.api.service.ContentSettingApiService;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.web.controller.content.adaptor.ClerkStoreAdaptor;
import com.gic.haoban.manage.web.controller.content.adaptor.MaterialDataAdaptor;
import com.gic.haoban.manage.web.qo.content.ContentAuditMaterialDataQO;
import com.gic.haoban.manage.web.qo.content.ContentAuditMaterialQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialSaveQO;
import com.gic.haoban.manage.web.vo.content.creative.ContentMaterialConvsVO;
import com.gic.haoban.manage.web.vo.content.creative.ContentMaterialDataVO;
import com.gic.haoban.manage.web.vo.content.creative.ContentMaterialVO;
import com.gic.marketing.pro.api.dto.clerktask.ClerkTaskContentLogDTO;
import com.gic.marketing.pro.api.service.clerktask.ClerkTaskApiService;
import com.gic.mq.sdk.GicMQClient;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 好办-创作中心
 *
 */
@Controller
@RequestMapping("/creative")
public class ContentCreativeController {

    private static final Logger log = LoggerFactory.getLogger(ContentCreativeController.class);
    @Autowired
    private ContentMaterialApiService contentMaterialApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;
    @Autowired
    private ClerkTaskApiService clerkTaskApiService ;
    @Autowired
    private ContentSettingApiService contentSettingApiService ;

    /**
     * 创建素材
     * @param saveQO
     * @return
     */
    @ResponseBody
    @RequestMapping("/save-material")
    public RestResponse<ContentMaterialDTO> saveMaterial(@Validated @RequestBody ContentMaterialSaveQO saveQO) {
        String clerkId = saveQO.getClerkId();
        StaffDTO staffDTO = clerkStoreAdaptor.queryStaff(clerkId);
        if (staffDTO == null) {
            return RestResponse.failure("-1", "成员不存在");
        }
        ClerkDTO clerk = clerkService.getClerkByClerkId(clerkId);
        if (clerk == null) {
            return RestResponse.failure("-1", "导购不存在");
        }
        //组装导购发布人信息
        ContentProducerClerkRandomQDTO producerQDTO = new ContentProducerClerkRandomQDTO();
        producerQDTO.setProducerType(MaterialProducerTypeEnum.CLERK.value);
        producerQDTO.setNickName(clerk.getClerkName());
        String headImg = staffDTO.getHeadImg();
        if (StringUtils.isBlank(headImg)) {
            headImg = clerk.getImageUrl();
        }
        producerQDTO.setAvatar(headImg);
        producerQDTO.setEnterpriseId(saveQO.getEnterpriseId());
        producerQDTO.setClerkId(clerkId);
        producerQDTO.setClerkCode(clerk.getClerkCode());
        producerQDTO.setStoreId(clerk.getStoreId());
        ContentMaterialQDTO contentMaterialQDTO = EntityUtil.changeEntityByJSON(ContentMaterialQDTO.class, saveQO);
        contentMaterialQDTO.setCreatorId(clerk.getClerkId());
        contentMaterialQDTO.setCreatorName(clerk.getClerkName());
        contentMaterialQDTO.setUpdaterId(clerk.getClerkId());
        contentMaterialQDTO.setUpdaterName(clerk.getClerkName());
        contentMaterialQDTO.setProducer(producerQDTO);
        contentMaterialQDTO.setMaterialPurpose(MaterialPurposeEnum.AUDIT.code);
        contentMaterialQDTO.setPublishType(MaterialPublishTypeEnum.NONE.value);
        contentMaterialQDTO.setShelfStatus(Constant.FLAG_TRUE);
        ServiceResponse<ContentMaterialDTO> response = contentMaterialApiService.saveMaterial(contentMaterialQDTO);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        Long clerkTaskPlanId = saveQO.getClerkTaskPlanId() ;
        if(null != clerkTaskPlanId) {
            ClerkTaskContentLogDTO dto = new ClerkTaskContentLogDTO() ;
            dto.setPlanId(clerkTaskPlanId);
            dto.setRelationId(response.getResult().getContentMaterialId());
            dto.setEnterpriseId(saveQO.getEnterpriseId());
            dto.setContentPublishType(1);
            dto.setStatusFlag(0);
            dto.setClerkId(clerkId);
            this.clerkTaskApiService.saveContent(dto) ;
        }else {
            // 发送审批消息
            // 不是私域，且未开启自动审核
            ServiceResponse<ContentSettingDTO> resp = this.contentSettingApiService.queryContentSettingInfo(saveQO.getEnterpriseId()) ;
            if(resp.getResult().getCommunityUserSetting().getClerkMaterialAudit()==null || resp.getResult().getCommunityUserSetting().getClerkMaterialAudit()==0) {
                this.sendAudit(saveQO.getEnterpriseId(),saveQO.getClerkId()) ;
            }
        }
        return RestResponse.successResult(response.getResult());
    }

    private void sendAudit(String enterpriseId, String clerkId) {
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId) ;
        String clerkName = clerk.getClerkName() ;
        Map<String, String> map = new HashMap<>();
        map.put("clerkName", clerkName);
        this.send(enterpriseId,map,"clerkCreateContent");
    }

    private void send(String enterpriseId ,Map<String, String> map , String msgCode) {
        log.info("发送消息={}",msgCode);
        String mqName = "haobanNotice";
        JSONObject json = new JSONObject() ;
        json.put("messageCode",msgCode) ;
        json.put("mqRouterCode",mqName) ;
        json.put("enterpriseId",enterpriseId) ;
        json.put("businessId",ToolUtil.randomUUID()) ;
        json.put("uniqueKey",UniqueIdUtils.uniqueLongHex()) ;
        json.put("createTime",new Date()) ;
        json.put("variableMap",map) ;
        try {
            GicMQClient client = GICMQClientUtil.getClientInstance();
            client.sendMessage(mqName, JSON.toJSONString(json));
        } catch (Exception e) {
            log.info("异常",e);
        }
    }

    /**
     * 删除素材
     * @param enterpriseId  企业id
     * @param contentMaterialId 素材id
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete-material")
    public RestResponse<Void> saveMaterial(String enterpriseId, Long contentMaterialId) {
        ServiceResponse<Void> response = contentMaterialApiService.deleteMaterial(enterpriseId, contentMaterialId);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult();
    }


    /**
     * 素材详情
     * @param enterpriseId 企业id
     * @param contentMaterialId 素材id
     * @return
     */
    @ResponseBody
    @RequestMapping("/detail-material")
    public RestResponse<ContentMaterialVO> getMaterialDetail(String enterpriseId, Long contentMaterialId) {
        ServiceResponse<ContentMaterialDTO> response = contentMaterialApiService.getMaterialDetail(enterpriseId, contentMaterialId);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        ContentMaterialVO detailVO = EntityUtil.changeEntityByJSON(ContentMaterialVO.class, response.getResult());
        Map<Long, ContentMaterialConvsVO> map = materialDataAdaptor.queryCreativeConvsMap(enterpriseId, Lists.newArrayList(detailVO.getContentMaterialId()), null);
        ContentMaterialConvsVO materialConvsVO = map.get(detailVO.getContentMaterialId());
        detailVO.setConvs(materialConvsVO);
        return RestResponse.successResult(detailVO);
    }

    /**
     * 素材列表
     * @param auditMaterialQO qo
     * @return
     */
    @ResponseBody
    @RequestMapping("/page-material")
    public RestResponse<Page<ContentMaterialVO>> pageAuditMaterial(@RequestBody ContentAuditMaterialQO auditMaterialQO) {
        ContentMaterialPageQDTO pageQDTO = new ContentMaterialPageQDTO();
        String enterpriseId = auditMaterialQO.getEnterpriseId();
        pageQDTO.setEnterpriseId(enterpriseId);
        pageQDTO.setStoreId(auditMaterialQO.getStoreId());
        pageQDTO.setClerkId(auditMaterialQO.getClerkId());
        pageQDTO.setQueryScene(MaterialSearchSceneEnum.HAOBAN_AUDIT.value);
        Integer convsFlag = auditMaterialQO.getConvsFlag();
        // 分页数据总数（无转化查询取素材分页数据，有转化查询取数据组返回的分页数据）
        Integer totalCount = null;
        //素材对应转化数据map
        Map<Long, ContentMaterialConvsVO> map = null;
        //转化数据过滤的素材id列表
        List<Long> filterMaterialIdList = null;
        boolean convs = convsFlag != null && convsFlag == Constant.FLAG_TRUE;
        //是否有转化查询
        if (convs) {
            ServiceResponse<List<Long>> listIdResponse = contentMaterialApiService.listMaterialIdBySearch(pageQDTO);
            if (!listIdResponse.isSuccess() || CollectionUtils.isEmpty(listIdResponse.getResult())) {
                return RestResponse.successResult(new Page<>());
            }
            List<Long> materialIdList = listIdResponse.getResult();
            Page<ContentMaterialConvsVO> dataPage = materialDataAdaptor.queryCreativeConvs(enterpriseId, materialIdList, auditMaterialQO.getBasePageInfo());
            if (dataPage == null || CollectionUtils.isEmpty(dataPage.getResult())) {
                return RestResponse.successResult(new Page<>());
            }
            List<ContentMaterialConvsVO> result = dataPage.getResult();
            map = result.stream().collect(Collectors.toMap(ContentMaterialConvsVO::getContentMaterialId, t -> t));
            filterMaterialIdList = result.stream().map(ContentMaterialConvsVO::getContentMaterialId).collect(Collectors.toList());
            totalCount = dataPage.getTotalCount();
        }

        if(null != auditMaterialQO.getClerkTaskPlanId()) {
            List<Long> materiaIdList = this.clerkTaskApiService.listContentMaterialIdList(auditMaterialQO.getClerkTaskPlanId(),auditMaterialQO.getClerkId()) ;
            if(CollectionUtils.isEmpty(materiaIdList)) {
                return RestResponse.successResult(new Page<>());
            }
            filterMaterialIdList = materiaIdList ;
            log.info("导购任务id={},{}",auditMaterialQO.getClerkTaskPlanId(),filterMaterialIdList);
        }

        pageQDTO.setContentMaterialIdList(filterMaterialIdList);
        ServiceResponse<Page<ContentMaterialDTO>> response = contentMaterialApiService.pageMaterial(pageQDTO, auditMaterialQO.getBasePageInfo());
        if (!response.isSuccess() || CollectionUtils.isEmpty(response.getResult().getResult())) {
            return RestResponse.successResult(new Page<>());
        }
        Page<ContentMaterialDTO> page = response.getResult();
        Page<ContentMaterialVO> result = new Page<>();
        List<ContentMaterialVO> list = EntityUtil.changeEntityListByJSON(ContentMaterialVO.class, response.getResult().getResult());
        if (totalCount == null) {
            totalCount = page.getTotalCount();
        }
        result.setTotalCount(totalCount);
        result.setResult(list);
        result.setCurrentPage(page.getCurrentPage());
        result.setPageSize(page.getPageSize());
        if (!convs) {
            List<Long> materialIdList = list.stream().map(ContentMaterialVO::getContentMaterialId).collect(Collectors.toList());
            BasePageInfo pageInfo = new BasePageInfo();
            pageInfo.setPageNum(1);
            pageInfo.setPageSize(materialIdList.size());
            map = materialDataAdaptor.queryCreativeConvsMap(enterpriseId, materialIdList, pageInfo);
        }
        //列表转化数据
        if (CollectionUtils.isNotEmpty(list)) {
            for (ContentMaterialVO materialVO : list) {
                Long contentMaterialId = materialVO.getContentMaterialId();
                ContentMaterialConvsVO materialConvsVO = map.get(contentMaterialId);
                materialVO.setConvs(materialConvsVO);
            }
        }
        return RestResponse.successResult(result);
    }

    /**
     * 数据概览
     * @param auditMaterialQO  qo
     * @return
     */
    @ResponseBody
    @RequestMapping("/material-data")
    public RestResponse<ContentMaterialDataVO> auditMaterialData(@RequestBody ContentAuditMaterialDataQO auditMaterialQO) {
        ContentMaterialPageQDTO pageQDTO = new ContentMaterialPageQDTO();
        String enterpriseId = auditMaterialQO.getEnterpriseId();
        Integer createFlag = auditMaterialQO.getCreateFlag();
        pageQDTO.setEnterpriseId(enterpriseId);
        pageQDTO.setStoreId(auditMaterialQO.getStoreId());
        pageQDTO.setClerkId(auditMaterialQO.getClerkId());
        pageQDTO.setQueryScene(MaterialSearchSceneEnum.HAOBAN_AUDIT.value);
        ServiceResponse<Long> response = contentMaterialApiService.countMaterialBySearch(pageQDTO);
        pageQDTO.setAuditStatus(MaterialAuditEnum.AUDIT.code);
        ServiceResponse<Long> auditResponse = contentMaterialApiService.countMaterialBySearch(pageQDTO);
        if (!response.isSuccess() || !auditResponse.isSuccess()) {
            return RestResponse.failure("-1", "请求失败");
        }
        ContentMaterialDataVO materialDataVO = new ContentMaterialDataVO();
        materialDataVO.setAuditCount(auditResponse.getResult());
        materialDataVO.setCreateCount(response.getResult());
        if (createFlag == null || createFlag == Constant.FLAG_FALSE) {
            pageQDTO.setAuditStatus(MaterialAuditEnum.SUCCESS.code);
            //转化数据
            ServiceResponse<List<Long>> idListResponse = contentMaterialApiService.listMaterialIdBySearch(pageQDTO);
            if (!idListResponse.isSuccess()) {
                return RestResponse.failure("-1", "请求失败");
            }
            ContentMaterialConvsVO materialConvsVO = materialDataAdaptor.queryCreativeConvsOverview(enterpriseId, idListResponse.getResult());
            materialDataVO.setConvs(materialConvsVO);
        }
        return RestResponse.successResult(materialDataVO);
    }

}
