package cn.com.ctop.kuaishou.modules.document.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import cn.com.ctop.kuaishou.modules.document.mapper.AuditRejectedResubmitMapper;
import cn.com.ctop.kuaishou.modules.document.mapper.DocumentLibraryMapper;
import cn.com.ctop.kuaishou.modules.document.service.AuditRejectedResubmitService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 拒审重提
 * @Author: zzy
 * @Date: 2021-09-06
 * @Version: V1.0
 */
@Service
@Slf4j
public class AuditRejectedResubmitServiceImpl implements AuditRejectedResubmitService {

    @Autowired
    AuditRejectedResubmitMapper auditRejectedResubmitMapper;

    @Autowired
    private IMaterialCutFrameService cutFrameService;

    @Autowired
    private IKuaiShouImageGetService imageGetService;

    @Autowired
    private IKuaiShouMaterialUploadService uploadService;

    @Autowired
    private ICtopOauthTokenService tokenService;

    @Autowired
    private IKuaiShouUpdateService updateService;

    @Autowired
    private DocumentLibraryMapper documentLibraryMapper;

    /**
     * 重新提交创意
     *
     * @param
     * @return
     */
    @Override
    public Result resubmit() {
        Result result = new Result();
        List<KuaiShouCreative> creativeList = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        try {
            log.info(formatter.format(calendar.getTime()));
            creativeList = auditRejectedResubmitMapper.getCreativeList(42, formatter.format(calendar.getTime()));
            //可重提封面词组
            List<String> submit = auditRejectedResubmitMapper.getRejectThesaurusListByStatus(0);
            //可重提广告语词组
            List<String> submit2 = auditRejectedResubmitMapper.getRejectThesaurusListByStatus(1);
            //不可重提词组
            List<String> resubmit = auditRejectedResubmitMapper.getRejectThesaurusListByStatus(2);
            creativeList.stream().forEach(obj -> {
                String reviewDetail = obj.getReviewDetail();
                List<String> strings = Arrays.asList(reviewDetail.split(";"));
                Boolean flag = isSubmit(strings, resubmit);
                if (!flag) {
                    //不可重提
                    log.info("修改为不可重提:{}", reviewDetail);
                    auditRejectedResubmitMapper.updateCreativeResubmit(String.valueOf(obj.getCreativeId()), 1);
                } else {
                    //判断是否封面重提
                    Boolean flag2 = isNotSubmit(strings, submit);
                    //判断是否广告语重提
                    Boolean flag3 = isNotSubmit(strings, submit2);
                    JSONObject updateJson = new JSONObject();
                    if (flag2 || flag3) {
                        Integer submit_size = obj.getSubmitSize();
                        if (submit_size < 2) {
                            //重提
                            log.info("进行重提:{}", reviewDetail);
                            String imageToken = null;
                            List<Map<String, String>> documentByAccountId = null;
                            updateJson.put("creativeId", obj.getCreativeId());
                            CtopOauthToken oauthToken = tokenService.getTokenByAccountId(obj.getAccountId());
                            if (flag2) {
                                log.info("进行封面重提:{}", reviewDetail);
                                //更换封面
                                JSONObject cutJson = cutFrameService.getCutFrameByVideoMd5(obj.getPhotoId(), obj.getImageToken());
                                if (!Check.isNull(cutJson)) {
                                    String signature = cutJson.getString("signature");
                                    String url = cutJson.getString("url");
                                    imageToken = getImageToken(signature, obj.getAccountId(), oauthToken.getAccessToken(), url);
                                    if (imageToken != null) {
                                        updateJson.put("imageToken", imageToken);
                                    } else {
                                        log.info("未查询到封面:accountId:{},creativeId:{}", obj.getAccountId(), obj.getCreativeId());
                                    }
                                }
                            }
                            if (flag3) {
                                //重提
                                log.info("进行广告语重提:{}", reviewDetail);
                                //更换文案
                                documentByAccountId = documentLibraryMapper.getDocumentByAccountId(String.valueOf(obj.getAccountId()), obj.getCopyWriterId());
                                if (documentByAccountId != null && documentByAccountId.size() > 0) {
                                    updateJson.put("description", documentByAccountId.get(0).get("copyWriter"));
                                } else {
                                    log.info("未查询到广告语:accountId:{},creativeId:{}", obj.getAccountId(), obj.getCreativeId());
                                }
                            }
                            if (imageToken != null || (documentByAccountId!=null && documentByAccountId.size() > 0)) {
                                Map<String, Object> creativeMap = updateService.updateCreative(oauthToken.getAccessToken(), obj.getAccountId(), updateJson);
                                Integer code = (Integer) creativeMap.get("code");
                                if (code == 0) {
                                    //修改重提次数和文案id
                                    auditRejectedResubmitMapper.updateCreativeResubmitSize(obj.getCreativeId(), documentByAccountId != null && documentByAccountId.size() > 0 ? documentByAccountId.get(0).get("copyWriterId") : null);
                                    //插入文案关联创意表信息
                                    if (documentByAccountId !=null && documentByAccountId.size() > 0) {
                                        auditRejectedResubmitMapper.saveCopyWriterCenter(documentByAccountId.get(0).get("copyWriterId"), String.valueOf(obj.getCreativeId()), new Date());
                                    }
                                    log.info("拒审重提成功,accountId:{},creativeId:{}", obj.getAccountId(), obj.getCreativeId());
                                } else {
                                    log.info("拒审重提失败,accountId:{},creativeId:{}", obj.getAccountId(), obj.getCreativeId());
                                }
                            }
                        } else {
                            log.info("重提次数已达上限:accountId:{},creativeId:{}", obj.getAccountId(), obj.getCreativeId());
                        }

                    } else {
                        //手动重提
                        log.info("手动重提:{}", reviewDetail);
                    }
                }
            });
            result.setSuccess(true);
            result.success("重提创意成功");
        } catch (Exception e) {
            log.info("重提创意错误:{}", e.toString());
            result.error500("重提创意错误");
        }

        return result;
    }

    /**
     * 判断不可重提
     *
     * @param
     * @return
     */
    public Boolean isSubmit(List<String> reviewDetail, List<String> thesaurusList) {
        Boolean flag = true;
        if (reviewDetail != null && thesaurusList != null) {
            for (String review : reviewDetail) {
                for (String thesaurus : thesaurusList) {
                    if (review.contains(thesaurus)) {
                        flag = false;
                        return flag;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 判断可重提
     *
     * @param
     * @return
     */
    public Boolean isNotSubmit(List<String> reviewDetail, List<String> thesaurusList) {
        if (reviewDetail != null && thesaurusList != null) {
            for (String review : reviewDetail) {
                Boolean flag = false;
                for (String thesaurus : thesaurusList) {
                    if (review.contains(thesaurus)) {
                        flag = true;
                    }
                }
                if (!flag) {
                    return false;
                }
            }
        }
        return true;
    }


    private String getImageToken(String md5, Long accountId, String accessToken, String url) {
        String imageToken = null;
        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("signature", md5);
        queryWrapper.last("limit 1");
        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
        if (!Check.isNull(imageGet)) {
            imageToken = imageGet.getImageToken();
        } else {
            imageToken = uploadService.kuauiShouImageUpload(url, md5, accountId, accessToken);
        }
        return imageToken;

    }
}
