package com.sckw.report.service.operator;

import com.sckw.core.model.page.PageResult;
import com.sckw.core.model.vo.TableStatisticRes;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.report.enums.TOrderStatusEnum;
import com.sckw.report.model.dto.OperatorTOrderListStsConditionDTO;
import com.sckw.report.model.vo.OperatorTOrderContractParam;
import com.sckw.report.model.vo.OperatorTOrderExportQueryVO;
import com.sckw.report.model.vo.OperatorTOrderListQueryVO;
import com.sckw.report.model.vo.OperatorTOrderStsQueryVO;
import com.sckw.report.service.KwOrderService;
import com.sckw.report.service.param.TradeOrderListExport;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @desc: 运营端贸易订单管理相关service
 * @author: yzc
 * @date: 2023-09-14 11:23
 */
@Service
@Slf4j
@AllArgsConstructor
public class TradeOrderManageService {

    private final KwOrderService kwOrderService;


    /**
     * @desc: 贸易订单列表分页查询
     * @author: yzc
     * @date: 2023-09-14 14:24
     * @Param params:
     * @return: com.sckw.core.model.page.PageResult
     */
    public PageResult listPaging(OperatorTOrderListQueryVO params) {
        Criteria criteria = buildCriteria(BeanUtils.copyProperties(params, OperatorTOrderListStsConditionDTO.class), false);
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        return kwOrderService.getResult(criteria, sort, params.getPage(), params.getPageSize());
    }

    /**
     * @desc: 贸易订单列表统计查询
     * @author: yzc
     * @date: 2023-09-14 14:22
     * @Param params:
     * @return: com.sckw.core.model.vo.TableStatisticRes
     */
    public TableStatisticRes listStatistic(OperatorTOrderStsQueryVO params) {
        Criteria criteria = buildCriteria(BeanUtils.copyProperties(params, OperatorTOrderListStsConditionDTO.class), true);
        List<TOrderStatusEnum> enums = TOrderStatusEnum.getSortList();
        enums.remove(0);
        return kwOrderService.getTableStatistic(criteria, enums);
    }

    /**
     * @desc: 贸易订单列表导出
     * @author: yzc
     * @date: 2023-09-14 14:40
     * @Param params:
     * @return: java.util.List<com.sckw.report.service.param.TradeOrderListExport>
     */
    public List<TradeOrderListExport> export(OperatorTOrderExportQueryVO params) {
        Query query = new Query();
        if (StringUtils.isNotBlank(params.getIds())) {
            List<Long> ids = StringUtils.splitStrToList(params.getIds(), ",", Long.class);
            Criteria criteria = new Criteria();
            criteria.and("_id").in(ids).and("delFlag").is(0);
            query.addCriteria(criteria);
        } else {
            query.addCriteria(buildCriteria(BeanUtils.copyProperties(params, OperatorTOrderListStsConditionDTO.class), false));
        }
        query.with(Sort.by(Sort.Order.desc("createTime")));
        return kwOrderService.getExportResult(query);
    }

    /**
     * @desc: 构建Criteria
     * @author: yzc
     * @date: 2023-09-14 14:25
     * @Param params:
     * @Param isStatistic:
     * @return: org.springframework.data.mongodb.core.query.Criteria
     */
    private Criteria buildCriteria(OperatorTOrderListStsConditionDTO params, boolean isStatistic) {
        Criteria condition = new Criteria();
        condition.and("delFlag").is(0);
        //状态
        if (!isStatistic && Objects.nonNull(params.getStatus())) {
            condition.and("status").is(params.getStatus());
        } else {
            condition.and("status").ne(0);
        }
        //装货地址
        String loadCode = params.getShippingAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (params.getShippingAddressLevel()) {
                case 1 -> condition.and("loadCityCode")
                        .regex(Pattern.compile("^" + loadCode.substring(0, 2) + ".*$", Pattern.CASE_INSENSITIVE));
                case 2 -> condition.and("loadCityCode")
                        .regex(Pattern.compile("^" + loadCode.substring(0, 4) + ".*$", Pattern.CASE_INSENSITIVE));
                case 3 -> condition.and("loadCityCode").is(loadCode);
            }
        }
        //卸货地址
        String unloadCode = params.getUnloadingAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (params.getUnloadingAddressLevel()) {
                case 1 -> condition.and("unloadCityCode")
                        .regex(Pattern.compile("^" + unloadCode.substring(0, 2) + ".*$", Pattern.CASE_INSENSITIVE));
                case 2 -> condition.and("unloadCityCode")
                        .regex(Pattern.compile("^" + unloadCode.substring(0, 4) + ".*$", Pattern.CASE_INSENSITIVE));
                case 3 -> condition.and("unloadCityCode").is(unloadCode);
            }
        }
        //提货方式
        if (StringUtils.isNotBlank(params.getPickupType())) {
            condition.and("pickupType").is(params.getPickupType());
        }
        //交易方式
        if (StringUtils.isNotBlank(params.getTrading())) {
            condition.and("trading").is(params.getTrading());
        }
        //交付类型
        if (StringUtils.isNotBlank(params.getDeliveryType())) {
            condition.and("deliveryType").is(params.getDeliveryType());
        }
        //下单方式
        if (StringUtils.isNotBlank(params.getSource())) {
            condition.and("source").is(params.getSource());
        }
        //日期范围
        if (Objects.nonNull(params.getStartCreateTime()) && Objects.nonNull(params.getEndCreateTime())) {
            condition.and("createTime").gte(params.getStartCreateTime()).lte(params.getEndCreateTime());
        } else if (Objects.nonNull(params.getStartCreateTime())) {
            condition.and("createTime").gte(params.getStartCreateTime());
        } else if (Objects.nonNull(params.getEndCreateTime())) {
            condition.and("createTime").lte(params.getEndCreateTime());
        }
        //关键字模糊匹配
        if (StringUtils.isNotBlank(params.getKeywords())) {
            Pattern pattern = Pattern.compile("^.*" + params.getKeywords() + ".*$", Pattern.CASE_INSENSITIVE);
            Criteria keywordsMatch = new Criteria().orOperator(
                    Criteria.where("tOrderNo").regex(pattern), Criteria.where("procureFirmName").regex(pattern),
                    Criteria.where("supplyFirmName").regex(pattern), Criteria.where("goodsName").regex(pattern));
            condition.andOperator(keywordsMatch);
        }
        return condition;
    }

    /**
     * @desc: 合同关联订单列表
     * @author: yzc
     * @date: 2023-09-14 14:52
     * @Param params:
     * @return: com.sckw.core.model.page.PageResult
     */
    public PageResult contractAssociationList(OperatorTOrderContractParam params) {
        Criteria criteria = new Criteria();
        List<Long> ids = StringUtils.splitStrToList(params.getContractIds(), ",", Long.class);
        criteria.and("contractId").in(ids).and("delFlag").is(0);
        Sort sort = Sort.by(Sort.Direction.DESC, "contractId", "createTime");
        return kwOrderService.getResult(criteria, sort, params.getPage(), params.getPageSize());
    }
}
