package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.utils.Check;
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.jeecg.modules.ctop.entity.MaterialUploadTask;
import org.jeecg.modules.ctop.mapper.MaterialUploadTaskMapper;
import org.jeecg.modules.ctop.service.IMaterialUploadTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同步素材任务
 *
 * @author jeecg-boot
 * 2021-10-21
 * @version V1.0
 */
@Service
public class MaterialUploadTaskServiceImpl extends ServiceImpl<MaterialUploadTaskMapper, MaterialUploadTask> implements IMaterialUploadTaskService {

    @Autowired
    private MaterialUploadTaskMapper materialUploadTaskMapper;

    /**
     * 同步素材提交任务
     *
     * @param json
     * @return
     */

    @Override
    public JSONObject submitTask(JSONObject json) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(json)) {
                throw new Exception("入参不能为空");
            }
            Integer mediaId = json.getInteger("mediaId");
            if (Check.isNull(mediaId)) {
                throw new Exception("媒体信息必传");
            }
            JSONArray materialArray = json.getJSONArray("materialArray");
            if (Check.isNull(materialArray)) {
                throw new Exception("请传入素材信息");
            }
            JSONArray accountArray = json.getJSONArray("accountArray");
            if (Check.isNull(accountArray)) {
                throw new Exception("请传入账户信息");
            }
            String loginId = json.getString("loginId");
            if (Check.isNull(loginId)) {
                throw new Exception("请传入登录人id");
            }
            String userName = json.getString("userName");
            if (Check.isNull(userName)) {
                throw new Exception("请传入登录人姓名");
            }
            Integer isMultiagent = json.getInteger("isMultiagent");
            if (Check.isNull(isMultiagent)) {
                throw new Exception("请传入主体信息");

            }

            Map<String, JSONObject> useMap = new HashMap<>();
            List<MaterialUploadTask> tasksList = new ArrayList<>();
            Integer shieldBackwardSwitch = null;
            for (int j = 0; j < materialArray.size(); j++) {
                String materialId = materialArray.getString(j);
                JSONObject materialInfo = materialUploadTaskMapper.getMaterialNameBySignature(materialId);
                if (Check.isNull(materialInfo)) {
                    continue;
                }
                String materialName = materialInfo.getString("materialName");
                String materialUrl = materialInfo.getString("materialUrl");
                String signature = materialInfo.getString("signature");
                for (int i = 0; i < accountArray.size(); i++) {
                    Long accountId = null;
                    Long userId = null;
                    if (mediaId == 2 || mediaId == 4) {
                        JSONObject accountJson = accountArray.getJSONObject(i);
                        if (Check.isNull(accountJson)) {
                            continue;
                        }
                        userId = accountJson.getLong("userId");
                        accountId = accountJson.getLong("accountId");
                        if (isMultiagent == 1) {
                            Integer count = materialUploadTaskMapper.getCountByUserIdAndMd5(userId, signature);
                            if (count > 0) {
                                getUseMap(useMap, userId, materialName, signature);
                                continue;
                            }
                        } else if (isMultiagent == 2) {
                            Integer count = materialUploadTaskMapper.getCountByaccountIdAndMd5(userId, accountId, signature);
                            if (count > 0) {
                                getUseMap(useMap, userId, materialName, signature);
                                continue;
                            }
                        }

                        shieldBackwardSwitch = json.getInteger("shieldBackwardSwitch");
                    } else if (mediaId == 1 || mediaId == 3) {
                        accountId = accountArray.getLong(i);
                        if (Check.isNull(accountId)) {
                            continue;
                        }
                        Integer count = materialUploadTaskMapper.getCountByAccountIdAndMd5(accountId, signature);
                        if (count > 0) {
                            getUseMap(useMap, accountId, materialName, signature);
                            continue;
                        }
                    }
                    MaterialUploadTask task = new MaterialUploadTask();
                    task.setAccountId(accountId);
                    if (!Check.isNull(userId)) {
                        task.setKuaishouUserId(userId);
                    }
                    task.setShieldBackwardSwitch(shieldBackwardSwitch);
                    task.setMediaId(mediaId);
                    task.setSignature(signature);
                    task.setUserId(loginId);
                    task.setUserName(userName);
                    task.setMaterialName(materialName);
                    task.setMaterialUrl(materialUrl);
                    task.setTaskStatus(0);
                    task.setRemarks("素材待同步");
                    tasksList.add(task);
                }
            }
            if (!Check.isNull(tasksList)) {
                materialUploadTaskMapper.replaceBatch(tasksList);
            }
            returnJson.put("code", 0);
            returnJson.put("message", "任务提交成功");
            if (!Check.isNullMap(useMap)) {
                JSONArray array = new JSONArray();
                for (Map.Entry<String, JSONObject> entry : useMap.entrySet()) {
                    JSONObject mapValue = entry.getValue();
                    array.add(mapValue);
                }
                returnJson.put("data", array);
            }
        } catch (Exception e) {
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }

        return returnJson;
    }

    @Override
    public PageInfo<List<JSONObject>> uploadDetail(String signature, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize, false);
        List<JSONObject> details = materialUploadTaskMapper.uploadDetail(signature);
        Integer total = materialUploadTaskMapper.getCount(signature);
        PageInfo pageInfo = new PageInfo(details);
        pageInfo.setTotal(total);
        return pageInfo;
    }


    private Map<String, JSONObject> getUseMap(Map<String, JSONObject> userMap, Long userId, String materialName, String signature) {
        JSONObject useJson = userMap.get(signature);
        if (Check.isNull(useJson)) {
            JSONObject addJson = new JSONObject();
            addJson.put("materialName", materialName);
            addJson.put("message", "此素材正在同步中或已同步");
            JSONArray userIdArray = new JSONArray();
            userIdArray.add(userId);
            addJson.put("ids", userIdArray);
            userMap.put(signature, addJson);

        } else {
            JSONArray userIdArray = useJson.getJSONArray("ids");
            userIdArray.add(userId);
        }
        return userMap;
    }

}
