package com.njzscloud.dispose.cst.order.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.dispose.cst.customer.constant.IdentityCategory;
import com.njzscloud.dispose.cst.customer.pojo.entity.CustomerEntity;
import com.njzscloud.dispose.cst.customer.service.CustomerService;
import com.njzscloud.dispose.cst.order.mapper.OrderTransMapper;
import com.njzscloud.dispose.cst.order.pojo.entity.OrderTransEntity;
import com.njzscloud.dispose.cst.order.pojo.param.OrderTransQueryParam;
import com.njzscloud.dispose.cst.order.pojo.result.OrderTransResult;
import com.njzscloud.dispose.sys.auth.pojo.result.MyResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 运输信息
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderTransService extends ServiceImpl<OrderTransMapper, OrderTransEntity> {

    private final CustomerService customerService;

    @Transactional(rollbackFor = Exception.class)
    public void add(OrderTransEntity orderTransEntity) {
        this.save(orderTransEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void modify(OrderTransEntity orderTransEntity) {
        this.updateById(orderTransEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    public OrderTransResult detail(Long id) {
        return baseMapper.getById(id);
    }

    /**
     * 分页查询，返回联表结果
     */
    public PageResult<OrderTransResult> paging(PageParam pageParam, OrderTransQueryParam param) {
        QueryWrapper<OrderTransResult> ew = Wrappers.query();
        if (param != null) {
            ew.ge(param.getOrderTimeStart() != null, "co.order_time", param.getOrderTimeStart())
                .le(param.getOrderTimeEnd() != null, "co.order_time", param.getOrderTimeEnd())
                .eq(param.getTransOrgId() != null, "co.trans_org_id", param.getTransOrgId())
                .like(StrUtil.isNotBlank(param.getTruckLicensePlate()), "cot.truck_license_plate", param.getTruckLicensePlate())
                .like(StrUtil.isNotBlank(param.getSn()), "co.sn", param.getSn())
                .eq(param.getTrainNum() != null, "cot.train_num", param.getTrainNum())
                .like(StrUtil.isNotBlank(param.getStationName()), "co.station_name", param.getStationName())
                .eq(param.getOrderStatus() != null, "co.order_status", param.getOrderStatus())
                .eq(param.getTransStatus() != null, "cot.trans_status", param.getTransStatus())
                .eq(param.getCheckStatus() != null, "cot.check_status", param.getCheckStatus());
        }
        // 管理员查看全部，非管理员按身份过滤
        if (!SecurityUtil.isAdmin()) {
            MyResult userDetail = SecurityUtil.loginUser();
            if (userDetail.isKanLiao()) {
                Long userId = userDetail.getUserId();
                if (userId != null) {
                    ew.eq("cot.checker_id", userId);
                } else {
                    throw Exceptions.clierr("当前登录人无用户ID");
                }
            } else {
                Long currentCustomerId = userDetail.getCurrentCustomerId();
                if (currentCustomerId != null) {
                    CustomerEntity customer = customerService.getById(currentCustomerId);
                    if (customer != null && customer.getIdentityCategory() != null) {
                        ew.eq(IdentityCategory.ChanFei.equals(customer.getIdentityCategory())
                                || IdentityCategory.CaiGou.equals(customer.getIdentityCategory()),
                            "co.customer_id", currentCustomerId);
                        ew.eq(IdentityCategory.YunShu.equals(customer.getIdentityCategory()),
                            "co.trans_customer_id", currentCustomerId);
                        ew.eq(IdentityCategory.SiJi.equals(customer.getIdentityCategory()),
                            "cot.driver_customer_id", currentCustomerId);
                    } else {
                        throw Exceptions.clierr("客户信息或客户身份类型不存在");
                    }
                } else {
                    throw Exceptions.clierr("当前登录人无客户信息");
                }
            }
        }

        return PageResult.of(baseMapper.paging(pageParam.toPage(), ew));
    }
}

