//package com.gree.mall.manager.logic.marketing;
//
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.gree.mall.manager.bean.admin.AdminUserCom;
//import com.gree.mall.manager.bean.marketing.MarketingMaterialsAddReqBean;
//import com.gree.mall.manager.bean.marketing.MarketingMaterialsUpdateReqBean;
//import com.gree.mall.manager.commonmapper.MarketingMaterialsVisitCustomMapper;
//import com.gree.mall.manager.config.wx.WxConfiguration;
//import com.gree.mall.manager.constant.Constant;
//import com.gree.mall.manager.enums.MarketingMaterialsTypeEnum;
//import com.gree.mall.manager.exception.RemoteServiceException;
//import com.gree.mall.manager.logic.common.CommonLogic;
//import com.gree.mall.manager.logic.common.WorkWechatLogic;
//import com.gree.mall.manager.logic.wxCustomer.WxCustomerLogic;
//import com.gree.mall.manager.plus.entity.*;
//import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
//import com.gree.mall.manager.plus.service.CommonFileService;
//import com.gree.mall.manager.plus.service.MarketingMaterialsService;
//import com.gree.mall.manager.plus.service.MarketingMaterialsTagService;
//import com.gree.mall.manager.utils.CommonUtils;
//import com.gree.mall.manager.utils.oss.OSSUtil;
//import lombok.extern.slf4j.Slf4j;
//import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
//import me.chanjar.weixin.common.error.WxErrorException;
//import me.chanjar.weixin.cp.api.WxCpMediaService;
//import me.chanjar.weixin.cp.api.WxCpService;
//import org.apache.commons.io.FileUtils;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import sun.net.www.content.text.PlainTextInputStream;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.File;
//import java.io.IOException;
//import java.io.InputStream;
//import java.net.MalformedURLException;
//import java.net.URL;
//import java.rmi.RemoteException;
//import java.text.SimpleDateFormat;
//import java.util.*;
//
///**
// * 营销素材
// */
//@Slf4j
//@Service
//public class MarketingMaterialsLogic {
//
//    @Autowired
//    private MarketingMaterialsService marketingMaterialsService;
//    @Autowired
//    private CommonLogic commonLogic;
//    @Autowired
//    private CommonFileService commonFileService;
//    @Autowired
//    private MarketingMaterialsTagService marketingMaterialsTagService;
//    @Autowired
//    private AdminCompanyWechatService adminCompanyWechatService;
//    @Autowired
//    private WorkWechatLogic workWechatLogic;
//    @Autowired
//    private MarketingMaterialsVisitCustomMapper marketingMaterialsVisitCustomMapper;
//
//    /**
//     * 通过id获取
//     */
//    public MarketingMaterialsUpdateReqBean getById(String marketingMaterialsId) throws IOException {
//        MarketingMaterials byId = marketingMaterialsService.getById(marketingMaterialsId);
//        if (byId == null) {
//            throw new RemoteServiceException("该营销素材不存在");
//        }
//        MarketingMaterialsUpdateReqBean respBean=new MarketingMaterialsUpdateReqBean();
//        BeanUtils.copyProperties(byId,respBean);
//
//
//        //查询标签
//        List<Tag> materialsTag = marketingMaterialsVisitCustomMapper.getMaterialsTag(marketingMaterialsId);
//        respBean.setTag(materialsTag);
//
//        return respBean;
//
//    }
//
//    /**
//     * 素材文本类型url转string
//     */
//    public String urlToStr(String url) throws IOException {
//        return Txt.getTxtFile(url);
//    }
//
//
//    /**
//     * 分页获取营销素材
//     */
//    public IPage<MarketingMaterials> page(HttpServletRequest request, String title, String groupId, String type, Integer pageNum, Integer pageSize) throws IOException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        List<String> companyWechatIds = adminUser.getCompanyWechatIds();
//
//        return marketingMaterialsService.lambdaQuery()
//                .like(StringUtils.isNotBlank(title), MarketingMaterials::getTitle, title)
//                .eq(StringUtils.isNotBlank(groupId), MarketingMaterials::getMarketingGroupId, groupId)
//                .eq(MarketingMaterials::getType, type.trim())
//                .in(CollectionUtils.isNotEmpty(companyWechatIds), MarketingMaterials::getCompanyWechatId, companyWechatIds)
//                .orderByDesc(MarketingMaterials::getCreateTime)
//                .page(new Page<>(pageNum, pageSize));
//
//    }
//
//
//    /**
//     * 移组
//     */
//    public void moveGroup(HttpServletRequest request, String marketingMaterialsIds, String newGroupId) {
//        String userId = CommonUtils.getUserId(request);
//        String[] split = marketingMaterialsIds.split(",");
//        if (split.length == 0) {
//            return;
//        }
//
//        marketingMaterialsService.lambdaUpdate()
//                .set(MarketingMaterials::getMarketingGroupId, newGroupId)
//                .set(MarketingMaterials::getCreateTime, new Date())
//                .set(MarketingMaterials::getCreateBy, userId)
//                .in(MarketingMaterials::getMarketingMaterialsId, Arrays.asList(split))
//                .update();
//
//    }
//
//    /**
//     * 重置
//     */
//    public void reset(String groupId, String type) {
//
//        marketingMaterialsService.lambdaUpdate()
//                .eq(MarketingMaterials::getMarketingGroupId, groupId)
//                .eq(MarketingMaterials::getType, type.trim())
//                .remove();
//
//    }
//
//    /**
//     * 新增营销素材
//     */
//    @Transactional
//    public String add(HttpServletRequest request, MarketingMaterialsAddReqBean marketingMaterialsAddReqBean) throws IOException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        String loginCompanyWechatId = adminUser.getCompanyWechatId();
//        if (StringUtils.isBlank(loginCompanyWechatId)) {
//            throw new RemoteServiceException("运营账号暂无权限操作");
//        }
//        //校验请求数据
//        checkMarketingMaterialsAddReqBean(marketingMaterialsAddReqBean);
//
//        //新增数据
//        MarketingMaterials marketingMaterials = new MarketingMaterials();
//        BeanUtils.copyProperties(marketingMaterialsAddReqBean, marketingMaterials);
//
//        marketingMaterials.setCompanyWechatId(loginCompanyWechatId);
//        marketingMaterials.setCompanyName(adminUser.getCompanyName());
//        marketingMaterials.setCreateTime(new Date());
//        marketingMaterials.setCreateBy(adminUser.getAdminUserId());
//        marketingMaterials.setCreateName(adminUser.getNickName());
//
//        String type = marketingMaterials.getType();
//        //type !=文本 ,type !=小程序
//        if (!type.equals(MarketingMaterialsTypeEnum.TEXT.getCode()) && !type.equals(MarketingMaterialsTypeEnum.SMALL.getCode())) {
//
//            String fileType = type.equals(MarketingMaterialsTypeEnum.FILE.getCode()) ? "file" : (
//                    type.equals(MarketingMaterialsTypeEnum.VIDEO.getCode()) ? "video" : "image"
//            );
//
//            // 添加企微素材零时文件
//            try {
//                String mediaId = loadToQyWx(adminUser, marketingMaterialsAddReqBean.getFileUrl(), fileType);
//                marketingMaterials.setMediaId(mediaId);
//                marketingMaterials.setMediaIdLastUpdateTime(new Date());
//            } catch (WxErrorException e) {
//                throw new RemoteServiceException("上传素材至企业微信失败,请更换文件格式");
//            }
//        }
//        //添加营销素材
//        marketingMaterialsService.save(marketingMaterials);
//
//        //营销素材绑定标签
//        if (CollectionUtils.isNotEmpty(marketingMaterialsAddReqBean.getTag()) && marketingMaterials.getDynamicTitle() != null
//                && marketingMaterials.getDynamicTitle()) {
//
//            List<MarketingMaterialsTag> mmTagList = new ArrayList<>();
//            for (Tag tag : marketingMaterialsAddReqBean.getTag()
//            ) {
//                MarketingMaterialsTag mmTag = new MarketingMaterialsTag();
//                mmTag.setMarketingMaterialsId(marketingMaterials.getMarketingMaterialsId());
//                mmTag.setTagId(tag.getTagId());
//                mmTag.setName(tag.getName());
//                mmTag.setCreateTime(new Date());
//                mmTag.setCompanyWechatId(loginCompanyWechatId);
//                mmTag.setCompanyName(adminUser.getCompanyName());
//                mmTagList.add(mmTag);
//            }
//            //批量新增素材标签
//            marketingMaterialsTagService.saveBatch(mmTagList);
//
//        }
//
//        return marketingMaterials.getMarketingMaterialsId();
//    }
//
//    //校验请求数据
//    public void checkMarketingMaterialsAddReqBean(MarketingMaterials marketingMaterials) {
//
//        //  校验请求数据
//        String type = marketingMaterials.getType();
//        if (StringUtils.isBlank(type)) {
//            throw new RemoteServiceException("素材类型不能为null");
//        }
//        marketingMaterials.setType(type.trim());
//
//        if (StringUtils.isBlank(marketingMaterials.getTitle())) {
//            throw new RemoteServiceException("标题不能为null");
//        }
//
//        if (StringUtils.isBlank(marketingMaterials.getMarketingGroupId())) {
//            throw new RemoteServiceException("营销分组id不能为null");
//        }
//
//    }
//
//    private static class Txt {
//
//        //传入txt数据  返回url
////        public static String addTxtFile(String value) throws IOException {
////            String filePath = OSSUtil.OSS_TYPE_PIC + System.currentTimeMillis() + UUID.randomUUID().toString() + ".txt";
////            if (!OSSUtil.uploadFile(filePath, value.getBytes())) {
////                throw new RemoteServiceException("文件同步oss失败");
////            }
////            return OSSUtil.accessUrl + filePath;
////        }
////
////        //传入url和数据 跟新url中txt数据
////        public static String updateTxtFile(String url, String value) throws IOException {
////            String filePath = url.substring(OSSUtil.accessUrl.length());
////            if (!OSSUtil.uploadFile(filePath, value.getBytes())) {
////                throw new RemoteServiceException("文件同步oss失败");
////            }
////            return OSSUtil.accessUrl + filePath;
////        }
//
//        //传入txt数据  返回url
//        public static String getTxtFile(String url) throws IOException {
//            StringBuffer sb = new StringBuffer("");
//            URL urll = new URL(url);
//            PlainTextInputStream plainTextInputStream = (PlainTextInputStream) urll.getContent();
//            byte[] bt = new byte[1024];
//            int len = -1;
//            while ((len = plainTextInputStream.read(bt)) != -1) {
//                sb.append(new String(bt, 0, len));
//            }
//            return sb.toString();
//        }
//
//    }
//
//    /**
//     * 通过id删除营销素材
//     */
//    public void deleteById(String marketingMaterialsId) {
//        //删除营销素材
//        marketingMaterialsService.removeById(marketingMaterialsId);
//
//        //删除素材绑定的标签
//        marketingMaterialsTagService.lambdaUpdate()
//                .eq(MarketingMaterialsTag::getMarketingMaterialsId,marketingMaterialsId)
//                .remove();
//    }
//
//    /**
//     * 編輯
//     */
//    @Transactional
//    public void update(HttpServletRequest request, MarketingMaterialsUpdateReqBean updateReqBean) throws IOException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        String loginCompanyWechatId = adminUser.getCompanyWechatId();
//        if (StringUtils.isBlank(loginCompanyWechatId)) {
//            throw new RemoteServiceException("运营账号暂无权限操作");
//        }
//
//        String marketingMaterialsId = updateReqBean.getMarketingMaterialsId();
//        MarketingMaterials byId = null;
//        if (StringUtils.isBlank(marketingMaterialsId) || (byId = marketingMaterialsService.getById(marketingMaterialsId)) == null) {
//            throw new RemoteServiceException("营销素材id不能为null");
//        }
//
//        //校验
//        checkMarketingMaterialsAddReqBean(updateReqBean);
//
//        String type = updateReqBean.getType();
//
//        MarketingMaterials marketingMaterials = new MarketingMaterials();
//        BeanUtils.copyProperties(updateReqBean, marketingMaterials);
//
//        //type ！=文本 && type!=小程序
//        if (!type.equals(MarketingMaterialsTypeEnum.TEXT.getCode()) && !type.equals(MarketingMaterialsTypeEnum.SMALL.getCode())) {
//            //非文本
//
//            try {
//                String fileType = type.equals(MarketingMaterialsTypeEnum.FILE.getCode()) ? "file" : (
//                        type.equals(MarketingMaterialsTypeEnum.VIDEO.getCode()) ? "video" : "image"
//                );
//                String mediaId = loadToQyWx(adminUser, updateReqBean.getFileUrl(), fileType);
//
//                marketingMaterials.setMediaId(mediaId);
//                marketingMaterials.setMediaIdLastUpdateTime(new Date());
//            } catch (WxErrorException e) {
//                throw new RemoteServiceException("上传素材至企业微信失败,请更换文件格式");
//            }
//        }
//
//        //修改营销素材
//        marketingMaterialsService.updateById(marketingMaterials);
//
//        //营销素材绑定标签
//        if (CollectionUtils.isNotEmpty(updateReqBean.getTag()) && marketingMaterials.getDynamicTitle() != null
//                && marketingMaterials.getDynamicTitle()) {
//            //清除旧素材标签
//            marketingMaterialsTagService.lambdaUpdate()
//                    .eq(MarketingMaterialsTag::getMarketingMaterialsId, marketingMaterials.getMarketingMaterialsId())
//                    .remove();
//
//            List<MarketingMaterialsTag> mmTagList = new ArrayList<>();
//            for (Tag tag : updateReqBean.getTag()
//            ) {
//                MarketingMaterialsTag mmTag = new MarketingMaterialsTag();
//                mmTag.setMarketingMaterialsId(marketingMaterials.getMarketingMaterialsId());
//                mmTag.setTagId(tag.getTagId());
//                mmTag.setName(tag.getName());
//                mmTag.setCreateTime(new Date());
//                mmTag.setCompanyWechatId(loginCompanyWechatId);
//                mmTag.setCompanyName(adminUser.getCompanyName());
//                mmTagList.add(mmTag);
//            }
//            //批量新增素材标签
//            marketingMaterialsTagService.saveBatch(mmTagList);
//
//        }
//
//    }
//
//    /**
//     * 上传营销素材到企业微信
//     */
//    public String loadToQyWx(HttpServletRequest request, String fileUrl, String fileType) throws IOException, WxErrorException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        if (adminUser == null) {
//            throw new RemoteException("暂无授权,请联系管理员");
//        }
//        return loadToQyWx(adminUser, fileUrl, fileType);
//    }
//
//    /**
//     * 图片（image）：10MB，支持JPG,PNG格式
//     * 语音（voice） ：2MB，播放长度不超过60s，仅支持AMR格式
//     * 视频（video） ：10MB，支持MP4格式
//     * 普通文件（file）：20MB
//     * 上传营销素材到企业微信
//     */
//    public String loadToQyWx(AdminUserCom adminUserCom, String fileUrl, String fileType) throws IOException, WxErrorException {
//        AdminCompanyWechat adminCompanyWechat = adminUserCom.getAdminCompanyWechat();
//        return loadToQyWx(adminCompanyWechat, fileUrl, fileType);
//    }
//
//    public String loadToQyWx(AdminCompanyWechat adminCompanyWechat, String fileUrl, String fileType) throws IOException, WxErrorException {
//        WxCpService wxCpService = workWechatLogic.miniApp(adminCompanyWechat);
//
//        int i = fileUrl.lastIndexOf(".");
//        File file = new File("./logs/" + UUID.randomUUID().toString() + System.currentTimeMillis() + fileUrl.substring(i));
//        try {
//            URL url = new URL(fileUrl);
//            InputStream inputStream = url.openStream();
//            FileUtils.copyInputStreamToFile(inputStream, file);
//            WxMediaUploadResult upload = wxCpService.getMediaService().upload(fileType, file);
//            log.info("上传素材至企业微信成功:[返回mediaId:"+upload.getMediaId()+"]");
//            return upload.getMediaId();
//        } finally {
//            file.delete();
//        }
//    }
//
//
//    /**
//     * 更新营销素材MediaId
//     *
//     * @param day   跟新距离现在多少天的
//     * @param count 一次更新多少条
//     */
//    public IPage<MarketingMaterials> updateMaterialsMediaId(int day, int count) {
//        //所有企业微信
//        Map<String, AdminCompanyWechat> adminCompanyWechatMap = new HashMap<>();
//        for (AdminCompanyWechat adminCompanyWechat : adminCompanyWechatService.list()
//        ) {
//            adminCompanyWechatMap.put(adminCompanyWechat.getCompanyWechatId(), adminCompanyWechat);
//        }
//
//        //过期时间
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
//        calendar.add(Calendar.DAY_OF_MONTH, -day);
//        Date time = calendar.getTime();
//
//        //需跟新的素材
//        IPage<MarketingMaterials> page = marketingMaterialsService.lambdaQuery()
//                .le(MarketingMaterials::getMediaIdLastUpdateTime, time)
//                .ne(MarketingMaterials::getType, MarketingMaterialsTypeEnum.TEXT.getCode())
//                .ne(MarketingMaterials::getType, MarketingMaterialsTypeEnum.SMALL.getCode())
//                .page(new Page<>(1, count));
//
//        List<MarketingMaterials> data = page.getRecords();
//        if(CollectionUtils.isEmpty(data)){
//            return page;
//        }
//
//        for (MarketingMaterials mm : data
//        ) {
//
//            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatMap.get(mm.getCompanyWechatId());
//            String type = mm.getType();
//
//
//            //type 不为text时候
//            if (!type.equals(MarketingMaterialsTypeEnum.TEXT.getCode()) && !type.equals(MarketingMaterialsTypeEnum.SMALL.getCode())) {
//
//                try {
//                    String fileType = type.equals(MarketingMaterialsTypeEnum.FILE.getCode()) ? "file" : (
//                            type.equals(MarketingMaterialsTypeEnum.VIDEO.getCode()) ? "video" : "image"
//                    );
//                    String mediaId = loadToQyWx(adminCompanyWechat, mm.getFileUrl(), fileType);
//
//                    mm.setMediaId(mediaId);
//                } catch (WxErrorException | IOException e) {
//                    log.info("新增营销素材:调用企业微信失败返回:" + e.getMessage());
//                } finally {
//                    mm.setMediaIdLastUpdateTime(new Date());
//                }
//            }
//        }
//        marketingMaterialsService.updateBatchById(data);
//        return page;
//    }
//
//}
