package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.AdqAdvertiserInfo;
import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.AdqAccountClaimMapper;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.IAdqAccountClaimService;
import cn.com.ctop.common.module.service.IProjectService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ADQ账户认领 Service实现
 *
 * @author jeecg-boot
 */
@Slf4j
@Service
public class AdqAccountClaimServiceImpl extends ServiceImpl<AdqAccountClaimMapper, AdqAdvertiserInfo> implements IAdqAccountClaimService {

    @Resource
    private AdqAccountClaimMapper adqAccountClaimMapper;

    @Autowired
    private UserAllocationMapper userAllocationMapper;

    @Autowired
    private IProjectService projectService;

    @Override
    public JSONObject queryUnclaimedAccounts(String accountIds, String advertiserName, Integer pageNo, Integer pageSize) {
        JSONObject result = new JSONObject();
        int offset = (pageNo - 1) * pageSize;
        // 解析多个账户ID（支持逗号、换行、空格分隔）
        List<Long> accountIdList = null;
        if (accountIds != null && !accountIds.trim().isEmpty()) {
            accountIdList = Arrays.stream(accountIds.split("[,，\\s\\n]+"))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
        }
        List<JSONObject> list = adqAccountClaimMapper.queryUnclaimedAccounts(accountIdList, advertiserName, offset, pageSize);
        Long total = adqAccountClaimMapper.countUnclaimedAccounts(accountIdList, advertiserName);
        result.put("records", list);
        result.put("total", total);
        result.put("current", pageNo);
        result.put("size", pageSize);
        return result;
    }

    @Override
    public List<JSONObject> queryAdqProjects(String projectName, String userId) {
        return adqAccountClaimMapper.queryAdqProjects(projectName, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchClaimAccounts(JSONObject claimData) throws Exception {
        Long projectId = claimData.getLong("projectId");
        JSONArray accountIds = claimData.getJSONArray("accountIds");

        if (Check.isNull(projectId)) {
            throw new Exception("请选择项目");
        }
        if (Check.isNull(accountIds) || accountIds.isEmpty()) {
            throw new Exception("请选择要认领的账户");
        }

        // 获取项目信息
        Project project = projectService.getById(projectId);
        if (Check.isNull(project)) {
            throw new Exception("项目不存在");
        }

        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        String userName = loginUser.getRealname();

        for (int i = 0; i < accountIds.size(); i++) {
            JSONObject accountObj = accountIds.getJSONObject(i);
            Long accountId = accountObj.getLong("accountId");
            String advertiserName = accountObj.getString("advertiserName");
            Long adminAdvertiserId = accountObj.getLong("adminAdvertiserId");

            // 创建UserAllocation记录
            UserAllocation allocation = new UserAllocation();
            allocation.setUserId(userId);
            allocation.setUserName(userName);
            allocation.setAccountId(accountId);
            allocation.setProjectId(projectId);
            allocation.setMediaId("16");
            allocation.setAdvertiserId(project.getAdvertiserId());
            allocation.setAuthName(advertiserName);
            allocation.setAccountStatus(0);
            allocation.setWarningAmount(null);
            allocation.setWarningProportion(null);
            allocation.setDeleteComment(1);
            allocation.setAutoDelivery(0);
            allocation.setAdminAdvertiserId(adminAdvertiserId);
            allocation.setCreateTime(new Date());
            allocation.setUpdateTime(new Date());

            userAllocationMapper.insert(allocation);
        }
    }
}
