package com.zfire.mall.manager.logic.engin.order;

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.admin.AdminUserCom;
import com.zfire.mall.manager.bean.engin.order.EnginOrderBean;
import com.zfire.mall.manager.bean.engin.order.EnginOrderListBean;
import com.zfire.mall.manager.bean.retail.ProductPriceBean;
import com.zfire.mall.manager.commonmapper.engin.order.EnginOrderReserveMapper;
import com.zfire.mall.manager.datasource.engin.entity.AgencyBills;
import com.zfire.mall.manager.datasource.engin.entity.AgencyBillsBean;
import com.zfire.mall.manager.datasource.engin.entity.Machine4Agency;
import com.zfire.mall.manager.datasource.engin.logic.AgencyBillsLogic;
import com.zfire.mall.manager.enums.OrderTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.admin.AdminUserLogic;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.retail.RetailOrderLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.AdminUser;
import com.zfire.mall.manager.plus.entity.EnginOrder;
import com.zfire.mall.manager.plus.entity.EnginOrderItem;
import com.zfire.mall.manager.plus.entity.SaleType;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.JiaSMUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class EnginSysLogic {

    @Value("${spring.profiles.active}")
    private String profiles;

//    @Value("${engin.url}")
    private String enginUrl;
    @Resource
    CommonLogic commonLogic;
    @Resource
    KingDeeMaterialService kingDeeMaterialService;
    @Resource
    KingDeeCustomerService kingDeeCustomerService;
    @Resource
    SaleTypeService saleTypeService;
    @Resource
    WalletLogic walletLogic;
    @Resource
    EnginOrderLogic enginOrderLogic;
    @Resource
    RetailOrderLogic retailOrderLogic;
    @Autowired
    AdminUserService adminUserService;
    @Resource
    AgencyBillsLogic agencyBillsLogic;
    @Resource
    AdminUserLogic adminUserLogic;
    @Resource
    EnginOrderReserveMapper enginOrderReserveMapper;
    @Resource
    EnginOrderItemService enginOrderItemService;


    public IPage<AgencyBills> listPage(String recordNo, String projectName, String useUnit,
                                       Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
//        if (!adminUser.getIsCustomer()) {
//            throw new RemoteServiceException("当前账号不是经销商，请使用经销商登录操作单据");
//        }
        AdminUser adminUserNew = adminUserService.getById(adminUser.getAdminUserId());
        if (!adminUserNew.getBindEngin()) {
            throw new RemoteServiceException("当前经销商，未绑定工程系统账号");
        }

//        HashMap<String, Object> paramMap = new HashMap<>();
//        if (profiles.equals("dev")) {
//            paramMap.put("userName", "test002");
//            paramMap.put("userIds", Arrays.asList("266","268"));
//        } else {
//            paramMap.put("userName", adminUserNew.getEnginUserName());
//            paramMap.put("userIds", adminUser.getEnginUserIds());
//        }
//        paramMap.put("recordNo", recordNo);
//        paramMap.put("projectName", projectName);
//        paramMap.put("useUnit", useUnit);
//        paramMap.put("pageNum", pageNum);
//        paramMap.put("pageSize", pageSize);

//        String jsonStr = HttpUtil.post(enginUrl.replace("sysadmin", "") + "api/supply/queryAgencyBills", paramMap);
//
//        JSONObject data = this.CommonHandleInfo(jsonStr);
//
//        return JSONUtil.toBean(data, new TypeReference<Page<EnginSysAgencyBills>>() {
//        }, false);

        return agencyBillsLogic.queryAllowAgencyBills(adminUserNew.getEnginUserName(), recordNo, projectName, useUnit, pageNum, pageSize);
    }

    public AgencyBillsBean findBills(String saleTypeId, String recordNo, String userId, String enginOrderId, String customerId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (!adminUser.getBindEngin()) {
            throw new RemoteServiceException("当前帐号，未绑定工程系统帐号");
        }

        SaleType saleType = saleTypeService.getById(saleTypeId);
        if (Objects.isNull(saleType)) {
            throw new RemoteServiceException("销售类型不存在");
        }

        // 查询引用单号历史
        EnginOrderBean enginOrderBean = new EnginOrderBean();
        enginOrderBean.setEnginOrderId(enginOrderId);
        enginOrderBean.setAdminCompanyId(adminUser.getAdminCompanyId());
        enginOrderBean.setRefEnginRecordNo(recordNo);
        enginOrderBean.setEnginOrderType(OrderTypeEnum.HOME.getKey());
        enginOrderBean.setCustomerId(StringUtils.isNotBlank(customerId) ? customerId : adminUser.getCustomerId());
        Integer refCount = enginOrderLogic.checkEnginOrderRecord(enginOrderBean);
        enginOrderBean.setRefCount(refCount);

        AgencyBillsBean bills = this.reqFindBills(recordNo, userId);
        Integer canUseCount = Objects.isNull(bills.getCanUse()) ? 1 : bills.getCanUse();

        if (refCount >= canUseCount) {
            throw new RemoteServiceException(recordNo + "：无法再引用，已达最大引用次数" + canUseCount);
        }

        bills.setSaleTypeId(saleType.getId());
        bills.setSaleTypeCode(saleType.getSaleCode());
        bills.setSaleTypeName(saleType.getSaleName());

        queryItemDataHandle(bills, enginOrderBean, refCount, saleType);

        return bills;
    }

    private void queryItemDataHandle(AgencyBillsBean bills, EnginOrderBean enginOrderBean, Integer refCount, SaleType saleType) {
        List<String> oldNumbers = bills.getItems().stream()
                .map(Machine4Agency::getCode)
                .collect(Collectors.toList());
        // 获取产品价格列表
        IPage<ProductPriceBean> productPricePage = retailOrderLogic.queryProductList(null, null, null, null, null, null, null, enginOrderBean.getCustomerId(), oldNumbers, OrderTypeEnum.HOME.getKey(), 1, -1);
        List<ProductPriceBean> records = productPricePage.getRecords();
        Map<String, ProductPriceBean> priceBeanMap = records.stream()
                .collect(Collectors.toMap(v -> v.getSaleCode() + v.getMaterialOldNumber(), Function.identity(), (key1, key2) -> key1));

        for (Machine4Agency billsItem : bills.getItems()) {
            ProductPriceBean priceBean = priceBeanMap.get(bills.getSaleTypeCode() + billsItem.getCode());
            if (Objects.isNull(priceBean)) {
                throw new RemoteServiceException(billsItem.getCode() + billsItem.getMachine() + "：没有找到关联价格产品");
            }
            billsItem.setUseRefCount(refCount);
            billsItem.setSaleTypeId(saleType.getId());
            billsItem.setSaleTypeCode(saleType.getSaleCode());
            billsItem.setSaleTypeName(saleType.getSaleName());
            billsItem.setMaterialId(priceBean.getMaterialId());
            billsItem.setMaterialNumber(priceBean.getMaterialNumber());
            billsItem.setMaterialOldNumber(priceBean.getMaterialOldNumber());
            billsItem.setMaterialName(priceBean.getMaterialName());
            billsItem.setSpecification(priceBean.getSpecification());
            billsItem.setUnit(priceBean.getBaseUnit());

            if (CollectionUtil.isEmpty(billsItem.getCustomerWalletList())) {
                billsItem.setCustomerWalletList(new ArrayList<>());
            }
            billsItem.getCustomerWalletList().addAll(priceBean.getRebateWallets());
            billsItem.getCustomerWalletList().addAll(priceBean.getWallets());
        }
    }

    public AgencyBillsBean reqFindBills(String recordNo, String userId) {
//        HashMap<String, Object> paramMap = new HashMap<>();
//
//        paramMap.put("userId", userId);
//        paramMap.put("recordNo", recordNo);
//
//        String jsonStr = HttpUtil.post(enginUrl.replace("sysadmin", "") + "api/supply/findAgencyBills", paramMap);
//
//        JSONObject data = this.CommonHandleInfo(jsonStr);
//
//        EnginSysAgencyBills enginSysAgencyBills = JSONUtil.toBean(data, new TypeReference<EnginSysAgencyBills>() {
//        }, true);
//
//        if (Objects.isNull(enginSysAgencyBills)) {
//            throw new RemoteServiceException(recordNo + "：单据不存在");
//        }

        return agencyBillsLogic.findBills(recordNo, userId);
    }

//    private JSONObject CommonHandleInfo(String jsonStr) {
//        try {
//            if (StringUtils.isBlank(jsonStr)) {
//                throw new RemoteServiceException("工程机系统返回数据异常");
//            }
//            log.info("工程机返回数据：{}", jsonStr);
//            JSONObject result = JSONUtil.parseObj(jsonStr);
//
//            if (result.get("status", Integer.class) != 1) {
//                throw new RemoteServiceException(result.get("msg", String.class));
//            }
//
//            return result.get("data", JSONObject.class);
//        } catch (NullPointerException e) {
//            throw new RemoteServiceException("工程机系统通信异常");
//        }
//    }

    public void updEngineSystemBill(EnginOrder enginOrder, List<EnginOrderItem> orderItems) {
//        List<Machine4Agency> items = new ArrayList<>();
//        for (EnginOrderItem orderItem : orderItems) {
//            Machine4Agency machine4Agency = new Machine4Agency();
//            machine4Agency.setCode(orderItem.getMaterialOldNumber());
//            machine4Agency.setHasDeliverQty(orderItem.getQty());
//            items.add(machine4Agency);
//        }

//        HashMap<String, Object> paramMap = new HashMap<>();
//        if (profiles.equals("dev")) {
//            paramMap.put("userId", "268");
//        } else {
//            paramMap.put("userId", enginOrder.getEnginUserName());
//        }
//        paramMap.put("recordNo", enginOrder.getRefEnginRecordNo());
//        paramMap.put("items", items);

//        String reqStr = JSONUtil.toJsonStr(paramMap);
//        log.info("send engine system data:{}", reqStr);
//        String jsonStr = HttpUtil.post(enginUrl.replace("sysadmin", "") + "api/supply/updateBill", reqStr);
//
//        this.CommonHandleInfo(jsonStr);
        agencyBillsLogic.updateAgencyBillsStatus(enginOrder.getEnginUserName(), enginOrder.getRefEnginRecordNo());
    }

    public List<AgencyBills> queryBills(Collection<String> bills) {
//        HashMap<String, Object> paramMap = new HashMap<>();
//        paramMap.put("bills", bills);
//
//        String jsonStr = HttpUtil.get(enginUrl.replace("sysadmin", "") + "api/supply/queryBills", paramMap);
//
//        this.CommonHandleInfo(jsonStr);
//
//        JSONObject result = JSONUtil.parseObj(jsonStr);
//        JSONArray data = result.getJSONArray("data");
//
//        return JSONUtil.toBean(data, new TypeReference<List<EnginSysAgencyBills>>() {
//        }, true);
        return agencyBillsLogic.queryBills(bills);
    }

    public IPage<EnginOrderListBean> platformQueryList(String userName, String password, String timestamp, String sign,
                                                       String recordNo, String orderNo, String useUnit, String specs,
                                                       String realModel, String address, String orderType, Integer pageNum, Integer pageSize) {
        AdminUser adminUser = adminUserLogic.checkPlatformBind(userName, password, timestamp, sign);

        return enginOrderReserveMapper.platformQueryList(new Page<>(pageNum, pageSize), adminUser.getAdminUserId(), adminUser.getCustomerId(), recordNo, orderNo, useUnit,
                specs, realModel, address, orderType);
    }

    public void platformRef(String recordNo, String itemId, Boolean isRef, String timestamp, String sign) {
        String newSign = JiaSMUtil.jiasmDigest(recordNo, timestamp);
        if (!sign.equals(newSign) || Objects.isNull(isRef)) {
            throw new RemoteServiceException("请求不合法");
        }
        enginOrderItemService.lambdaUpdate()
                .set(EnginOrderItem::getPlatformRef, isRef)
                .eq(EnginOrderItem::getRefEnginRecordNo, recordNo)
                .eq(EnginOrderItem::getId, itemId);
    }
}
