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

import cn.hutool.core.collection.CollUtil;
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.dict.service.GlobalDictService;
import com.tourism.common.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.back.dao.TourOrderMapper;
import com.tourism.webadmin.back.dto.TourOrderDto;
import com.tourism.webadmin.back.model.TourOrder;
import com.tourism.webadmin.back.model.TourUser;
import com.tourism.webadmin.back.service.TourOrderPassenageService;
import com.tourism.webadmin.back.service.TourOrderService;
import com.tourism.webadmin.back.service.TourismProjectService;
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 java.math.BigDecimal;
import java.util.List;

/**
 * 旅游订单数据操作服务类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Slf4j
@MyDataSource(DataSourceType.MAIN)
@Service("tourOrderService")
public class TourOrderServiceImpl extends BaseService<TourOrder, Long> implements TourOrderService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TourOrderMapper tourOrderMapper;
    @Autowired
    private TourOrderPassenageService tourOrderPassenageService;
    @Autowired
    private TourismProjectService tourismProjectService;
    @Autowired
    private GlobalDictService globalDictService;

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourOrder saveNew(TourOrder tourOrder) {
        TourOrder tourOrder1 = this.buildDefaultValue(tourOrder);
        tourOrder1.setOrderNo(tourOrder1.getId().toString());
        tourOrderMapper.insert(tourOrder1);
        return tourOrder1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TourOrder> tourOrderList) {
        if (CollUtil.isNotEmpty(tourOrderList)) {
            tourOrderList.forEach(this::buildDefaultValue);
            tourOrderMapper.insertList(tourOrderList);
        }
    }

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        TourOrder tourOrder = tourOrderMapper.selectById(id);
        if (tourOrder == null) {
            return false;
        }
        if (tourOrderMapper.deleteById(id) == 0) {
            return false;
        }
        tourismProjectService.remove(tourOrder.getProjectId());
        tourOrderPassenageService.removeByOrderId(id);
        return true;
    }

    @Override
    public List<TourOrder> getTourOrderList(TourOrder filter, String orderBy) {
        return tourOrderMapper.getTourOrderList(filter, orderBy);
    }

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

    @Override
    public CallResult verifyRelatedData(TourOrder tourOrder, TourOrder originalTourOrder) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(tourOrder, originalTourOrder, TourOrder::getOrderStatus)
                && !globalDictService.existDictItemFromCache("OrderStatus", tourOrder.getOrderStatus())) {
            return CallResult.error(String.format(errorMessageFormat, "订单状态"));
        }
        return CallResult.ok();
    }

    @Override
    public List<TourUser> getTourUserListByProjectId(Long projectId) {
        return tourOrderMapper.getTourUserList(projectId);
    }

    @Override
    public void updateHistoryOrderPrice(TourOrder tourOrder) {
        TourOrder dtoFilter = new TourOrder();
        dtoFilter.setGroupPurchaseProgressId(tourOrder.getGroupPurchaseProgressId());
        List<TourOrder> tourOrderList = this.getTourOrderList(dtoFilter, "");
        tourOrderList.forEach(e -> {
            e.setAdultPrice(tourOrder.getAdultPrice());
            e.setChildrenPrice(tourOrder.getChildrenPrice());
            BigDecimal adultTotalPrice = tourOrder.getAdultPrice().multiply(BigDecimal.valueOf(e.getAdultNumber() == null ? 0 : e.getAdultNumber()));
            BigDecimal childrenTotalPrice = tourOrder.getChildrenPrice().multiply(BigDecimal.valueOf(e.getChildrenNumber() == null ? 0 : e.getChildrenNumber()));
            e.setTotalAmount(adultTotalPrice.add(childrenTotalPrice));
            tourOrderMapper.updateById(e);
        });
    }

    private TourOrder buildDefaultValue(TourOrder tourOrder) {
        if (tourOrder.getId() == null) {
            tourOrder.setId(idGenerator.nextLongId());
        }
        MyModelUtil.fillCommonsForInsert(tourOrder);
        tourOrder.setDataState(GlobalDeletedFlag.NORMAL);
        return tourOrder;
    }
}
