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

import cn.com.ctop.common.module.entity.SysUser;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyAccountService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.entity.TransferAccount;
import org.jeecg.modules.ctop.service.ITransferAccountService;
import org.jeecg.modules.performance.constants.PeriodConstant;
import org.jeecg.modules.performance.entity.OperateDetail;
import org.jeecg.modules.performance.mapper.OperateDetailMapper;
import org.jeecg.modules.performance.service.IOperateDetailService;
import org.jeecg.modules.performance.vo.TransferDetailVO;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 运营消耗详细
 */
@Service
@Slf4j
public class OperateDetailServiceImpl extends ServiceImpl<OperateDetailMapper, OperateDetail> implements IOperateDetailService {

    @Autowired
    private OperateDetailMapper operateDetailMapper;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private ITransferAccountService transferAccountService;
    @Autowired
    private IKuaishouReportDailyAccountService dailyAccountService;
    @Autowired
    private ISysUserRoleService roleService;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 快手账户消耗计算
     */
    @Override
    public void KsCostCalculateByAccount(String startStatDate, String endStatDate) {

        List<UserAllocation> list = userAllocationService.getByMediaId(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        for (UserAllocation allocation : list) {
            List<TransferDetailVO> transferDetailVOS = loadTransferDetail(allocation.getAccountId(), allocation.getUserId(), startStatDate, endStatDate);
            if (Check.isNull(transferDetailVOS)) {
                log.error("错误，未返回转户信息，accountId：{}", allocation.getAccountId());
                continue;
            }
            for (TransferDetailVO transferDetail : transferDetailVOS) {
                String userId = transferDetail.getUserId();
                Long accountId = transferDetail.getAccountId();
                String startDate = transferDetail.getStartDate();
                String endDate = transferDetail.getEndDate();
                String leaderId = roleService.getLeaderId(userId, "kuaishouOperationManager");
                List<JSONObject> costJsonArr = dailyAccountService.selectCost(accountId, startDate, endDate);
                if (!Check.isNull(costJsonArr)) {
                    costJsonArr.stream().filter(costJson -> !Check.isNull(costJson)).forEach(costJson -> {
                        BigDecimal cost = costJson.getBigDecimal("cost");
                        if (Check.isNull(cost)) {
                            return;
                        }
                        OperateDetail detail = new OperateDetail();
                        detail.setCost(cost);
                        detail.setAccountId(accountId);
                        detail.setStatDate(costJson.getString("statDate"));
                        detail.setLeaderId(leaderId);
                        detail.setUserId(userId);
                        detail.setMediaType(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
                        //TODO 判断是否为节假日
                        operateDetailMapper.insert(detail);
                    });

                }
            }
        }

    }


    /**
     * 头条账户消耗计算
     */
    @Override
    public void BtCostCalculateByAccount(String startStatDate, String endStatDate) {

        //1:获取头条账户
        List<UserAllocation> allocations = userAllocationService.getByMediaId(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
        if (allocations.isEmpty()) {
            log.info("获取头条用户失败");
            return;
        }
        allocations.forEach(allocation->{
            List<TransferDetailVO> transferDetailVOS = loadTransferDetail(allocation.getAccountId(), allocation.getUserId(), startStatDate, endStatDate);
            if (null != transferDetailVOS && transferDetailVOS.size() > 0) {
                transferDetailVOS.forEach(vo->{
                    SysUser user = sysUserService.getById(vo.getUserId());
                    List<OperateDetail> details = operateDetailMapper.selectBytedanceByParams(allocation.getAccountId(), vo.getStartDate() + " 00:00:00", vo.getEndDate() + "00:00:00", vo.getUserId(), user.getOrgCode());
                    if (!details.isEmpty()) {
                        details.forEach(detail->{
                            if (null != detail && null != detail.getCost()) {
                                if (detail.getUserId().equals(detail.getLeaderId())) {
                                    detail.setLeaderId(null);
                                }
                                //TODO 判断是否为节假日
                                this.save(detail);
                            }
                        });
                    }
                });
            }
        });
    }

    @Override
    public List<TransferDetailVO> loadTransferDetail(Long accountId, String userId, String startDate, String endDate) {
        List<TransferDetailVO> vos = new ArrayList<>();
        String realEndDate = DateUtils.addDay(endDate, -1);
        List<TransferAccount> transferAccounts = transferAccountService.getAccountQuarterDetail(accountId, startDate, endDate);
        if (Check.isNull(transferAccounts)) {
            vos.add(new TransferDetailVO(startDate, endDate, userId, accountId));
            return vos;
        } else if (transferAccounts.size() == 1) {
            TransferAccount account = transferAccounts.get(0);
            if (account.getTransferorDate().equals(startDate)) {
                //极限情况 季度末最后一天转让
                vos.add(new TransferDetailVO(startDate, endDate, userId, accountId));
                return vos;
            } else {
                vos.add(new TransferDetailVO(startDate, account.getAssigneeDate(), userId, accountId));
                vos.add(new TransferDetailVO(account.getAssigneeDate(), endDate, userId, accountId));
                return vos;
            }
        } else {
            TransferAccount firstAccount = transferAccounts.get(0);
            TransferAccount lastAccout = transferAccounts.get(transferAccounts.size() - 1);
            vos.add(new TransferDetailVO(startDate, firstAccount.getAssigneeDate(), firstAccount.getTransferor(), accountId));
            String lastTwoAssigneeDate = "";
            for (int i = 1; i <= transferAccounts.size() - 1; i++) {
                TransferAccount account = transferAccounts.get(i);
                TransferAccount preAccount = transferAccounts.get(i - 1);
                vos.add(new TransferDetailVO(preAccount.getAssigneeDate(), account.getAssigneeDate(), account.getTransferor(), accountId));
                lastTwoAssigneeDate = account.getAssigneeDate();
            }
            if (lastAccout.getTransferorDate().equals(realEndDate)) {
                //最后一条数据的转让时间为季度末尾
                vos.add(new TransferDetailVO(lastTwoAssigneeDate, endDate, lastAccout.getTransferor(), accountId));
            } else {
                vos.add(new TransferDetailVO(lastTwoAssigneeDate, lastAccout.getAssigneeDate(), lastAccout.getTransferor(), accountId));
                vos.add(new TransferDetailVO(lastAccout.getAssigneeDate(), endDate, lastAccout.getAssignee(), accountId));
            }
            vos = vos.parallelStream().filter(
                    vo -> !vo.getStartDate().equals(vo.getEndDate())
            ).collect(Collectors.toList());
        }
        return vos;
    }

    @Override
    public List<JSONObject> getOperateGroupAccountByUser(JSONObject requestBody) {
        String userId=requestBody.getString("userId");
        int year= requestBody.getInteger("year");
        String quarter=requestBody.getString("quarter");
        int mediaType=requestBody.getInteger("mediaType");
        String startDate= year+"-"+ PeriodConstant.valueOf(quarter).getStart();
        String endDate= year+"-"+PeriodConstant.valueOf(quarter).getEnd();
        List<JSONObject> result=new ArrayList<>();
        if(mediaType==CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT){
            result=operateDetailMapper.ByteDanceOperateDetailGroupAccountByDate(startDate,endDate,userId);
        }else if(mediaType==CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT){
            result=operateDetailMapper.kuaiShouOperateDetailGroupAccountByDate(startDate,endDate,userId);
        }
        return result;
    }
}
