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.PayOrderSettingModel;
import com.zhongshu.card.client.model.paySetting.paySetting.PayOrderSettingParam;
import com.zhongshu.card.client.model.projectAbout.PayChannelConfigModel;
import com.zhongshu.card.client.type.DataState;
import com.zhongshu.card.server.core.dao.projectAbout.PayOrderSettingDao;
import com.zhongshu.card.server.core.dao.projectAbout.ProjectPaySettingDao;
import com.zhongshu.card.server.core.domain.paySetting.PayOrderSetting;
import com.zhongshu.card.server.core.domain.paySetting.ProjectPaySetting;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.pay.ChinaumsSenselessPayService;
import com.zhongshu.card.server.core.service.payment.PayCallService;
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 java.util.*;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2024/11/12
 */
@Slf4j
@Service
public class PayOrderSettingService extends SuperService {

    @Autowired
    private PayOrderSettingDao payOrderSettingDao;

    @Autowired
    private ProjectPaySettingDao projectPaySettingDao;

    @Autowired
    private ProjectChannelConfigService projectChannelConfigService;

    @Autowired
    private PayCallService payCallService;

    @Autowired
    private ChinaumsSenselessPayService chinaumsSenselessPayService;

    /**
     * 得到用户的支付服务
     *
     * @return
     */
    public ResultContent<List<PayOrderSettingModel>> getUserPayOrderSetting() {
        String userId = getCurrentUserId();
        String projectOid = getCurrentProjectOid();
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(projectOid)) {
            return ResultContent.buildFail("项目信息失败");
        }

        List<PayOrderSetting> payOrderSettings = getUserPayOrderSettings(userId, projectOid);
        List<PayOrderSettingModel> models = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(payOrderSettings)) {
            models = payOrderSettings.stream().map(this::toModel).collect(Collectors.toUnmodifiableList());
        }
        return ResultContent.buildSuccess(models);
    }

    /**
     * 得到用户的支付渠道排序数据
     *
     * @param userId
     * @param projectOid
     * @return
     */
    public List<PayOrderSetting> getUserPayOrderSettings(String userId, String projectOid) {
        // 已有的数据
        List<PayOrderSetting> payOrderSettings = payOrderSettingDao.findByUserIdAndProjectOidOrderBySortAsc(userId, projectOid);
        long max = 1;
        HashMap<PaymentType, PayOrderSetting> map = new HashMap<>();
        if (ObjectUtils.isNotEmpty(payOrderSettings)) {
            for (PayOrderSetting temp : payOrderSettings) {
                long sort = temp.getSort();
                if (sort > max) {
                    max = sort;
                }
                map.put(temp.getPaymentType(), temp);
            }
        }

        // 所有的支付渠道
        List<PaymentType> paymentTypes = getProjectPayment(projectOid);
        List<PayOrderSetting> newList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(paymentTypes)) {
            long i = max;
            for (PaymentType paymentType : paymentTypes) {
                PayOrderSetting payOrderSetting = null;
                if (map.containsKey(paymentType)) {
                    payOrderSetting = map.get(paymentType);
                } else {
                    payOrderSetting = new PayOrderSetting();
                    i++;
                    payOrderSetting.setSort(i);
                }
                payOrderSetting.setProjectOid(projectOid);
                payOrderSetting.setUserId(userId);
                payOrderSetting.setPaymentType(paymentType);
                payOrderSettings.add(payOrderSetting);
                newList.add(payOrderSetting);
            }
            Collections.sort(newList, new Comparator<PayOrderSetting>() {

                @Override
                public int compare(PayOrderSetting o1, PayOrderSetting o2) {
                    return (int) (o1.getSort() - o2.getSort());
                }
            });
            payOrderSettingDao.saveAll(newList);
        }
        return newList;
    }

    /**
     * 得到用户的支付渠道列表 （排序后的数据）
     *
     * @param userId
     * @param projectOid
     * @return
     */
    public ResultContent<List<PaymentType>> getUserPayment(String userId, String projectOid) {
        // 得到项目支持的付款方式
        List<PaymentType> supportTypes = getProjectPayment(projectOid);
        if (ObjectUtils.isEmpty(supportTypes)) {
            return ResultContent.buildFail("项目暂无开启支付渠道");
        }

        // 不同的支付渠道 结合当前用户判断
        if (ObjectUtils.isNotEmpty(supportTypes)) {
            // 用户的排序
            List<PayOrderSetting> payOrderSettings = payOrderSettingDao.findByUserIdAndProjectOidOrderBySortAsc(userId, projectOid);
            if (ObjectUtils.isNotEmpty(payOrderSettings)) {
                Map<PaymentType, Long> map = payOrderSettings.stream().collect(Collectors.toMap(it -> it.getPaymentType(), it -> it.getSort()));
                long defaultSort = 0;
                // 排序
                Collections.sort(supportTypes, new Comparator<PaymentType>() {
                    @Override
                    public int compare(PaymentType o1, PaymentType o2) {
                        long sort1 = map.get(o1) != null ? map.get(o1) : defaultSort;
                        long sort2 = map.get(o2) != null ? map.get(o2) : defaultSort;
                        return (int) (sort1 - sort2);
                    }
                });
            }
        }
        // 转换后的
        List<PaymentType> userPaymentTypes = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(supportTypes)) {
            for (PaymentType paymentType : supportTypes) {
                paymentType = payCallService.turnPaymentType(paymentType);
                if (paymentType == PaymentType.UnionFrictionlessPay) {
                    boolean b = chinaumsSenselessPayService.isSigned(projectOid, userId);
                    if (!b) {
                        log.info("用户未开启银联无感支付： {}", userId);
                        continue;
                    }
                }

                if (!userPaymentTypes.contains(paymentType)) {
                    userPaymentTypes.add(paymentType);
                }
            }
        }
        return ResultContent.buildSuccess(userPaymentTypes);
    }

    /**
     * 得到项目支持的支付渠道（已启用的）
     *
     * @param projectOid
     * @return
     */
    public List<PaymentType> getProjectPayment(String projectOid) {
        List<PaymentType> paymentTypes = new ArrayList<PaymentType>();
        List<ProjectPaySetting> projectPaySettings = projectPaySettingDao.findByProjectOid(projectOid);
        if (ObjectUtils.isNotEmpty(projectPaySettings)) {
            for (ProjectPaySetting projectPaySetting : projectPaySettings) {
                if (projectPaySetting.getState() != DataState.Enable) {
                    continue;
                }
                // 启用状态
                paymentTypes.add(projectPaySetting.getChannelType());
            }
        }
        return paymentTypes;
    }

    /**
     * 保存排序信息
     *
     * @param param
     * @return
     */
    public ResultContent saveOrder(PayOrderSettingParam param) {
        String userId = getCurrentUserId();
        String projectOid = getCurrentProjectOid();

        Map<String, Long> sortMap = param.getData();
        List<PayOrderSetting> payOrderSettings = payOrderSettingDao.findByUserIdAndProjectOidOrderBySortAsc(userId, projectOid);
        if (ObjectUtils.isNotEmpty(payOrderSettings)) {
            for (PayOrderSetting payOrderSetting : payOrderSettings) {
                if (sortMap.containsKey(payOrderSetting.getId())) {
                    payOrderSetting.setSort(sortMap.get(payOrderSetting.getId()));
                }
            }
            payOrderSettingDao.saveAll(payOrderSettings);
        }
        return ResultContent.buildSuccess();
    }

    public PayOrderSettingModel toModel(PayOrderSetting entity) {
        PayOrderSettingModel model = new PayOrderSettingModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
            PayChannelConfigModel channelConfigModel = projectChannelConfigService.getProjectPayChannelModel(entity.getPaymentType());
            model.setName(channelConfigModel.getName());
            model.setLogo(channelConfigModel.getLogo());
            model.setPaymentChannelType(channelConfigModel.getPaymentChannelType());
        }
        return model;
    }

}
