package cn.com.ctop.kuaishou.modules.ai.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.ISysRoleExtService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouCrowdPack;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouPopulationPackage;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouPopulationPackageRel;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouPopulationPackageMapper;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouPopulationPackageRelMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouMaterialPoolOperationRecordService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouPopulationGroupService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouPopulationPackageRelService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouPopulationPackageService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouPopulationService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * 项目绑定的人群包模板
 *
 * @author jeecg-boot
 * 2021-05-06
 * @version V1.0
 */
@Service
public class KuaishouPopulationPackageServiceImpl extends ServiceImpl<KuaishouPopulationPackageMapper, KuaishouPopulationPackage> implements IKuaishouPopulationPackageService {

    @Autowired
    private KuaishouPopulationPackageMapper kuaishouPopulationPackageMapper;
    @Autowired
    private KuaishouPopulationPackageRelMapper relMapper;
    @Autowired
    private IKuaishouPopulationPackageRelService relService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouPopulationService kuaishouPopulationService;
    @Autowired
    private IKuaishouPopulationService iKuaishouPopulationService;
    @Autowired
    private IKuaishouPopulationGroupService populationGroupService;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private IKuaishouMaterialPoolOperationRecordService kuaishouMaterialPoolOperationRecordService;

    @Value("${zip.local.download-path}")
    private String downloadPath;

    @Override
    public Result<Object> createEntity(KuaishouPopulationPackage kuaishouPopulationPackage) {
        QueryWrapper<KuaishouPopulationPackage> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", kuaishouPopulationPackage.getProjectId());
        wrapper.eq("orientation_name", kuaishouPopulationPackage.getOrientationName());
        wrapper.eq("data_status", 1);
        wrapper.last("limit 1");
        KuaishouPopulationPackage checkName = kuaishouPopulationPackageMapper.selectOne(wrapper);
        if (!Check.isNull(checkName)) {
            return Result.error("该项目下已存在人群包名，请重新输入！");
        }

        String url = kuaishouPopulationPackage.getUrl();
        String newFileUrl = getDownloadPath(url);
        if (Check.isNull(newFileUrl)) {
            return Result.error("本地下载文件失败，路径：" + url);
        }
        String md5 = null;
        try {
            md5 = LoadFileUtil.getMD5(newFileUrl);
        } catch (IOException e) {
            log.error("获取MD5签名失败", e);
        }

        QueryWrapper<KuaishouPopulationPackage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", kuaishouPopulationPackage.getProjectId());
        queryWrapper.eq("signature", md5);
        queryWrapper.eq("data_status", 1);
        queryWrapper.last("limit 1");
        KuaishouPopulationPackage one = kuaishouPopulationPackageMapper.selectOne(queryWrapper);
        if (!Check.isNull(one)) {
            return Result.error("该项目已上传过此人群包，人群包名为：" + one.getOrientationName());
        }
        kuaishouPopulationPackage.setSignature(md5);
        kuaishouPopulationPackage.setDataStatus(1);
        kuaishouPopulationPackage.setStatDate(DateUtils.formatDate(new Date()));
        this.save(kuaishouPopulationPackage);
        LoadFileUtil.delFile(newFileUrl);
        return Result.ok("上传成功");
    }

    /**
     * 文件下载到本地的路径
     */
    private String getDownloadPath(String url) {
        StringBuffer path = new StringBuffer();
        path.append(downloadPath).append(DateUtils.getNowDate(DateUtils.WEB_FORMAT)).append("/").append(UUID.randomUUID().toString()).append("/");
        if (!url.contains("http")) {
            url = "https:".concat(url);
        }
        return LoadFileUtil.downLoadFromUrl(url, path.toString());
    }

    @Override
    public Result<Object> push(JSONArray accountIds, Long id, JSONObject request) {
        KuaishouPopulationPackage pPackage = kuaishouPopulationPackageMapper.selectById(id);
        if (Check.isNull(pPackage)) {
            return Result.error("没有获取到人群包");
        }
        String newFileUrl = getDownloadPath(pPackage.getUrl());
        if (Check.isNull(newFileUrl)) {
            return Result.error("本地下载文件失败，路径：" + pPackage.getUrl());
        }
        request.put("projectId",pPackage.getProjectId());
        for (Object account : accountIds) {
            Long accountId = Long.valueOf(String.valueOf(account));
            KuaishouPopulationPackageRel relEntity = relMapper.queryEntity(accountId, pPackage.getId());
            //查询该定向模板下是否存在有效的账户数据，不存在执行推送或者上传。
            if (Check.isNull(relEntity)) {
                //查询账户同一主题下可推送的该人群包ID
                KuaishouPopulationPackageRel populationPackageRel = relMapper.queryPushableCrowdPackage(accountId, pPackage.getId());
                if (Check.isNull(populationPackageRel)) {
                    //执行上传操作
                    uploadAccount(pPackage, accountId, newFileUrl);
                } else {
                    //执行跨账户推送操作
                    pushAccount(populationPackageRel, pPackage, accountId);
                }
            }
        }
        kuaishouMaterialPoolOperationRecordService.addRecord(request, "/kuaishouPopulationPackage/push", 2, "push");
        LoadFileUtil.delFile(newFileUrl);
        return Result.ok("推送结束");
    }


    /**
     * 执行推送操作
     */
    private void pushAccount(KuaishouPopulationPackageRel populationPackageRel, KuaishouPopulationPackage pPackage, Long accountId) {
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        JSONArray array = new JSONArray();
        array.add(accountId);
        JSONObject jsonObject = kuaishouPopulationService.pushAccountsPopulation(token, populationPackageRel.getOrientationId(), array);
        if (jsonObject.getInteger("code") == 0) {
            List<KuaishouCrowdPack> list = new ArrayList<>();
            JSONObject data = jsonObject.getJSONObject("data");
            if (!Check.isNull(data)) {
                JSONArray success = data.getJSONArray("success");
                if (!Check.isNull(success)) {
                    populationPackageRel.setProjectId(pPackage.getProjectId());
                    populationPackageRel.setPopId(pPackage.getId());
                    populationPackageRel.setAccountId(Long.valueOf(String.valueOf(accountId)));
                    populationPackageRel.setMessage("OK");
                    populationPackageRel.setStatDate(DateUtils.formatDate(new Date()));
                }
                JSONArray fail = data.getJSONArray("fail");
                if (!Check.isNull(fail)) {
                    KuaishouPopulationPackageRel fRel = relMapper.queryByAccountId(accountId, populationPackageRel.getOrientationId());
                    if (Check.isNull(fRel)) {
                        populationPackageRel = new KuaishouPopulationPackageRel();
                        populationPackageRel.setProjectId(pPackage.getProjectId());
                        populationPackageRel.setPopId(pPackage.getId());
                        populationPackageRel.setSignature(pPackage.getSignature());
                        populationPackageRel.setDataStatus(0);
                        populationPackageRel.setOrientationName(pPackage.getOrientationName());
                        populationPackageRel.setAccountId(accountId);
                        populationPackageRel.setMessage("推送失败");
                        populationPackageRel.setStatDate(DateUtils.formatDate(new Date()));
                    }
                }
            }
        } else {
            populationPackageRel = new KuaishouPopulationPackageRel();
            populationPackageRel.setProjectId(pPackage.getProjectId());
            populationPackageRel.setPopId(pPackage.getId());
            populationPackageRel.setDataStatus(0);
            populationPackageRel.setSignature(pPackage.getSignature());
            populationPackageRel.setAccountId(accountId);
            populationPackageRel.setOrientationName(pPackage.getOrientationName());
            populationPackageRel.setMessage(jsonObject.getString("message"));
            populationPackageRel.setStatDate(DateUtils.formatDate(new Date()));
        }
        List<KuaishouPopulationPackageRel> packageRels = new ArrayList(1);
        packageRels.add(populationPackageRel);
        relMapper.replaceBatch(packageRels);
    }

    //**执行上传操作*/
    private void uploadAccount(KuaishouPopulationPackage pPackage, Long accountId, String newFileUrl) {
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        KuaishouPopulationPackageRel packageRel = null;
        JSONObject jsonObject = kuaishouPopulationService.updatePopulation(token, pPackage.getType(), pPackage.getOrientationName(), newFileUrl);
        if (!Check.isNull(jsonObject)) {
            if (jsonObject.getInteger("code") == 0) {
                packageRel = JSONObject.toJavaObject(jsonObject.getJSONObject("data"), KuaishouPopulationPackageRel.class);
                packageRel.setSignature(pPackage.getSignature());
                packageRel.setMessage(jsonObject.getString("message"));
                packageRel.setStatDate(DateUtils.formatDate(new Date()));
                packageRel.setProjectId(pPackage.getProjectId());
                packageRel.setPopId(pPackage.getId());
                packageRel.setDataStatus(1);//成功
            } else {
                packageRel = new KuaishouPopulationPackageRel();
                packageRel.setAccountId(accountId);
                packageRel.setOrientationName(pPackage.getOrientationName());
                packageRel.setSignature(pPackage.getSignature());
                packageRel.setMessage(jsonObject.getString("message"));
                packageRel.setStatDate(DateUtils.formatDate(new Date()));
                packageRel.setProjectId(pPackage.getProjectId());
                packageRel.setPopId(pPackage.getId());
                packageRel.setDataStatus(0);
            }
        } else {
            packageRel = new KuaishouPopulationPackageRel();
            packageRel.setAccountId(accountId);
            packageRel.setOrientationName(pPackage.getOrientationName());
            packageRel.setSignature(pPackage.getSignature());
            packageRel.setMessage("上传失败，返回结果为空");
            packageRel.setStatDate(DateUtils.formatDate(new Date()));
            packageRel.setProjectId(pPackage.getProjectId());
            packageRel.setPopId(pPackage.getId());
            packageRel.setDataStatus(0);
        }
        List<KuaishouPopulationPackageRel> packageRels = new ArrayList(1);
        packageRels.add(packageRel);
        relMapper.replaceBatch(packageRels);
    }

    @Override
    public Result<Object> queryPageList(KuaishouPopulationPackage kuaishouPopulationPackage, Integer pageNo, Integer pageSize) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = null;
        if (!Check.isNull(user)) {
            userId = user.getId();
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            //角色为管理员、销售、媒介可以查看所有项目信息
            if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
                userId = null;
            }
        }
        Long total = kuaishouPopulationPackageMapper.queryPageListTotal(userId, kuaishouPopulationPackage.getProjectId(), kuaishouPopulationPackage.getOrientationName());
        PageHelper.startPage(pageNo, pageSize, false);
        List<JSONObject> list = kuaishouPopulationPackageMapper.queryPageList(userId, kuaishouPopulationPackage.getProjectId(), kuaishouPopulationPackage.getOrientationName());
        if (!Check.isNull(list)) {
            for (JSONObject object : list) {
                object.put("unitCount", kuaishouPopulationPackageMapper.queryUnitCount(object.getLong("id")));
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setTotal(total);
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> queryPushResults(Long id, JSONArray accountIds) {
        List<JSONObject> list = relMapper.queryPushResults(id, accountIds);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public Result<Object> queryPushHistory(Long id) {
        List<JSONObject> list = relMapper.queryPushResults(id, null);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public Result<Object> getRelatedAccounts(Long id) {
        List<JSONObject> list = relMapper.getRelatedAccounts(id);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public Result<Object> getRelatedGroups(Long id, Long accountId) {
        List<JSONObject> list = kuaishouPopulationPackageMapper.getRelatedGroups(id, accountId);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public void crowdListQuery() {
        List<JSONObject> objs = kuaishouPopulationPackageMapper.queryListByStatus();
        for (JSONObject o : objs) {
            Long accountId = o.getLong("account_id");
            Long projectId = o.getLong("project_id");
            Hashtable newIds = new Hashtable();
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            if (!Check.isNull(token)) {
                for (int i = 0; i <= 7; i++) {
                    if (i != 2) {
                        JSONObject jsonObject = iKuaishouPopulationService.getPopulationList(accountId, token.getAccessToken(), i);
                        if (jsonObject.getInteger("code") == 0) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (!Check.isNull(data)) {
                                JSONArray details = data.getJSONArray("details");
                                if (details.size() > 0) {
                                    List<KuaishouPopulationPackageRel> list = new ArrayList<>();
                                    for (int j = 0; j < details.size(); j++) {
                                        JSONObject obj = details.getJSONObject(j);
                                        KuaishouPopulationPackageRel rel = JSONObject.parseObject(obj.toJSONString(), KuaishouPopulationPackageRel.class);
                                        newIds.put(rel.getOrientationId(), rel.getOrientationId());
                                        if (Check.isNull(relMapper.queryByOrientationId(rel.getOrientationId(), rel.getAccountId()))) {
                                            rel.setProjectId(projectId);
                                            rel.setDataStatus(1);
                                            rel.setStatDate(DateUtils.formatDate(new Date()));
                                            list.add(rel);
                                        } else {
                                            rel.setDataStatus(1);
                                            relMapper.updateStatus(rel);
                                        }
                                    }
                                    if (!Check.isNull(list)) {
                                        relMapper.replaceBatch(list);
                                    }
                                }
                            }
                        }
                    }
                }
                //查询现有的人群包ID集
                List<Long> oldOrientationIds = relMapper.queryByOrientationId(null, accountId);
                if (oldOrientationIds.size() != newIds.size()) {
                    for (Long id : oldOrientationIds) {
                        if (!newIds.contains(id)) {
                            KuaishouPopulationPackageRel rel = new KuaishouPopulationPackageRel();
                            rel.setDataStatus(0);
                            rel.setOrientationId(id);
                            rel.setAccountId(accountId);
                            rel.setMessage("人群包已从媒体后台删除");
                            relMapper.updateStatus(rel);
                        }
                    }
                }
            }
        }
    }

    @Override
    public Result<Object> getAccountByProjectId(Long projectId, String id) {
        List<JSONObject> list = relMapper.getAccountByProjectId(projectId, id);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public Result<Object> checkPopulationPackage(String signature) {
        KuaishouPopulationPackage ksPackage = kuaishouPopulationPackageMapper.checkPopulationPackage(signature);
        if (Check.isNull(ksPackage)) {
            return Result.ok("success");
        } else {
            Result<Object> r = new Result<>();
            r.setCode(201);
            r.setMessage("项目已保存过该人群包，名称为：" + ksPackage.getOrientationName());
            r.setSuccess(true);
            return r;
        }
    }

}
