package com.tourism.webadmin.back.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.tourism.common.core.annotation.MyDataSource;
import com.tourism.common.core.base.dao.BaseDaoMapper;
import com.tourism.common.core.base.service.BaseService;
import com.tourism.common.core.constant.GlobalDeletedFlag;
import com.tourism.common.core.object.CallResult;
import com.tourism.common.core.object.MyRelationParam;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.back.dao.DeliveryOrderMapper;
import com.tourism.webadmin.back.model.DeliveryOrder;
import com.tourism.webadmin.back.model.DeliveryOrderItems;
import com.tourism.webadmin.back.service.DeliveryOrderItemsService;
import com.tourism.webadmin.back.service.DeliveryOrderService;
import com.tourism.webadmin.config.DataSourceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tourism.common.dict.service.GlobalDictService;

import java.util.List;
import java.util.Set;

/**
 * 外卖订单管理数据操作服务类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Slf4j
@MyDataSource(DataSourceType.MAIN)
@Service("deliveryOrderService")
public class DeliveryOrderServiceImpl extends BaseService<DeliveryOrder, String> implements DeliveryOrderService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private DeliveryOrderMapper deliveryOrderMapper;
    @Autowired
    private DeliveryOrderItemsService deliveryOrderItemsService;
    @Autowired
    private GlobalDictService globalDictService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<DeliveryOrder> mapper() {
        return deliveryOrderMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DeliveryOrder saveNew(DeliveryOrder deliveryOrder) {
        this.verifyMaskFieldData(deliveryOrder);
        deliveryOrderMapper.insert(this.buildDefaultValue(deliveryOrder));
        return deliveryOrder;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<DeliveryOrder> deliveryOrderList) {
        if (CollUtil.isNotEmpty(deliveryOrderList)) {
            deliveryOrderList.forEach(this::buildDefaultValue);
            deliveryOrderList.forEach(this::verifyMaskFieldData);
            deliveryOrderMapper.insertList(deliveryOrderList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<DeliveryOrder> deliveryOrderList, int batchSize) {
        if (CollUtil.isEmpty(deliveryOrderList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = 10000;
        }
        int start = 0;
        do {
            int end = Math.min(deliveryOrderList.size(), start + batchSize);
            List<DeliveryOrder> subList = deliveryOrderList.subList(start, end);
            // 如果数据量过大，同时当前表中存在createTime或updateTime等字段，可以考虑在外部创建一次 new Date()，
            // 然后传入buildDefaultValue，这样可以减少对象的创建次数，降低GC，提升效率。橙单之所以没有这样生成，是因为
            // 有些业务场景下需要按照这两个日期字段排序，因此我们只是在这里给出优化建议。
            subList.forEach(this::buildDefaultValue);
            deliveryOrderMapper.insertList(subList);
            if (end == deliveryOrderList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DeliveryOrder saveNewWithRelation(DeliveryOrder deliveryOrder, JSONObject relationData) {
        this.saveNew(deliveryOrder);
        this.saveOrUpdateRelationData(deliveryOrder, relationData);
        return deliveryOrder;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(DeliveryOrder deliveryOrder, DeliveryOrder originalDeliveryOrder) {
        this.compareAndSetMaskFieldData(deliveryOrder, originalDeliveryOrder);
        MyModelUtil.fillCommonsForUpdate(deliveryOrder, originalDeliveryOrder);
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<DeliveryOrder> uw = this.createUpdateQueryForNullValue(deliveryOrder, deliveryOrder.getId());
        return deliveryOrderMapper.update(deliveryOrder, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateWithRelation(
            DeliveryOrder deliveryOrder, DeliveryOrder originalDeliveryOrder, JSONObject relationData) {
        // deliveryOrder 为空的时候，无需修改主表数据。
        if (deliveryOrder != null && !this.update(deliveryOrder, originalDeliveryOrder)) {
            return false;
        }
        this.saveOrUpdateRelationData(originalDeliveryOrder, relationData);
        return true;
    }

    private void saveOrUpdateRelationData(DeliveryOrder deliveryOrder, JSONObject relationData) {
        List<DeliveryOrderItems> deliveryOrderItemsList =
                relationData.getObject("deliveryOrderItemsList", new TypeReference<List<DeliveryOrderItems>>() {});
        // 对于一对多更新，分为以下三步：
        // 1. 在关联从表中，删除掉与主表字段关联，但是又没有出现在本地更新中的数据。我们将这些数据视为需要删除的数据。
        // 2. 在本次更新数据列表中，如果从表的对象没有主键Id，我们视为新数据，可以批量插入。
        // 3. 在本次更新数据列表中，如果从表的对象存在主键Id，我们视为已有数据，逐条更新。
        if (deliveryOrderItemsList != null) {
            deliveryOrderItemsService.updateBatchByOrderId(deliveryOrder.getId(), deliveryOrderItemsList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(String id) {
        if (deliveryOrderMapper.deleteById(id) == 0) {
            return false;
        }
        deliveryOrderItemsService.removeByOrderId(id);
        return true;
    }

    @Override
    public List<DeliveryOrder> getDeliveryOrderList(DeliveryOrder filter, String orderBy) {
        return deliveryOrderMapper.getDeliveryOrderList(filter, orderBy);
    }

    @Override
    public List<DeliveryOrder> getDeliveryOrderListWithRelation(DeliveryOrder filter, String orderBy) {
        List<DeliveryOrder> resultList = deliveryOrderMapper.getDeliveryOrderList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    private DeliveryOrder buildDefaultValue(DeliveryOrder deliveryOrder) {
        if (deliveryOrder.getId() == null) {
            deliveryOrder.setId(idGenerator.nextStringId());
        }
        MyModelUtil.fillCommonsForInsert(deliveryOrder);
        deliveryOrder.setDataState(GlobalDeletedFlag.NORMAL);
        MyModelUtil.setDefaultValue(deliveryOrder, "shopName", "");
        return deliveryOrder;
    }

    @Override
    public CallResult verifyImportList(List<DeliveryOrder> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "payType")) {
            callResult = verifyImportForGlobalDict(dataList, "payTypeDictMap", DeliveryOrder::getPayType);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "orderStatus")) {
            callResult = verifyImportForGlobalDict(dataList, "orderStatusDictMap", DeliveryOrder::getOrderStatus);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "refundStatus")) {
            callResult = verifyImportForGlobalDict(dataList, "refundStatusDictMap", DeliveryOrder::getRefundStatus);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(DeliveryOrder deliveryOrder, DeliveryOrder originalDeliveryOrder) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(deliveryOrder, originalDeliveryOrder, DeliveryOrder::getPayType)
                && !globalDictService.existDictItemFromCache("DeliveryPayType", deliveryOrder.getPayType())) {
            return CallResult.error(String.format(errorMessageFormat, "支付方式"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(deliveryOrder, originalDeliveryOrder, DeliveryOrder::getOrderStatus)
                && !globalDictService.existDictItemFromCache("DeliveryOrderStatus", deliveryOrder.getOrderStatus())) {
            return CallResult.error(String.format(errorMessageFormat, "订单状态"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(deliveryOrder, originalDeliveryOrder, DeliveryOrder::getRefundStatus)
                && !globalDictService.existDictItemFromCache("DeliveryOrderRefundStatus", deliveryOrder.getRefundStatus())) {
            return CallResult.error(String.format(errorMessageFormat, "退款状态"));
        }
        return CallResult.ok();
    }
}
