package com.zhongshu.card.server.core.service.paySetting;

import com.github.microservice.net.ResultContent;
import com.github.microservice.types.payment.PaymentType;
import com.zhongshu.card.client.model.paySetting.paySetting.PayShareListModel;
import com.zhongshu.card.client.model.paySetting.paySetting.PayShareListParam;
import com.zhongshu.card.client.model.paySetting.paySetting.ProjectMainPaySettingModel;
import com.zhongshu.card.client.model.paySetting.paySetting.ProjectMainPaySettingParam;
import com.zhongshu.card.client.type.paySetting.RegularType;
import com.zhongshu.card.client.type.paySetting.SettlementRulesType;
import com.zhongshu.card.client.utils.DateUtils;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.projectAbout.PayShareListDao;
import com.zhongshu.card.server.core.dao.projectAbout.ProjectMainPaySettingDao;
import com.zhongshu.card.server.core.dao.projectAbout.ProjectOrgPaySettingInfoDao;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.paySetting.PayShareList;
import com.zhongshu.card.server.core.domain.paySetting.ProjectMainPaySetting;
import com.zhongshu.card.server.core.domain.paySetting.ProjectOrgPaySettingInfo;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.schedule.ScheduleTaskConfigService;
import com.zhongshu.card.server.core.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

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

/**
 * 项目的配置
 *
 * @author TRX
 * @date 2024/11/5
 */
@Slf4j
@Service
public class ProjectMainPaySettingService extends SuperService {

    @Autowired
    private ProjectMainPaySettingDao projectMainPaySettingDao;

    @Autowired
    private ProjectOrgPaySettingInfoDao projectPaySettingInfoDao;

    @Autowired
    private PayShareListDao payShareListDao;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private ScheduleTaskConfigService scheduleTaskConfigService;

    @Autowired
    private ProjectPaySettingServiceImpl projectPaySettingService;

    /**
     * 保存项目配置
     *
     * @param param
     * @return
     */
    public ResultContent saveMainPaySetting(ProjectMainPaySettingParam param) {
        if (StringUtils.isEmpty(param.getProjectOid())) {
            return ResultContent.buildFail("projectOid不能为空");
        }

        ProjectOrgPaySettingInfo orgPaySettingInfo = projectPaySettingInfoDao.findTopById(param.getPaySettingInfoId());
        if (ObjectUtils.isEmpty(orgPaySettingInfo)) {
            return ResultContent.buildFail("主账号数据不存在");
        }
        if (orgPaySettingInfo.getIsDefault() == null || !orgPaySettingInfo.getIsDefault()) {
            return ResultContent.buildFail("选择的不是主账户类型");
        }

        // 子商户信息
        ProjectOrgPaySettingInfo childPaySettingInfo = null;
        if (StringUtils.isNotEmpty(param.getChildPaySettingInfoId())) {
            childPaySettingInfo = projectPaySettingInfoDao.findTopById(param.getChildPaySettingInfoId());
        }

        if (param.getSettlementRulesType() == SettlementRulesType.Dn) {
            if (StringUtils.isEmpty(param.getDnTimeStr())) {
                return ResultContent.buildFail("dnTimeStr不能为空");
            }
            param.setRegularTimeStr("");
        }
        if (param.getSettlementRulesType() == SettlementRulesType.Regular) {
            if (StringUtils.isEmpty(param.getRegularTimeStr())) {
                return ResultContent.buildFail("regularTimeStr不能为空");
            }
            param.setDnTimeStr("");
        }
        // 项目 的分成
        BigDecimal projectScale = param.getProjectScale();
        if (projectScale != null) {
            if (BigDecimal.ZERO.compareTo(projectScale) == 1 || BigDecimal.valueOf(100).compareTo(projectScale) == -1) {
                return ResultContent.buildFail("projectScale不符合要求");
            }
        }
        // 机构 的分成
        BigDecimal orgScale = param.getOrgScale();
        if (projectScale != null) {
            if (BigDecimal.ZERO.compareTo(orgScale) == 1 || BigDecimal.valueOf(100).compareTo(orgScale) == -1) {
                return ResultContent.buildFail("orgScale不符合要求");
            }
        }
        BigDecimal all = orgScale.add(projectScale);
        if (all.compareTo(BigDecimal.valueOf(100)) != 0) {
            return ResultContent.buildFail("项目分成和机构分成之和不等100");
        }

        // 提现额度
        Long minWithdraw = param.getMinWithdraw();
        Long maxWithdraw = param.getMaxWithdraw();
        if (minWithdraw <= 0 || maxWithdraw <= 0) {
            return ResultContent.buildFail("minWithdraw或maxWithdraw不能小于等于0");
        }
        if (minWithdraw > maxWithdraw) {
            return ResultContent.buildFail("minWithdraw不能大于maxWithdraw");
        }

        ProjectMainPaySetting mainPaySetting = projectMainPaySettingDao.findTopByProjectOidAndChannelType(param.getProjectOid(), orgPaySettingInfo.getChannelType());
        if (ObjectUtils.isEmpty(mainPaySetting)) {
            mainPaySetting = new ProjectMainPaySetting();
        }
        BeanUtils.copyProperties(param, mainPaySetting);

        // 主商户信息
        mainPaySetting.setPaySettingInfo(orgPaySettingInfo);
        mainPaySetting.setBelongOig(orgPaySettingInfo.getBelongOig());
        mainPaySetting.setBelongOrgName(orgPaySettingInfo.getBelongOrgName());

        // 主账户的子商户信息
        mainPaySetting.setChildPaySettingInfo(childPaySettingInfo);

        mainPaySetting.setChannelType(orgPaySettingInfo.getChannelType());
        mainPaySetting.setPaymentChannelType(orgPaySettingInfo.getPaymentChannelType());

        projectMainPaySettingDao.save(mainPaySetting);
        // 加入结算定时任务
        scheduleTaskConfigService.initProjectSettlementRulesTask(mainPaySetting);
        return ResultContent.buildSuccess();
    }

    /**
     * 查询主商户的 商户号
     *
     * @param projectOid
     * @param paymentType
     * @return
     */
    public String getProjectPaymentMchId(String projectOid, PaymentType paymentType) {
        ProjectMainPaySetting mainPaySetting = projectMainPaySettingDao.findTopByProjectOidAndChannelType(projectOid, paymentType);
        if (mainPaySetting != null) {
            ProjectOrgPaySettingInfo paySettingInfo = mainPaySetting.getPaySettingInfo();
            if (paySettingInfo != null) {
                return paySettingInfo.getMchId();
            }
        }
        return "";
    }

    /**
     * 得到项目配置
     *
     * @param projectOid
     * @return
     */
    public ResultContent<ProjectMainPaySettingModel> getMainPaySetting(String projectOid, PaymentType paymentType) {
        ProjectMainPaySetting mainPaySetting = getProjectMainPaySetting(projectOid, paymentType);
        ProjectMainPaySettingModel model = toMainModel(mainPaySetting);
        model.setProjectOid(projectOid);
        return ResultContent.buildSuccess(model);
    }

    public ProjectMainPaySetting getProjectMainPaySetting(String projectOid, PaymentType paymentType) {
        if (StringUtils.isNotEmpty(projectOid) && paymentType != null) {
            return projectMainPaySettingDao.findTopByProjectOidAndChannelType(projectOid, paymentType);
        }
        return null;
    }

    /**
     * 得到结算定时任务的结算时间
     *
     * @param projectOid
     * @param paymentType
     * @return
     */
    public Long getCurrentRunTime(String projectOid, PaymentType paymentType) {
        Long time = System.currentTimeMillis();
        if (StringUtils.isNotEmpty(projectOid) && paymentType != null) {
            ProjectMainPaySetting entity = getProjectMainPaySetting(projectOid, paymentType);
            if (ObjectUtils.isNotEmpty(entity)) {
                SettlementRulesType settlementRulesType = entity.getSettlementRulesType();
                if (settlementRulesType == SettlementRulesType.Dn) {
                    // 结算N天前的
                    Integer days = entity.getDays();
                    Calendar c = Calendar.getInstance();
                    c.setTimeInMillis(System.currentTimeMillis());
                    c.add(Calendar.DATE, days * -1);
                    time = c.getTimeInMillis();
                } else if (settlementRulesType == SettlementRulesType.Regular) {
                    RegularType regularType = entity.getRegularType();
                    if (regularType == RegularType.Day) {
                        Calendar c = Calendar.getInstance();
                        c.setTimeInMillis(System.currentTimeMillis());
                        c.add(Calendar.DATE, -1);
                        time = c.getTimeInMillis();
                    } else if (regularType == RegularType.Week) {
                        time = DateUtils.getPreWeekLastTime();
                    } else if (regularType == RegularType.Month) {
                        time = DateUtils.getPreMonthLastTime();
                    }
                }
            }
        }
        return time;
    }

    //---------------------------项目上的灵活 分账配置 start -----------------------

    /**
     * 保存项目的灵活分账规则
     *
     * @param param
     * @return
     */
    public ResultContent savePayShareList(PayShareListParam param) {
        if (StringUtils.isEmpty(param.getProjectOid())) {
            return ResultContent.buildFail("projectOid不能为空");
        }
        if (param.getPaymentType() == null) {
            return ResultContent.buildFail("paymentType不能为空");
        }
        Organization projectInfo = organizationDao.findTopByOid(param.getProjectOid());
        PayShareList entity = null;
        PayShareList nameTemp = payShareListDao.findTopByProjectOidAndNameAndPaymentType(param.getProjectOid(), param.getName(), param.getPaymentType());
        if (StringUtils.isNotEmpty(param.getId())) {
            entity = payShareListDao.findTopById(param.getId());
            if (ObjectUtils.isEmpty(entity)) {
                return ResultContent.buildFail("id不存在");
            }
            if (ObjectUtils.isNotEmpty(nameTemp) && !nameTemp.getId().equals(entity.getId())) {
                return ResultContent.buildFail(String.format("名称已存在：%s", param.getName()));
            }
            initUpdateEntity(entity);
        } else {
            if (ObjectUtils.isNotEmpty(nameTemp)) {
                return ResultContent.buildFail(String.format("名称已存在：%s", param.getName()));
            }
            entity = new PayShareList();
            initEntityNoCheckOid(entity);
        }
        // 项目 的分成
        BigDecimal projectScale = param.getProjectScale();
        if (projectScale != null) {
            if (BigDecimal.ZERO.compareTo(projectScale) == 1 || BigDecimal.valueOf(100).compareTo(projectScale) == -1) {
                return ResultContent.buildFail("projectScale不符合要求");
            }
        }
        // 机构 的分成
        BigDecimal orgScale = param.getOrgScale();
        if (projectScale != null) {
            if (BigDecimal.ZERO.compareTo(orgScale) == 1 || BigDecimal.valueOf(100).compareTo(orgScale) == -1) {
                return ResultContent.buildFail("orgScale不符合要求");
            }
        }
        BigDecimal all = orgScale.add(projectScale);
        if (all.compareTo(BigDecimal.valueOf(100)) != 0) {
            return ResultContent.buildFail("项目分成和机构分成之和不等100");
        }

        BeanUtils.copyProperties(param, entity);
        entity.setProjectInfo(projectInfo);
        entity.setProjectCode(projectInfo.getCode());
        entity.setProjectName(projectInfo.getName());

        payShareListDao.save(entity);
        return ResultContent.buildSuccess();
    }

    public ResultContent<List<PayShareListModel>> getPayShareList(String projectOid, PaymentType paymentType) {
        List<PayShareList> list = payShareListDao.findByProjectOidAndPaymentTypeOrderBySortAsc(projectOid, paymentType);
        List<PayShareListModel> models = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)) {
            models = list.stream().map(this::toModel).collect(Collectors.toUnmodifiableList());
        }
        return ResultContent.buildSuccess(models);
    }

    /**
     * 删除分账灵活规则
     *
     * @param id
     * @return
     */
    public ResultContent deletePayShareList(String id) {
        PayShareList entity = payShareListDao.findTopById(id);
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail("数据不存在");
        }
        payShareListDao.delete(entity);
        return ResultContent.buildSuccess();
    }

    public PayShareListModel toModel(PayShareList entity) {
        PayShareListModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new PayShareListModel();
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

    public ProjectMainPaySettingModel toMainModel(ProjectMainPaySetting entity) {
        ProjectMainPaySettingModel model = new ProjectMainPaySettingModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new ProjectMainPaySettingModel();
            BeanUtils.copyProperties(entity, model);

            ProjectOrgPaySettingInfo paySettingInfo = entity.getPaySettingInfo();
            if (ObjectUtils.isNotEmpty(paySettingInfo)) {
                model.setPaySettingInfoId(paySettingInfo.getId());
                model.setPaySettingInfoName(paySettingInfo.getName());
            }
            model.setSettingInfoModel(projectPaySettingService.toModel(entity.getPaySettingInfo()));

            model.setChildPaySettingInfo(projectPaySettingService.toModel(entity.getChildPaySettingInfo()));
        }
        return model;
    }
}
