package com.gic.haoban.manage.service.service.out.impl.content;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.manage.api.dto.ContentMaterialDTO;
import com.gic.haoban.manage.api.dto.content.MaterialConvertDTO;
import com.gic.haoban.manage.api.dto.content.log.ClerkShareMaterialLogDTO;
import com.gic.haoban.manage.api.dto.content.log.TriggerCustomerDetailLogDTO;
import com.gic.haoban.manage.api.enums.content.ClerkShareMaterialType;
import com.gic.haoban.manage.api.service.MaterialApiService;
import com.gic.haoban.manage.api.service.content.MaterialShareLogApiService;
import com.gic.haoban.manage.service.pojo.bo.content.ClerkShareLogBO;
import com.gic.haoban.manage.service.pojo.bo.content.TriggerCustomerDetailBO;
import com.gic.haoban.manage.service.service.content.ClerkShareLogService;
import com.gic.haoban.manage.service.service.content.TriggerCustomerDetailService;
import com.gic.haoban.manage.service.util.DrawImageUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/3/18 8:34 PM
 * @Description
 * @Version
 **/
@Component(value = "materialShareLogApiServiceImpl")
public class MaterialShareLogApiServiceImpl implements MaterialShareLogApiService {

    private static final Logger log = LoggerFactory.getLogger(MaterialShareLogApiServiceImpl.class);

    /**
     * 导购分享素材 客户触达日志
     * @see com.gic.haoban.manage.api.service.content.task.QywxGroupMsgTaskApiService#handlerTriggerCustomerDetailLog(String)
     */
    private static final String SHARE_MATERIAL_DETAIL_LOG = "handlerTriggerCustomerDetailLog";
    @Autowired
    private ClerkShareLogService clerkShareLogService;
    @Autowired
    TriggerCustomerDetailService triggerCustomerDetailService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    MaterialApiService materialApiService;


    @Override
    public ServiceResponse<Long> saveClerkShareMaterialLog(ClerkShareMaterialLogDTO clerkShareMaterialLogDTO) {
        log.info("saveClerkShareMaterialLog 保存导购分享日志 clerkId:{}, bizId:{} {}", clerkShareMaterialLogDTO.getClerkId(),
                clerkShareMaterialLogDTO.getBizId(), JSON.toJSONString(clerkShareMaterialLogDTO));

        if (StringUtils.isNotBlank(clerkShareMaterialLogDTO.getExternalUserId())) {
            // 通过对话框发送
            TriggerCustomerDetailBO temp = new TriggerCustomerDetailBO();
            temp.setId(UniqueIdUtils.uniqueLong());
            temp.setEnterpriseId(clerkShareMaterialLogDTO.getEnterpriseId());
            temp.setWxEnterpriseId(clerkShareMaterialLogDTO.getWxEnterpriseId());
            temp.setBizId(clerkShareMaterialLogDTO.getBizId());
            temp.setBizType(clerkShareMaterialLogDTO.getBizType());
            temp.setClerkId(clerkShareMaterialLogDTO.getClerkId());
            temp.setStaffId(clerkShareMaterialLogDTO.getStaffId());
            temp.setStoreId(clerkShareMaterialLogDTO.getStoreId());
            temp.setChannelType(clerkShareMaterialLogDTO.getShareType());
            temp.setCustomerId(clerkShareMaterialLogDTO.getExternalUserId());
            temp.setCreateTime(new Date());
            temp.setUpdateTime(new Date());
            temp.setDeleteFlag(0);
            triggerCustomerDetailService.batchSave(Collections.singletonList(temp));
            return ServiceResponse.success(temp.getId());
        }

        ClerkShareLogBO clerkShareLogBO = new ClerkShareLogBO();
        BeanUtils.copyProperties(clerkShareMaterialLogDTO, clerkShareLogBO);
        Long logId = clerkShareLogService.saveClerkShareLog(clerkShareLogBO);
        if (logId != null && ClerkShareMaterialType.SHARE_PYQ.getCode().equals(clerkShareLogBO.getShareType())){
            // MQ 通知处理导购分享日志
            TriggerCustomerDetailLogDTO triggerCustomerDetailLog = new TriggerCustomerDetailLogDTO();
            triggerCustomerDetailLog.setEnterpriseId(clerkShareLogBO.getEnterpriseId());
            triggerCustomerDetailLog.setClerkId(clerkShareLogBO.getClerkId());
            triggerCustomerDetailLog.setShareType(ClerkShareMaterialType.SHARE_PYQ.getCode());
            TriggerCustomerDetailLogDTO.SharePYQ sharePYQ = new TriggerCustomerDetailLogDTO.SharePYQ();
            sharePYQ.setShareLogId(logId);
            triggerCustomerDetailLog.setSharePYQ(sharePYQ);
            try{
                log.info("分享朋友圈日志 MQ {}", JSON.toJSONString(triggerCustomerDetailLog));
                GICMQClientUtil.getClientInstance().sendMessage(SHARE_MATERIAL_DETAIL_LOG, JSON.toJSONString(triggerCustomerDetailLog), 60);
            }catch (Exception ex){
                log.warn("客户分享素材 触达日志MQ异常 {}", JSON.toJSONString(triggerCustomerDetailLog), ex);
            }
        }
        return ServiceResponse.success(logId);
    }

    /**
     * 转换素材id
     *
     * @param materialConvertDTO
     * @return
     */
    @Override
    public ServiceResponse<List<String>> convertMaterialId(MaterialConvertDTO materialConvertDTO) {
        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(materialConvertDTO.getEnterpriseId());
        if (enterpriseDTO == null) {
            return ServiceResponse.failure("-701", "企业不存在");
        }
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            URL url = new URL(materialConvertDTO.getQrCodeUrl());
            InputStream inputStream = url.openStream();
            byteArrayOutputStream = DrawImageUtils.cloneInputStream(inputStream);
        }catch (Exception ex) {
            log.info("获取二维码流对象异常 qrCodeUrl:{}", materialConvertDTO.getQrCodeUrl());
            return ServiceResponse.failure("-701", "系统异常");
        }
        if (byteArrayOutputStream == null) {
            return ServiceResponse.success();
        }
        ByteArrayOutputStream finalByteArrayOutputStream = byteArrayOutputStream;
        List<String> imageUrls = materialConvertDTO
                .getImageUrls()
//                .stream()
                .parallelStream()
                .map(item -> DrawImageUtils.addWaterNew(enterpriseDTO.getFactoryCode(), item, ""))
                .collect(Collectors.toList());
        log.info("转换后的图片数据 {}", JSON.toJSONString(imageUrls));
        List<String> materialIds = imageUrls.parallelStream()
                .map(item -> {
                    ContentMaterialDTO contentMaterialDTO = new ContentMaterialDTO();
                    contentMaterialDTO.setMaterialType(materialConvertDTO.getMaterialType());
                    contentMaterialDTO.setImgUrl(item);
                    contentMaterialDTO.setMediaType(materialConvertDTO.getMediaType());
                    ServiceResponse<String> serviceResponse = materialApiService.getMaterialId(materialConvertDTO.getWxEnterpriseId(), contentMaterialDTO);
                    if (serviceResponse.isSuccess()) {
                        return serviceResponse.getResult();
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return ServiceResponse.success(materialIds);
    }
}
