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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
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.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouLandpagePackage;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouLandpagePackageRel;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouLandpagePackageMapper;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouLandpagePackageRelMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouLandpagePackageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 落地页账户项目关联表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-05-11
 */
@Service
public class KuaishouLandpagePackageServiceImpl extends ServiceImpl<KuaishouLandpagePackageMapper, KuaishouLandpagePackage> implements IKuaishouLandpagePackageService {

    @Resource
    private KuaishouLandpagePackageMapper landpagePackageMapper;
    @Resource
    private KuaishouLandpagePackageRelMapper landpagePackageRelMapper;
    @Autowired
    private KuaishouLandpagePackageRelServiceImpl landpagePackageRelService;

    @Resource
    private UserAllocationMapper userAllocationMapper;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private ISysRoleExtService sysRoleService;

    @Override
    public Result<Object> queryPageList(KuaishouLandpagePackage kuaishouLandpagePackage, 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;
            }
        }
        PageHelper.startPage(pageNo, pageSize);
        List<JSONObject> list = landpagePackageMapper.queryPageList(userId, kuaishouLandpagePackage.getAccountId(), kuaishouLandpagePackage.getProjectId());
        return Result.ok(new PageInfo<JSONObject>(list));
    }

    @Override
    public Result<Object> synchronousData(Long projectId) {
        try {
            List<UserAllocation> userAllocations = userAllocationMapper.selectAccountListByProjectId(projectId);
            for (UserAllocation userAllocation : userAllocations) {
                Long accountId = userAllocation.getAccountId();
                CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
                String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PAGE_LIST;
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Access-Token", oauthToken.getAccessToken());
                Map<String, Object> param = new HashMap<>();
                param.put("advertiser_id", accountId);
                param.put("page_size", 500);
                String result = HttpUtils.httpPostRequest(url, param, headers);
                JSONObject resultJson = JSON.parseObject(result);
                if (!Check.isNull(resultJson)) {
                    if (resultJson.getInteger("code") == 0) {
                        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
                        if (!Check.isNull(details)) {
                            List<KuaishouLandpagePackage> landpagePackageList = new ArrayList<>();
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject jsonObject = details.getJSONObject(i);
                                KuaishouLandpagePackage landpagePackage = getEntity(jsonObject);
                                landpagePackage.setAccountId(accountId);
                                landpagePackage.setProjectId(projectId);
                                landpagePackageList.add(landpagePackage);
                            }
                            if (!Check.isNull(landpagePackageList)) {
                                landpagePackageMapper.deleteByAccountId(accountId);
                                landpagePackageMapper.replaceBatch(landpagePackageList);
                            }

                        }
                    } else {
                        log.error(resultJson.getString("message") + "，accountId:" + accountId);
                    }
                }
            }
        } catch (Exception e) {
            log.error("同步项目下落地页和账户关联数据异常", e);
            return Result.error("同步项目下落地页和账户关联数据异常");
        }
        return Result.ok("同步成功");
    }

    /**
     * 处理对象参数
     */
    private KuaishouLandpagePackage getEntity(JSONObject jsonObject) {
        KuaishouLandpagePackage landpagePackage = new KuaishouLandpagePackage();
        landpagePackage.setLandpageName(jsonObject.getString("name"));
        landpagePackage.setSiteId(jsonObject.getLong("id"));
        landpagePackage.setUrl(jsonObject.getString("url"));
        landpagePackage.setBizType(jsonObject.getInteger("biz_type"));
       /* landpagePackage.setLandpageCreateTime(jsonObject.getSqlDate("create_time"));
        landpagePackage.setLandpageUpdateTime(jsonObject.getSqlDate("update_time"));*/
        JSONArray compsArr = jsonObject.getJSONArray("comps");
        if (!Check.isNull(compsArr)) {
            landpagePackage.setComps(JSONObject.toJSONString(compsArr));
            for (int j = 0; j < compsArr.size(); j++) {
                JSONObject compJson = compsArr.getJSONObject(j);
                JSONObject props = compJson.getJSONObject("props");
                if (!Check.isNull(props)) {
                    landpagePackage.setAppId(props.getLong("appId"));
                }
            }
        }
        return landpagePackage;
    }

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

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

    @Override
    public void createLandPageAndUnit(Long siteId, Long creativeId, Long unitId, Long accountId) {
        try {
            JSONObject entity = landpagePackageRelMapper.queryByUnitId(siteId, unitId, accountId);
            if (Check.isNull(entity)) {
                KuaishouLandpagePackageRel rel = new KuaishouLandpagePackageRel();
                rel.setUnitId(unitId);
                rel.setAccountId(accountId);
                rel.setSiteId(siteId);
                JSONArray creativeArr = new JSONArray();
                creativeArr.add(creativeId);
                rel.setCreativeArr(JSONObject.toJSONString(creativeArr));
                landpagePackageRelService.save(rel);
            } else {
                //不为空，落地页已经绑定过广告组，判断是否是新的创意
                JSONArray creative_arr = entity.getJSONArray("creative_arr");
                if (!creative_arr.contains(creativeId)) {
                    //不包含创意，则添加并更新进数据表中
                    KuaishouLandpagePackageRel rel = new KuaishouLandpagePackageRel();
                    creative_arr.add(creativeId);
                    rel.setCreativeArr(JSONObject.toJSONString(creative_arr));
                    rel.setId(entity.getLong("id"));
                    landpagePackageRelMapper.updateById(rel);
                }
            }
        } catch (Exception e) {
            log.error("绑定落地页与广告组异常", e);
        }
    }
}
