package com.ghy.payment.service.impl;

import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.text.Convert;
import com.ghy.common.enums.FinancialDetailType;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.mapper.FinancialDetailMapper;
import com.ghy.payment.request.FinancialAccountBillReq;
import com.ghy.payment.response.FinancialAccountBillResp;
import com.ghy.payment.response.FinancialCountResponse;
import com.ghy.payment.service.FinancialDetailService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

import static java.time.temporal.ChronoField.*;

@Service
public class FinancialDetailServiceImpl implements FinancialDetailService {

    private static final AtomicLong INDEX = new AtomicLong(1L);

    public static final DateTimeFormatter MINI_FORMATTER = new DateTimeFormatterBuilder()
            .appendValue(YEAR, 4).appendValue(MONTH_OF_YEAR, 2)
            .appendValue(DAY_OF_MONTH, 2).appendValue(HOUR_OF_DAY, 2)
            .appendValue(MINUTE_OF_HOUR, 2).appendValue(SECOND_OF_MINUTE, 2).toFormatter();


    @Resource
    private FinancialDetailMapper financialDetailMapper;


    @Override
    public List<FinancialCountResponse> count(String countTime, String billingState, List<Integer> financialDetailTypes, Integer payeeId) {
        FinancialCountResponse request = new FinancialCountResponse();
        request.setCreateTime(countTime);
        request.setFlag("true");
        request.setFinancialDetailTypes(financialDetailTypes);
        request.setPayeeId(payeeId);
        request.setBillingState(billingState);
        // 查询各月含有收入的费用
        List<FinancialCountResponse> list = financialDetailMapper.count(request);
        list.forEach(financialCountResponse -> {
            // 查询指定月支出的
            request.setFlag("false");
            request.setCreateTime(financialCountResponse.getCreateTime());
            List<FinancialCountResponse> payCountList = financialDetailMapper.count(request);
            if (payCountList != null && payCountList.size() != 0) {
                financialCountResponse.setPayCount(payCountList.get(0).getIncomeCount());
            } else {
                financialCountResponse.setPayCount("0");
            }
        });
        return list;
    }


    @Override
    public FinancialDetail selectByOrderDetailId(Long orderDetailId) {
        FinancialDetail financialDetail = new FinancialDetail();
        financialDetail.setOrderDetailId(orderDetailId);
        financialDetail.setFinancialDetailType(FinancialDetailType.ORDER_FEE.getCode());
        List<FinancialDetail> list = financialDetailMapper.selectFinancialDetailList(financialDetail);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<FinancialDetail> selectListByOrderDetailId(Long orderDetailId) {
        FinancialDetail financialDetail = new FinancialDetail();
        financialDetail.setOrderDetailId(orderDetailId);
        return financialDetailMapper.selectFinancialDetailList(financialDetail);
    }

    @Override
    public int insertFinancialDetail(FinancialDetail financialDetail) {
        return financialDetailMapper.insertFinancialDetail(financialDetail);
    }

    @Override
    public int updateFinancialDetail(FinancialDetail financialDetail) {
        return financialDetailMapper.updateFinancialDetail(financialDetail);
    }

    @Override
    public List<FinancialDetail> selectFinancialDetailList(FinancialDetail financialDetail) {
        return financialDetailMapper.selectFinancialDetailList(financialDetail);
    }

    @Override
    public List<FinancialAccountBillResp> selectFinancialDetailListV2(FinancialAccountBillReq financialAccountBillReq) {
        List<FinancialAccountBillResp> list = financialDetailMapper.selectFinancialDetailListV2(financialAccountBillReq);
        list.forEach(model->{
            if(model.getOrderStatus() == 6){
                model.setOrderStatusDesc("运营利润--已取消");
            }else if(model.getOrderStatus() == 5){
                model.setOrderStatusDesc("运营利润--已到账");
            }else {
                model.setOrderStatusDesc("运营利润--待分账");
            }
            if(model.getPayStatus() == 1){
                model.setPayStatusDesc("已支付");
            }else {
                model.setPayStatusDesc("未支付");
            }
        });
        return list;
    }

    @Override
    public FinancialDetail selectById(Long financialDetailId) {
        return financialDetailMapper.selectById(financialDetailId);
    }

    @Override
    public List<FinancialDetail> selectByFinancialMasterId(Long financialMasterId) {
        return financialDetailMapper.selectByFinancialMasterId(financialMasterId);
    }

    @Override
    public int deleteFinancialDetailByIds(String ids) {
        Long[] financialDetailIds = Convert.toLongArray(ids);
        return financialDetailMapper.deleteFinancialDetailByIds(financialDetailIds);
    }

    @Override
    public int deleteFinancialDetailByOrderDetailId(Long orderDetailId) {
        return financialDetailMapper.deleteFinancialDetailByOrderDetailId(orderDetailId);
    }

    @Override
    public String checkFinancialDetailCodeUnique(FinancialDetail financialDetail) {
        long financialDetailId = financialDetail.getId() == null ? -1L : financialDetail.getId();
        FinancialDetail info = financialDetailMapper.checkFinancialDetailCodeUnique(financialDetail.getCode());
        if (info != null && info.getId() != financialDetailId) {
            return UserConstants.FINANCIAL_CODE_NOT_UNIQUE;
        }
        return UserConstants.FINANCIAL_CODE_UNIQUE;
    }

    @Override
    public String createCode() {
        INDEX.compareAndSet(9999L, 1L);
        LocalDateTime now = LocalDateTime.now();
        return "fd" + now.format(MINI_FORMATTER) + INDEX.getAndIncrement();
    }

    @Override
    public void payReverseSucceeded(String reverseId) {
        financialDetailMapper.payReverseSucceeded(reverseId);
    }

    @Override
    public void updateByFinancialMasterId(FinancialDetail financialDetail) {
        financialDetailMapper.updateByFinancialMasterId(financialDetail);
    }

    @Override
    public List<FinancialDetail> selectByFinancialMasterIdAndType(Long financialMasterId, int type) {
        FinancialDetail financialDetail = new FinancialDetail();
        financialDetail.setFinancialMasterId(financialMasterId);
        financialDetail.setFinancialDetailType(type);
        return financialDetailMapper.selectFinancialDetailList(financialDetail);
    }

    @Override
    public Map<Long, FinancialDetail> byOrderIdInMap(List<Long> orderIdList) {
        Map<Long, FinancialDetail> longFinancialDetailHashMap = new HashMap<>();
        if (orderIdList != null && orderIdList.size() > 0) {
            List<FinancialDetail> financialDetailList = financialDetailMapper.selectByOrderDetailIds(orderIdList);
            if (financialDetailList != null && financialDetailList.size() > 0) {
                for (FinancialDetail financialDetail : financialDetailList) {
                    longFinancialDetailHashMap.put(financialDetail.getOrderDetailId(), financialDetail);
                }
            }
        }
        return longFinancialDetailHashMap;
    }

    @Override
    public List<FinancialDetail> selectByOrderDetailIds(Set<Long> orderDetailIds) {
        if (CollectionUtils.isEmpty(orderDetailIds)) {
            return new ArrayList<>();
        }
        return financialDetailMapper.selectByOrderDetailIds(orderDetailIds);
    }

    @Override
    public int updatePayStatus(Long id, Integer payStatus) {
        return financialDetailMapper.updatePayStatus(id, payStatus);
    }

    @Override
    public void refundSucceeded(String reverseId) {
        financialDetailMapper.refundSucceeded(reverseId);
    }
}
