package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.TallyBookDAO;
import com.cool.store.dao.TallyBookDetailDAO;
import com.cool.store.dto.TallyBookDTO;
import com.cool.store.dto.TallyBookDetailDTO;
import com.cool.store.entity.TallyBookDO;
import com.cool.store.entity.TallyBookDetailDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.TallyBookStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.TallyBookRequest;
import com.cool.store.response.TallyBookDetailResponse;
import com.cool.store.service.TallyBookService;
import com.cool.store.vo.PartnerUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: WangShuo
 * @Date: 2025/03/28/09:59
 * @Version 1.0
 * @注释:
 */
@Slf4j
@Service
public class TallyBookServiceImpl implements TallyBookService {

    @Resource
    private TallyBookDAO tallyBookDAO;

    @Resource
    private TallyBookDetailDAO tallyBookDetailDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertOrUpdateSelective(TallyBookRequest request, PartnerUserInfoVO user) {
        TallyBookDO tallyBookDO = new TallyBookDO();
        tallyBookDO.setId(request.getId());
        tallyBookDO.setStatus(TallyBookStatusEnum.IS_SUBMIT.getCode());;
        tallyBookDO.setUpdateUser(user.getPartnerId());
        tallyBookDO.setTotal(request.getTotal());
        tallyBookDO.setUpdateTime(new Date());
        tallyBookDO.setOperatorName(request.getOperatorName());
        tallyBookDAO.updateByPrimaryKeySelective(tallyBookDO);
        tallyBookDetailDAO.batchDeleteByTallyBookId(request.getId());
        List<TallyBookDetailDO> tallyBookDetailDOList = request.toTallyBookDetailDOList(request.getId());
        tallyBookDetailDAO.batchInsert(tallyBookDetailDOList);
        return request.getId();
    }

    @Override
    public List<TallyBookDTO> getTallyBookListByShopIdAndYear(Long shopId, Integer year) {
        List<TallyBookDO> list = tallyBookDAO.getTallyBookListByShopIdAndYear(shopId, year);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<TallyBookDO> sortList = list.stream().sorted(Comparator.comparing(TallyBookDO::getMonth)).collect(Collectors.toList());
        List<TallyBookDTO> result = new ArrayList<>();
        for (TallyBookDO tallyBookDO : sortList) {
            TallyBookDTO tallyBookDTO = new TallyBookDTO();
            BeanUtils.copyProperties(tallyBookDO, tallyBookDTO);
            result.add(tallyBookDTO);
        }
        return result;
    }

    @Override
    public Long initData(Long shopId, String partnerId) {
        Date date = new Date();
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取年份
        int year = localDate.getYear();
        // 获取月份
        int month = localDate.getMonthValue();
        List<TallyBookDO> list = tallyBookDAO.getTallyBookListByShopIdAndYear(shopId, year);
        TallyBookDO tallyBookDO = new TallyBookDO();
        tallyBookDO.setShopId(shopId);
        tallyBookDO.setPartnerId(partnerId);
        tallyBookDO.setYear(year);
        tallyBookDO.setMonth(month);
        tallyBookDO.setCreateTime(new Date());
        tallyBookDO.setStatus(TallyBookStatusEnum.NOT_SUBMIT.getCode());
        log.info("initData记账本DO:{}", JSONObject.toJSONString(tallyBookDO));
        if (CollectionUtils.isEmpty(list)) {
            return tallyBookDAO.insertSelective(tallyBookDO);
        }
        List<Integer> monthList = list.stream().map(TallyBookDO::getMonth).collect(Collectors.toList());
        if (!monthList.contains(month)) {
            return tallyBookDAO.insertSelective(tallyBookDO);
        }
        return null;
    }

    @Override
    public TallyBookDetailResponse getTallyBookDetailByTallyBookId(Long tallyBookId) {
        TallyBookDetailResponse response = new TallyBookDetailResponse();
        TallyBookDO tallyBookDO = tallyBookDAO.getById(tallyBookId);
        if (tallyBookDO == null){
            throw new ServiceException(ErrorCodeEnum.TALLY_BOOK_NOT_EXIST);
        }
        List<TallyBookDetailDO> tallyBookDetailList = tallyBookDetailDAO.getTallyBookDetailListByTallyBookId(tallyBookId);
        List<TallyBookDetailDTO> dto = response.toDTO(tallyBookDetailList);
        response.setTotal(tallyBookDO.getTotal());
        response.setYear(tallyBookDO.getYear());
        response.setMonth(tallyBookDO.getMonth());
        response.setList(dto);
        return response;
    }
}
