package com.zfire.mall.manager.logic.engin.v2.deposit;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.PoySaleCountBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.engin.v2.deposit.DepositManageVO;
import com.zfire.mall.manager.commonmapper.engin.deposit.DepositMangeReserveMapper;
import com.zfire.mall.manager.enums.OrderTypeEnum;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.EnginOrderItem;
import com.zfire.mall.manager.zfire.bean.QueryParamBean;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DepositManageV2Logic {

    @Resource
    DepositMangeReserveMapper depositMangeReserveMapper;
    @Resource
    CommonLogic commonLogic;

    public IPage<DepositManageVO> v2HomeListPage(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        if (adminUser.getIsCustomer()) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.customer_id")
                    .setCompare("=")
                    .setValue(adminUser.getCustomerId()));
        }
        if (CollectionUtil.isNotEmpty(adminUser.getAdminCompanyIds())) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.admin_company_id")
                    .setCompare("IN")
                    .setValue(adminUser.getAdminCompanyIds()));
        }
        if (CollectionUtil.isNotEmpty(adminUser.getServiceIds())) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.service_id")
                    .setCompare("IN")
                    .setValue(adminUser.getServiceIds()));
        }
        zfireParamBean.getParams().add(new QueryParamBean().setParam("a.engin_order_type")
                .setCompare("=")
                .setValue(OrderTypeEnum.HOME.getKey()));
        List<QueryParamBean> newList = new ArrayList<>();
        List<QueryParamBean> factoryNoList = new ArrayList<>();
        List<QueryParamBean> specialNoList = new ArrayList<>();
        List<QueryParamBean> billNoList = new ArrayList<>();
        // 删除原查询条件
        for (QueryParamBean param : zfireParamBean.getParams()) {
            switch (param.getParam()) {
                case "b.factory_no":
                    factoryNoList.add(param);
                    break;
                case "b.special_no":
                    specialNoList.add(param);
                    break;
                case "b.bill_no":
                    billNoList.add(param);
                    break;
                default:
                    newList.add(param);
                    break;
            }
        }

        this.specialFieldsHandle(newList, factoryNoList, "b.factory_no", "b.factory_no_number","\\d+\\D*$", 1);
        this.specialFieldsHandle(newList, specialNoList, "b.special_no", "b.special_no_number","\\d+\\D*$", 2);
        this.specialFieldsHandle(newList, billNoList, "b.bill_no", "b.bill_no_number","[^0-9]", 3);

        zfireParamBean.getParams().clear();
        zfireParamBean.getParams().addAll(newList);

        FieldUtils.supplyParam(zfireParamBean);

        IPage<DepositManageVO> depositManageVOIPage = depositMangeReserveMapper.v2HomeListPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);

        if (CollectionUtil.isEmpty(depositManageVOIPage.getRecords())) {
            return depositManageVOIPage;
        }

        Set<String> recordNos = depositManageVOIPage.getRecords().stream()
                .map(DepositManageVO::getRefEnginRecordNo)
                .collect(Collectors.toSet());

        // 获取订单上的发货数量
        List<EnginOrderItem> orderItems = depositMangeReserveMapper.queryOrderHasSendQty(recordNos);
        Map<String, EnginOrderItem> orderItemMap = orderItems.stream()
                .collect(Collectors.toMap(v -> v.getRefEnginRecordNo() + "|" + v.getMaterialId() + "|" + v.getCustomerWalletId() + "|" + v.getPrice() , Function.identity()));

        for (DepositManageVO record : depositManageVOIPage.getRecords()) {
            EnginOrderItem orderItem = orderItemMap.get(record.getRefEnginRecordNo() + "|" + record.getMaterialId() + "|" + record.getCustomerWalletId() + "|" + record.getItemPrice());
            if (Objects.nonNull(orderItem)) {
                record.setOrderHasSendQty(orderItem.getQty());
            }
//            if (adminUser.getIsCustomer()) {
//                record.setGeLiNote("");
//                record.setGeLiInerNote("");
//            }
        }
        return depositManageVOIPage;
    }

    private void specialFieldsHandle(List<QueryParamBean> newList, List<QueryParamBean> paramsList, String fieldName,
                                     String betweenFieldName, String regex, int type) {
        if (CollectionUtil.isNotEmpty(paramsList)) {
            String preStr = "";
            for (QueryParamBean bean : paramsList) {
                if (bean.getCompare().equals(">")) {
                    preStr = this.substringStrHandle(newList, bean, betweenFieldName, preStr, regex, ">=", type);
                } else if (bean.getCompare().equals("<")) {
                    preStr = this.substringStrHandle(newList, bean, betweenFieldName, preStr, regex, "<=", type);
                } else {
                    newList.add(bean);
                }
            }
            if (StringUtils.isNotBlank(preStr)) {
                newList.add(new QueryParamBean().setParam(fieldName)
                        .setCompare("like")
                        .setValue(preStr));
            }
        }
    }

    private String substringStrHandle(List<QueryParamBean> newList, QueryParamBean bean, String betweenFieldName,
                                      String preStr, String regex, String replaceStr, int type) {
        if (Objects.nonNull(bean.getValue())) {
            String valueStr = bean.getValue().toString();
            if (type == 1) {
                int length = valueStr.replaceFirst(regex, "").length();
                if (StringUtils.isNotBlank(valueStr.substring(length))) {
                    if (StringUtils.isNotBlank(preStr)) {
                        preStr = valueStr.substring(0, length);
                    }
                    newList.add(new QueryParamBean().setParam(betweenFieldName)
                            .setCompare(replaceStr)
                            .setValue(valueStr.substring(length)));
                }
            } else if (type == 2) {
                int length = valueStr.replaceFirst(regex, "").length();
                if (StringUtils.isNotBlank(valueStr.substring(length))) {
                    String[] cs = valueStr.split("-");
                    if(cs.length == 3) {
                        if (StringUtils.isNotBlank(preStr)) {
                            preStr = cs[0]+"-"+cs[1];
                        }
                        newList.add(new QueryParamBean().setParam(betweenFieldName)
                                .setCompare(replaceStr)
                                .setValue(cs[2]));
                    }
                }
            } else if (type == 3) {
                if (StringUtils.isNotBlank(valueStr)) {
                    Pattern p = Pattern. compile(regex);
                    String str = p.matcher(valueStr).replaceAll("").trim();
                    if(!StringUtils.isBlank(str) && valueStr.contains(str)) {
                        preStr = valueStr.substring(0, valueStr.indexOf(str)) ;
                        newList.add(new QueryParamBean().setParam(betweenFieldName)
                                .setCompare(replaceStr)
                                .setValue(str));
                    }
                }
            }
        }
        return preStr;
    }

    public PoySaleCountBean v2HomeCountList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser(true);
        if (adminUser.getIsCustomer()) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.customer_id")
                    .setCompare("=")
                    .setValue(adminUser.getCustomerId()));
        }
        if (CollectionUtil.isNotEmpty(adminUser.getAdminCompanyIds())) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.admin_company_id")
                    .setCompare("IN")
                    .setValue(adminUser.getAdminCompanyIds()));
        }
        if (CollectionUtil.isNotEmpty(adminUser.getServiceIds())) {
            zfireParamBean.getParams().add(new QueryParamBean().setParam("a.service_id")
                    .setCompare("IN")
                    .setValue(adminUser.getServiceIds()));
        }
        zfireParamBean.getParams().add(new QueryParamBean().setParam("a.engin_order_type")
                .setCompare("=")
                .setValue(OrderTypeEnum.HOME.getKey()));
        List<QueryParamBean> newList = new ArrayList<>();
        List<QueryParamBean> factoryNoList = new ArrayList<>();
        List<QueryParamBean> specialNoList = new ArrayList<>();
        List<QueryParamBean> billNoList = new ArrayList<>();
        // 删除原查询条件
        for (QueryParamBean param : zfireParamBean.getParams()) {
            switch (param.getParam()) {
                case "b.factory_no":
                    factoryNoList.add(param);
                    break;
                case "b.special_no":
                    specialNoList.add(param);
                    break;
                case "b.bill_no":
                    billNoList.add(param);
                    break;
                default:
                    newList.add(param);
                    break;
            }
        }

        this.specialFieldsHandle(newList, factoryNoList, "b.factory_no", "b.factory_no_number","\\d+\\D*$", 1);
        this.specialFieldsHandle(newList, specialNoList, "b.special_no", "b.special_no_number","\\d+\\D*$", 2);
        this.specialFieldsHandle(newList, billNoList, "b.bill_no", "b.bill_no_number","[^0-9]", 3);

        zfireParamBean.getParams().clear();
        zfireParamBean.getParams().addAll(newList);

        FieldUtils.supplyParam(zfireParamBean);

        return depositMangeReserveMapper.v2CountList(zfireParamBean);
    }
}
