package org.dromara.zhishu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.pop.sdk.common.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.ShopWarehouseAuto;
import org.dromara.zhishu.domain.SinglePrint;
import org.dromara.zhishu.domain.bo.SinglePrintBo;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.service.IProductService;
import org.dromara.zhishu.service.IShopService;
import org.dromara.zhishu.service.IShopWarehouseAutoService;
import org.dromara.zhishu.util.DateUtilsUtils;
import org.dromara.zhishu.util.InterfaceUtils;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class ProductServiceImpl implements IProductService {

    private final IShopService shopService;



    private final IShopWarehouseAutoService shopWarehouseAutoService;

    /**
     * 获取用户仓库信息
     */
    @Override
    public Map getMappingList(){

        String mappingListStr = InterfaceUtils.getInterfaceGetWithParams(
                UrlUtil.getNewWarehouse(),
                "/api/warehouse/mapping_list",
                new HashMap<>()
        );

        Map map = JsonUtil.transferToObj(mappingListStr,Map.class);

        return map;
    }

    @Override
    public TableDataInfo<Map> queryPageList(Map bo) {

        String userId = bo.get("aboutId").toString();
        String warehouseId = bo.get("warehouseId").toString();
        String page = bo.get("pageNum").toString();
        String pageSize = bo.get("pageSize").toString();

        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("page_size", pageSize);
        params.put("user_id",userId);
        params.put("warehouse_id",warehouseId);

        if (bo.get("barcode") != null){
            params.put("barcode",bo.get("barcode").toString());
        }
        if (bo.get("name") != null){
            params.put("name",bo.get("name").toString());
        }
        if (bo.get("appearance") != null){
            params.put("appearance",bo.get("appearance").toString());
        }
        // 库存
        if (bo.get("stockOperator") != null && bo.get("stockValue") != null){
            params.put("stock_operator",bo.get("stockOperator").toString());
            params.put("stock_value", bo.get("stockValue").toString());
        }
        // 价格
        if (bo.get("salepriceOperator") != null && bo.get("salepriceValue") != null){
            params.put("saleprice_operator",bo.get("salepriceOperator").toString());
            // 换算金额
            String saleprice_value = new BigDecimal( bo.get("salepriceValue").toString()).multiply(new BigDecimal(100)).toString();
            params.put("saleprice_value",saleprice_value);
        }
        // 创建日期
        if (bo.get("startCreatedAt") != null){
            params.put("start_created_at", DateUtilsUtils.dateStringToTimestamp10(bo.get("startCreatedAt").toString(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (bo.get("endCreatedAt") != null){
            params.put("end_created_at", DateUtilsUtils.dateStringToTimestamp10(bo.get("endCreatedAt").toString(),"yyyy-MM-dd HH:mm:ss"));
        }

        String productListStr = InterfaceUtils.getInterfaceGetWithParams(
                UrlUtil.getNewWarehouse(),
                "/api/product/distribution_list",
                params
        );
        Map<String, Object> dataMap = JsonUtil.transferToObj(productListStr, Map.class);
        Map<String, Object> data = (Map<String, Object>) dataMap.get("data");

        List<Map> productList = (List<Map>) data.get("list");
        int total = (int) data.get("total");

        Page<Map> result = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize), total);
        result.setRecords(productList);
        return TableDataInfo.build(result);
    }

    /**
     * 发布商品
     * @param map
     * @return
     */
    @Override
    public void releaseGoods(Map map){

        // 获取仓库id
        Long userId = Long.parseLong(map.get("userId").toString());
        // 店铺id数组
        String[] shopIdArr = map.get("shopIds").toString().split(",");
        // 转换成数值类型
        Long[] shopIdLongArr = new Long[shopIdArr.length];
        // 店铺类型数组
        Long[] shopTypeArr = new Long[shopIdArr.length];
        for (int i=0;i<shopIdArr.length;i++){
            String shopId = shopIdArr[i];
            // 获取店铺信息
            ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
            shopIdLongArr[i] = shopVo.getId();
            // 存储数据类型
            shopTypeArr[i] = Long.parseLong(shopVo.getShopType());
        }
        // 是否一键发布标记 0 否  1 是
        String oneClick = map.get("oneClick").toString();
        Long[] productIdLongArr = null;
        if (oneClick.equals("0")){
            // 商品id
            String[] productIdArr = map.get("productIds").toString().split(",");
            // 转换成数值类型
            productIdLongArr = Arrays.stream(productIdArr)
                    .map(String::trim)
                    .map(Long::valueOf)
                    .toArray(Long[]::new);

            // 封装数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user_id",userId);
            jsonObject.put("shop_ids",shopIdLongArr);
            jsonObject.put("shop_types",shopTypeArr);
            jsonObject.put("product_ids",productIdLongArr);
            // 调用发布接口
            InterfaceUtils.postJson(UrlUtil.getNewWarehouse(),"/api/product/batchPush",jsonObject.toJSONString());
        }else {
            /**
             * 一键发布
             */
            // 页数
            int pageNum = 1;
            // 获取参数
            Map params = (Map) map.get("params");
            params.put("pageSize",1000);

            while(true){
                params.put("pageNum",pageNum);
                TableDataInfo<Map> tableDataInfo = queryPageList(params);
                List<Map> productList = tableDataInfo.getRows();
                if (productList == null || productList.isEmpty()){
                    // 当查不到数据的时候退出循环
                    break;
                }else{
                    // 存在数据时
                    pageNum++;
                    // 提取id并转换为String数组
                    String[] productIdArray = productList.stream()
                            .map(productMap -> productMap.get("id").toString()) // 将id转换为String
                            .toArray(String[]::new); // 转换为String数组

                    // 转换成数值类型
                    productIdLongArr = Arrays.stream(productIdArray)
                            .map(String::trim)
                            .map(Long::valueOf)
                            .toArray(Long[]::new);


                    // 封装数据
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("user_id",userId);
                    jsonObject.put("shop_ids",shopIdLongArr);
                    jsonObject.put("shop_types",shopTypeArr);
                    jsonObject.put("product_ids",productIdLongArr);
                    // 调用发布接口
                    InterfaceUtils.postJson(UrlUtil.getNewWarehouse(),"/api/product/batchPush",jsonObject.toJSONString());
                    // 清空商品
                    productIdLongArr = null;
                }
            }
        }
    }

    /**
     * 自动发布接口
     * @param map
     */
    @Override
    public void releaseGoodsAuto(Map map){
        // 用户id
        Long userId = Long.parseLong(map.get("userId").toString());
        // 仓库id
        Long warehouseId = Long.parseLong(map.get("warehouseId").toString());
        // 根据用户id和仓库id查询关联店铺
        ShopWarehouseAuto shopWarehouseAuto = new ShopWarehouseAuto();
        shopWarehouseAuto.setUserId(userId);
        shopWarehouseAuto.setWarehouseId(warehouseId);
        List<ShopWarehouseAuto> shopWarehouseAutoList = shopWarehouseAutoService.queryList(shopWarehouseAuto);
        if (!shopWarehouseAutoList.isEmpty()){
            List<Long> shopIds = shopWarehouseAutoList.stream()
                    .map(ShopWarehouseAuto::getShopId)
                    .toList();

            List<ShopVo> shopVoList = shopService.selectByIds(shopIds);

            String idsStr = shopVoList.stream()
                    .map(ShopVo::getId)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            Map data = new HashMap();
            data.put("userId",userId.toString());
            data.put("shopIds",idsStr);
            data.put("oneClick","0");
            data.put("productIds",map.get("productId").toString());
            releaseGoods(data);
        }
    }
}
