package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
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.R;
import org.dromara.common.core.utils.StringUtils;
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.system.domain.bo.SysDictDataBo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.service.ISysDictDataService;
import org.dromara.zhishu.domain.bo.ZhishuShopGoodsBo;
import org.dromara.zhishu.domain.dto.OrderExternalGoodsDto;
import org.dromara.zhishu.domain.vo.FastMailVo;
import org.dromara.zhishu.domain.vo.ZhishuShopGoodsVo;
import org.dromara.zhishu.service.IFastMailService;
import org.dromara.zhishu.service.IOrderExternalGoodsService;
import org.dromara.zhishu.service.IZhishuShopGoodsService;
import org.dromara.zhishu.util.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓库订单
 *
 * @author yxy
 * @date 2025-12-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/orderExternalGoods")
public class OrderExternalGoodsController {

    private final IOrderExternalGoodsService orderExternalGoodsService;
    private final ISysDictDataService dictDataService;
    private final IZhishuShopGoodsService zhishuShopGoodsService;
    private final IFastMailService fastMailService;


    @GetMapping("/getU")
    public Long getUserId(){
        return LoginHelper.getUserId();
    }

    /**
     * 查询仓库订单列表
     */
    @SaCheckPermission("zhishu:orderExternalGoods:list")
    @GetMapping("/list")
    public TableDataInfo<OrderExternalGoodsDto> list(OrderExternalGoodsDto dto, PageQuery pageQuery) {
        Map params = new HashMap<>();
        params.put("pageNum",pageQuery.getPageNum());
        params.put("pageSize",pageQuery.getPageSize());
        params.put("deptUseId", LoginHelper.getUserId());
        params.put("erpAfterSalesStatus",dto.getErpAfterSalesStatus());
        if(dto.getErpAfterSalesStatus() != 0){
            Long userId = LoginHelper.getUserId();
            if (userId != 1) {
                params.put("createBy",userId);
            }
        }

        if (dto.getOrderStatus() != null){
            params.put("orderStatus",dto.getOrderStatus());
        }

        if (dto.getConfirmStatus() != null){
            params.put("confirmStatus",dto.getConfirmStatus());
        }

        if (dto.getAfterSalesStatus() != null){
            params.put("afterSalesStatus",dto.getAfterSalesStatus());
        }

        if (dto.getTrackingNumber() != null){
            params.put("trackingNumber",dto.getTrackingNumber());
        }

        if (StringUtils.isNotEmpty(dto.getOrderSn())){
            params.put("orderSn",dto.getOrderSn());
        }
        if (dto.getShopType() != null){
            params.put("shopType",dto.getShopType());
        }
        if (dto.getShopErpId() != null){
            params.put("shopErpId",dto.getShopErpId());
        }
        if (StringUtils.isNotEmpty(dto.getItemList())){
            params.put("itemList",dto.getItemList());
        }

        if(!dto.getParams().isEmpty()){
            params.put("startTime",dto.getParams().get("startTime"));
            params.put("endTime",dto.getParams().get("endTime"));
        }

        String OrderExternalGoodsVoListStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/orderExternalGoods/getList",params);
        Map dataMap = JsonUtil.transferToObj(OrderExternalGoodsVoListStr,Map.class);
        List OrderExternalGoodsVoList = (List) dataMap.get("data");

        for (Object object : OrderExternalGoodsVoList){
            Map orderExternalGoodsVo = (Map) object;
            String goodsId = orderExternalGoodsVo.get("goodsId") == null ? "" : orderExternalGoodsVo.get("goodsId").toString();
            if (StringUtils.isNotEmpty(goodsId)){
                // 获取货号
                ZhishuShopGoodsVo zhishuShopGoodsVo = zhishuShopGoodsService.queryById(goodsId);
                if (zhishuShopGoodsVo != null){
                    orderExternalGoodsVo.put("shopGoodsVo",zhishuShopGoodsVo);
                }else{
                   orderExternalGoodsVo.put("shopGoodsVo",null);
                }
            }

        }

        int total = (int) dataMap.get("total");
        Page<OrderExternalGoodsDto> result = new Page<>(pageQuery.getPageNum(),pageQuery.getPageSize(),total);
        result.setRecords(OrderExternalGoodsVoList);
        return TableDataInfo.build(result);
    }

    /**
     * 查询仓库订单列表
     */
    @GetMapping("/appList")
    @SaIgnore
    public TableDataInfo<OrderExternalGoodsDto> appList(OrderExternalGoodsDto dto, PageQuery pageQuery) {
        Map params = new HashMap<>();
        params.put("pageNum",pageQuery.getPageNum());
        params.put("pageSize",pageQuery.getPageSize());
        params.put("deptUseId", dto.getCreateBy());
        params.put("erpAfterSalesStatus",dto.getErpAfterSalesStatus());

        if (StringUtils.isNotEmpty(dto.getOrderSn())){
            params.put("orderSn",dto.getOrderSn());
        }
        if (dto.getShopType() != null){
            params.put("shopType",dto.getShopType());
        }
        if (dto.getOrderStatus() != null){
            params.put("orderStatus",dto.getOrderStatus());
        }
        if(dto.getStartTime() != null){
            params.put("startTime",dto.getStartTime());
        }
        if(dto.getEndTime() != null){
            params.put("endTime",dto.getEndTime());
        }
        if(dto.getWhetherOutbound() != null){
            params.put("whetherOutbound",dto.getWhetherOutbound());
        }
        if (StringUtils.isNotEmpty(dto.getArtNo()) || StringUtils.isNotEmpty(dto.getOriginalArtNo()) || StringUtils.isNotEmpty(dto.getIsbn())){
            ZhishuShopGoodsBo bo = new ZhishuShopGoodsBo();
            bo.setUserId(Long.parseLong(params.get("deptUseId").toString()));
            bo.setIsQueryAllGoods(dto.getIsQueryAllGoods());
            if(StringUtils.isNotEmpty(dto.getArtNo())){
                bo.setArtNo(dto.getArtNo());
            }
            if (StringUtils.isNotEmpty(dto.getOriginalArtNo())){
                bo.setOriginalArtNo(dto.getOriginalArtNo());
            }
            if (StringUtils.isNotEmpty(dto.getIsbn())){
                bo.setIsbn(dto.getIsbn());
            }
            List<ZhishuShopGoodsVo> zhishuShopGoodsVoList = zhishuShopGoodsService.queryList(bo);
            if (zhishuShopGoodsVoList.isEmpty()){
                // 如果根据货号未查询到数据，则直接返回空
                Page<OrderExternalGoodsDto> result = new Page<>(pageQuery.getPageNum(),pageQuery.getPageSize(),0);
                return TableDataInfo.build(result);
            }else{
                params.put("goodsId",zhishuShopGoodsVoList.get(0).getId());
            }
        }

        String OrderExternalGoodsVoListStr = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/orderExternalGoods/getList",params);
        Map dataMap = JsonUtil.transferToObj(OrderExternalGoodsVoListStr,Map.class);
        List OrderExternalGoodsVoList = (List) dataMap.get("data");

        for (int i =0 ;i<OrderExternalGoodsVoList.size();i++){
            Map map = (Map) OrderExternalGoodsVoList.get(i);
            String goodsId =  map.get("goodsId").toString();
            ZhishuShopGoodsVo zhishuShopGoodsVo =  zhishuShopGoodsService.queryById(goodsId);
            if(zhishuShopGoodsVo != null){
                map.put("isbn",zhishuShopGoodsVo.getIsbn());
                map.put("artNo",zhishuShopGoodsVo.getArtNo());
                map.put("originalArtNo",zhishuShopGoodsVo.getOriginalArtNo() == null ? "" : zhishuShopGoodsVo.getOriginalArtNo());
            }else{
                map.put("isbn","");
                map.put("artNo","");
                map.put("originalArtNo","");
            }
        }

        int total = (int) dataMap.get("total");
        Page<OrderExternalGoodsDto> result = new Page<>(pageQuery.getPageNum(),pageQuery.getPageSize(),total);
        result.setRecords(OrderExternalGoodsVoList);
        return TableDataInfo.build(result);
    }


    @PostMapping("/editWhetherOutbound")
    @SaIgnore
    public Map editWhetherOutbound(String ids){
        Map map = new HashMap();
        map.put("ids",ids);
        String result = InterfaceUtils.postForm(UrlUtil.getOrderServiceUrl(),"/api/orderExternalGoods/editWhetherOutbound",map);
        return JsonUtil.transferToObj(result,Map.class);
    }

    /**
     * 快递单号匹配快递公司
     * @param trackingNumber
     * @return
     */
    @GetMapping("/getCompanyInfo")
    public String getCompanyInfo(String trackingNumber){
        ExpressCompanyDetector.ExpressInfo expressInfo = ExpressCompanyDetector.detect(trackingNumber);
        return expressInfo.getCode();
    }

    /**
     * 发货按钮
     * @param map
     * @return
     */
    @PostMapping("/submitCompanyOrder")
    @SaIgnore
    public R<Void> submitCompanyOrder(@RequestBody Map map){
        // 快递公司名称
//        String dictLabel = dictDataService.selectDictLabel("t_fast_mail_type",map.get("code").toString());
//        map.put("companyName",dictLabel);

        SysDictDataBo bo = new SysDictDataBo();
        bo.setDictType("t_fast_mail_type");
        List<SysDictDataVo> sysDictDataVoList = dictDataService.selectDictDataList(bo);
        map.put("sysDictDataVoListStr",JsonUtil.transferToJson(sysDictDataVoList));
//        String json = JsonUtil.transferToJson( map);
//        String result = DllInitializer.executeInterfaceForward("POST",UrlUtil.getOrderServiceUrl() + "/api/erpGoodsOrder/orderCompanyOrder",json);
        String result = InterfaceUtils.postForm(UrlUtil.getOrderServiceUrl(),"/api/erpGoodsOrder/orderCompanyOrder",map);
        System.out.println(result);
        return R.ok();
    }


    @PostMapping("/process")
    public Map process(@RequestBody Map map){
        System.out.println(map);
        Map requestMap = new HashMap();
        requestMap.put("id",map.get("erpOrderId").toString());
        if(null != map.get("erpAssReason") && StringUtils.isNotEmpty(map.get("erpAssReason").toString())){
            requestMap.put("erpAfterSalesStatus","6");
            requestMap.put("erpAssReason",map.get("erpAssReason").toString());
        }else if(null != map.get("rollbackType") && map.get("rollbackType").toString().equals("5")){
            // 延迟处理
            requestMap.put("erpAfterSalesStatus",map.get("rollbackType"));
        } else{
            // 1 同意  2 失败
            String handlingMethod = map.get("handlingMethod").toString();
            if(handlingMethod.equals("1")){
                // 同意售后
                // 回退类型 3 仅退款  2 退货退款
                String rollbackType = map.get("rollbackType").toString();
                requestMap.put("erpAfterSalesStatus",rollbackType);
                if(rollbackType.equals("3")){
                    // 同意仅退款：售后完成
                }else if(rollbackType.equals("2")){
                    // 同意退货退款：待仓库确认收货
                    requestMap.put("erpAssAddress",map.get("returnAddress"));
                }else{
                    // 其他
                    R.fail("未知异常");
                }
            }else if(handlingMethod.equals("2")){
                // 拒绝售后
                requestMap.put("erpAfterSalesStatus","4");
                requestMap.put("erpAssRemark",map.get("reasonForRejection"));
            }else{
                // 其他
                R.fail("未知异常");
            }
        }

        String result = InterfaceUtils.postForm(UrlUtil.getOrderServiceUrl(),"/api/orderExternalGoods/editAfterSales",requestMap);
        Map resultMap = JsonUtil.transferToObj(result,Map.class);
        return resultMap;
    }


    @GetMapping("/getErpAfterSalesOrderLog")
    @SaIgnore
    public List getErpAfterSalesOrderLog(String orderNo){
        String erpOrderLogListStr = InterfaceUtils.getInterface(UrlUtil.getOrderServiceUrl(),"/api/erpGoodsOrder/getErpOrderLog?orderNo="+orderNo+"_erpAfterSalesOrder");
        List erpOrderLogList = JsonUtil.transferToObj(erpOrderLogListStr,List.class);
        return erpOrderLogList;
    }


    /**
     *
     * @param erpOrderId   订单id
     * @param fastMailId    快递账号id
     * @param printTemplateData  打印模板数据
     * @param type    快递类型
     * @param deliveryMode 发货模式  1 全部发货  2 单独发货
     * @return
     */
    @GetMapping("/orderCreate")
    public R<Map> orderCreate(String erpOrderId,String fastMailId,String printTemplateData,String type,String erpGoodsId,String deliveryMode,String orderSn){
        FastMailVo fastMailVo = fastMailService.queryById(Long.parseLong(fastMailId));
        if (fastMailVo.getFastMailType().equals("1")){
            if (type.equals("YUNDA")){
                return orderExternalGoodsService.getYundaPdf(fastMailVo,erpOrderId,printTemplateData,type,deliveryMode,orderSn);
            }else if (type.equals("ZTO")){
                return orderExternalGoodsService.getZtoPdf(fastMailVo,erpOrderId,printTemplateData,type,deliveryMode,orderSn);
            }else if (type.equals("YZXB") || type.equals("JTSD")){
                return orderExternalGoodsService.orderCreate(fastMailVo,erpOrderId,printTemplateData,type,deliveryMode,orderSn);
            }else {
                return R.fail("无快递："+type);
            }
        }else{
            Map res = new HashMap();
            res.put("fastMailVo",JsonUtil.transferToJson(fastMailVo));
            res.put("erpOrderId",erpOrderId);
            res.put("deliveryMode",deliveryMode);
            res.put("orderSn",orderSn);
            String result = InterfaceUtils.postForm(UrlUtil.getOrderServiceUrl(),"/api/print/pddCreateOrder",res);
            Map resultMap = JsonUtil.transferToObj(result,Map.class);
            resultMap.put("fastMailType","2");
            resultMap.put("code",fastMailVo.getType());
            // 获取商品数据
            List<Map<String,String>> dataMapList = new ArrayList<>();
            List erpGoodsOrderList = (List) resultMap.get("erpGoodsOrderList");
            for (Object erpOrderObject : erpGoodsOrderList){
                Map erpOrderMap = (Map) erpOrderObject;
                Map itemMap = JsonUtil.transferToObj(erpOrderMap.get("itemList").toString(),Map.class);
                ZhishuShopGoodsVo zhishuShopGoodsVo = zhishuShopGoodsService.queryById(erpOrderMap.get("erpGoodsId").toString());
                Map dataMap = new HashMap();
                dataMap.put("isbn",zhishuShopGoodsVo.getIsbn());
                dataMap.put("goodsName",itemMap.get("goodsName"));
                dataMap.put("artNo",zhishuShopGoodsVo.getArtNo());
                dataMap.put("originalArtNo",zhishuShopGoodsVo.getOriginalArtNo());
                dataMap.put("goodsCount",itemMap.get("goodsCount"));
                dataMapList.add(dataMap);
            }
            resultMap.put("dataList",dataMapList);
            return R.ok(resultMap);
        }
    }

    /**
     * 获取韵达预览pdf
     * @param erpOrderId
     * @param orderSn
     * @param deliveryMode
     * @param printTemplateData
     * @return
     */
    @GetMapping("/getYunDaPreviewPdf")
    public R<Map> getYunDaPreviewPdf(String erpOrderId,String orderSn,String deliveryMode,String printTemplateData){
        Map res = new HashMap();

        Map erpGoodsOrderMap = new HashMap();
        erpGoodsOrderMap.put("orderId",erpOrderId);
        erpGoodsOrderMap.put("orderSn",orderSn);
        erpGoodsOrderMap.put("deliveryMode",deliveryMode);

        String data = InterfaceUtils.getInterfaceGetWithParams(UrlUtil.getOrderServiceUrl(),"/api/print/getOrderData",erpGoodsOrderMap);
        Map dataMap = JsonUtil.transferToObj(data,Map.class);
        List<Map<String,String>> dataMapList = new ArrayList<>();
        List erpGoodsOrderList = (List) dataMap.get("erpGoodsOrderList");
        for (Object erpOrderObject : erpGoodsOrderList){
            Map erpOrderMap = (Map) erpOrderObject;
            Map itemMap = JsonUtil.transferToObj(erpOrderMap.get("itemList").toString(),Map.class);
            ZhishuShopGoodsVo zhishuShopGoodsVo = zhishuShopGoodsService.queryById(erpOrderMap.get("erpGoodsId").toString());
            Map goodsMap = new HashMap();
            goodsMap.put("isbn",zhishuShopGoodsVo.getIsbn());
            goodsMap.put("goodsName",itemMap.get("goodsName"));
            goodsMap.put("artNo",zhishuShopGoodsVo.getArtNo());
            goodsMap.put("originalArtNo",zhishuShopGoodsVo.getOriginalArtNo());
            goodsMap.put("goodsCount",itemMap.get("goodsCount"));
            dataMapList.add(goodsMap);
        }
        // 收件人信息
        Map receiver = (Map) dataMap.get("receiver");
        // 发件人信息
        Map sender = (Map) dataMap.get("sender");
        String yundaPdf = DaDanUtil.getYunDaPreview();
        res.put("code","200");
        res.put("msg","快递单获取成功");
        res.put("pdfInfo",yundaPdf);
        res.put("receiver",receiver);
        res.put("sender",sender);
        res.put("dataList",dataMapList);
        res.put("printTemplateData",printTemplateData);
        return R.ok(res);
    }


    /**
     * 运单取消
     */
    @GetMapping("/cancelBmOrder")
    public R<Void> cancelBmOrder(String erpOrderId){
        String res = InterfaceUtils.getInterface(UrlUtil.getOrderServiceUrl(),"/api/print/cancelBmOrder?erpOrderId="+erpOrderId);
        Map resMap = JsonUtil.transferToObj(res,Map.class);
        if (resMap.get("code").equals("200")){
            return R.ok(resMap.get("msg").toString());
        }else{
            return R.fail(resMap.get("msg").toString());
        }
    }

    @GetMapping("/printView")
    public R<Map> printView(String erpOrderId){
        String res = InterfaceUtils.getInterface(UrlUtil.getOrderServiceUrl(),"/api/print/printView?erpOrderId="+erpOrderId);
        Map resMap = JsonUtil.transferToObj(res,Map.class);
        if (resMap.get("code").equals("200")){
            return R.ok(resMap);
        }else{
            return R.fail(resMap.get("msg").toString());
        }
    }
}
