package com.czg.service.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.czg.account.dto.HandoverRecordDTO;
import com.czg.account.entity.HandoverRecord;
import com.czg.account.service.HandoverRecordService;
import com.czg.account.vo.HandoverProductListVo;
import com.czg.account.vo.HandoverTotalVo;
import com.czg.exception.CzgException;
import com.czg.order.service.OrderInfoRpcService;
import com.czg.sa.StpKit;
import com.czg.service.account.mapper.HandoverRecordMapper;
import com.czg.utils.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 交班记录表
 *
 * @author Tankaikai tankaikai@aliyun.com
 * @since 1.0 2025-02-27
 */
@Service
public class HandoverRecordServiceImpl extends ServiceImpl<HandoverRecordMapper, HandoverRecord> implements HandoverRecordService {

    @DubboReference
    private OrderInfoRpcService orderInfoRpcService;


    @Override
    public Page<HandoverRecordDTO> getHandoverRecordPage(String beginDate, String endDate) {
        HandoverRecordDTO param = new HandoverRecordDTO();
        param.setBeginDate(beginDate);
        param.setEndDate(endDate);
        QueryWrapper queryWrapper = query().eq(HandoverRecord::getShopId, StpKit.USER.getShopId());
        if (StrUtil.isNotEmpty(param.getBeginDate())) {
            queryWrapper.ge(HandoverRecord::getHandoverTime, param.getBeginDate() + " 00:00:00");
        }
        if (StrUtil.isNotEmpty(param.getEndDate())) {
            queryWrapper.le(HandoverRecord::getHandoverTime, param.getEndDate() + " 23:59:59");
        }
        return super.pageAs(PageUtil.buildPage(), queryWrapper, HandoverRecordDTO.class);
    }

    @Override
    public List<HandoverProductListVo> getHandoverProductListById(Long id) {
        Long shopId = StpKit.USER.getShopId();
        HandoverRecord data = getOne(query().eq(HandoverRecord::getId, id).eq(HandoverRecord::getShopId, shopId));
        if (data == null || data.getProductData() == null) {
            return List.of();
        }
        return JSON.parseArray(data.getProductData(), HandoverProductListVo.class);
    }

    @Override
    public HandoverTotalVo totalHandoverData() {
        Long shopId = StpKit.USER.getShopId();
        LocalDateTime handoverTime = LocalDateTime.now();
        HandoverRecord record = super.getOne(query().eq(HandoverRecord::getShopId, shopId).isNull(HandoverRecord::getHandoverTime));
        HandoverTotalVo data = new HandoverTotalVo();
        if (record == null) {
            throw new CzgException("未处在当班状态");
        }
        data.setId(record.getId());
        data.setShopId(record.getShopId());
        data.setShopName(record.getShopName());
        data.setAccountType(record.getAccountType());
        data.setStaffId(record.getStaffId());
        data.setStaffName(record.getStaffName());
        data.setLoginTime(record.getLoginTime());
        data.setHandoverTime(handoverTime);
        String loginTimeStr = LocalDateTimeUtil.formatNormal(record.getLoginTime());
        String handoverTimeStr = LocalDateTimeUtil.formatNormal(handoverTime);
        data.setDetailList(orderInfoRpcService.getHandoverDetailList(shopId, loginTimeStr, handoverTimeStr));
        data.setCategoryList(orderInfoRpcService.getHandoverCategoryList(shopId, loginTimeStr, handoverTimeStr));
        HandoverRecord onlinePayTypeDate = orderInfoRpcService.getOnlinePayTypeDate(shopId, loginTimeStr, handoverTimeStr);
        // 合并结果
        CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true);
        if (onlinePayTypeDate != null) {
            BeanUtil.copyProperties(onlinePayTypeDate, data, copyOptions);
            data.setTurnover(onlinePayTypeDate.getOrderTurnover());
        }
        HandoverRecord handoverRecord = orderInfoRpcService.countShopUserFlow(shopId, loginTimeStr, handoverTimeStr);
        if (handoverRecord != null) {
            data.setTurnover(NumberUtil.add(data.getTurnover(), handoverRecord.getRecharge()));
            data.setRefundAmount(NumberUtil.add(data.getRefundAmount(), handoverRecord.getRefundAmount()));
            data.setRecharge(handoverRecord.getRecharge());
        }
        data.setReturnDishCount(orderInfoRpcService.countReturnDish(shopId, loginTimeStr, handoverTimeStr));
        return data;
    }

    @Override
    public void initHandoverRecord(HandoverRecord entity) {
        List<HandoverRecord> list = super.list(query().eq(HandoverRecord::getShopId, entity.getShopId()).isNull(HandoverRecord::getHandoverTime));
        if (CollUtil.isNotEmpty(list)) {
            return;
        }
        entity.setLoginTime(LocalDateTime.now());
        save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HandoverRecord handover() {
        HandoverTotalVo data = totalHandoverData();
        HandoverRecord entity = BeanUtil.copyProperties(data, HandoverRecord.class);
        entity.setCategoryData(JSON.toJSONString(data.getCategoryList(), JSONWriter.Feature.WriteMapNullValue));
        List<HandoverProductListVo> productData = data.getDetailList();
        entity.setProductData(JSON.toJSONString(productData, JSONWriter.Feature.WriteMapNullValue));
        super.updateById(entity);
        return entity;
    }

    @Override
    public void printHandoverReceipt(HandoverRecord record, Integer isPrint) {
        orderInfoRpcService.sendHandoverReceiptPrintMsgToMq(record.getShopId(), record);
    }
}