package com.ruoyi.logistics.controller;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.logistics.constant.ImportTemplateConstants;
import com.ruoyi.logistics.constant.JDDictConstants;
import com.ruoyi.logistics.domain.BizWaybillOrder;
import com.ruoyi.logistics.domain.SysDeptRate;
import com.ruoyi.logistics.domain.dto.JDOrderDTO;
import com.ruoyi.logistics.handler.JDOrderDynamicTemplateHandler;
import com.ruoyi.logistics.domain.dto.SfOrderImportDTO;
import com.ruoyi.logistics.handler.SFOrderDynamicTemplateHandler;
import com.ruoyi.logistics.service.IBizWaybillOrderService;
import com.ruoyi.logistics.service.impl.SysDeptRateServiceImpl;
import com.ruoyi.logistics.util.ExcelImportValidato;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * PC-运单管理
 * 
 * @author RuiJing
 * @date 2026-01-29
 */
@RestController
@RequestMapping("/order")
public class BizWaybillOrderController extends BaseController
{
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BizWaybillOrderController.class);
    @Autowired
    private IBizWaybillOrderService bizWaybillOrderService;

    @Autowired
    private SysDeptRateServiceImpl sysDeptRateService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询运单管理列表
     */
    @RequiresPermissions("system:order:list")
    @GetMapping("/list")

    public TableDataInfo list(BizWaybillOrder bizWaybillOrder)
    {
        startPage();
        List<BizWaybillOrder> list = bizWaybillOrderService.selectBizWaybillOrderList(bizWaybillOrder);
        return getDataTable(list);
    }

    /**
     * 导出运单管理列表
     */
    @RequiresPermissions("system:order:export")
    @Log(title = "运单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizWaybillOrder bizWaybillOrder)
    {
        List<BizWaybillOrder> list = bizWaybillOrderService.selectBizWaybillOrderList(bizWaybillOrder);
        ExcelUtil<BizWaybillOrder> util = new ExcelUtil<BizWaybillOrder>(BizWaybillOrder.class);
        util.exportExcel(response, list, "运单管理数据");
    }

    /**
     * 获取运单管理详细信息
     */
    @RequiresPermissions("system:order:query")
    @GetMapping(value = "/{waybillId}")
    public AjaxResult getInfo(@PathVariable("waybillId") Long waybillId)
    {
        return success(bizWaybillOrderService.selectBizWaybillOrderByWaybillId(waybillId));
    }

    /**
     * 新增运单管理
     */
    @RequiresPermissions("system:order:add")
    @Log(title = "运单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizWaybillOrder bizWaybillOrder) {
        try{
            return toAjax(bizWaybillOrderService.insertBizWaybillOrder(bizWaybillOrder));
          }
         catch(ServiceException e){
            return AjaxResult.error("下单失败！ 原因:"+e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }








    /**
     * 取消运单
     */
    @RequiresPermissions("system:order:edit")
    @Log(title = "运单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizWaybillOrder bizWaybillOrder)
    {

        try{
            bizWaybillOrderService.canceleBizWaybillOrder(bizWaybillOrder);
            return AjaxResult.success("运单取消成功！");
        }
        catch(ServiceException e){
            return AjaxResult.error("取消运单失败！ 原因:"+e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除运单管理
     */
    @RequiresPermissions("system:order:remove")
    @Log(title = "运单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{waybillIds}")
    public AjaxResult remove(@PathVariable Long[] waybillIds)
    {
        return toAjax(bizWaybillOrderService.deleteBizWaybillOrderByWaybillIds(waybillIds));
    }



    /**
     * 获取运单管理详细信息
     */
    @RequiresPermissions("system:order:query")
    @GetMapping(value = "/getFeeInfo")
    public AjaxResult getFeeInfo(@RequestParam("waybillCode") String waybillCode) {
        return success(bizWaybillOrderService.queryOrderFeeInfo(1, waybillCode));
    }


    /**
     * 获取运单pdf
     */
    @RequiresPermissions("system:order:query")
    @GetMapping(value = "/getWaybillPdf")
    public AjaxResult getWaybillPdf(@RequestParam("waybillId") Long waybillId) {
        BizWaybillOrder bizWaybillOrder = bizWaybillOrderService.selectBizWaybillOrderByWaybillId(waybillId);
        return success(bizWaybillOrderService.queryWaybillPdf(bizWaybillOrder));
    }

    /**
     * 批量下单
     */
  //  @RequiresPermissions("system:order:add")
    @Log(title = "批量下单", businessType = BusinessType.INSERT)
    @PostMapping("/batchAdd")
    public AjaxResult batchAdd(@RequestParam("file") MultipartFile file,
                                @RequestParam("orderType") Integer orderType) {

        int total=0;
        try {
            // 校验订单类型
            if (orderType == null || (orderType != 1 && orderType != 2)) {
                return AjaxResult.error("订单类型参数错误，必须为 1（京东）或 2（顺丰）");
            }

            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传的 Excel 文件为空");
            }

            // 使用 ExcelUtil 读取 Excel 数据
            if (1 == orderType) {
                List<JDOrderDTO> orderList = EasyExcel.read(file.getInputStream())
                        .head(JDOrderDTO.class)
                        .sheet()
                        .doReadSync();
                // 校验数据
                if (orderList == null || orderList.isEmpty()) {
                    return AjaxResult.error("Excel 文件中没有有效的订单数据");
                }
                // 标准校验：是否为规定模板
                boolean isTemplate = ExcelImportValidato.isValidTemplate(
                        file,
                        ImportTemplateConstants.JD_TEMPLATE_HEAD
                );

                if (!isTemplate) {
                    return AjaxResult.error("请使用系统提供的导入模板，请勿修改表头！");
                }


                Map<String,Object> result = bizWaybillOrderService.validateAndGetErrorJd(orderList);
                if (StringUtils.isNotBlank(result.get("errorMsg").toString())) {
                    return AjaxResult.error(result.get("errorMsg").toString());
                }
                total = orderList.size();
                // 调用批量下单方法
              // 先不用  bizWaybillOrderService.batchInsertJDBizWaybillOrder(orderList, orderType);



               bizWaybillOrderService.asyncBatchInsertJd((List<BizWaybillOrder>) result.get("orderList"), orderType);

            }
            if (2 == orderType) {

                ExcelUtil<SfOrderImportDTO> util = new ExcelUtil<>(SfOrderImportDTO.class);
                List<SfOrderImportDTO> orderList = EasyExcel.read(file.getInputStream())
                        .head(SfOrderImportDTO.class)
                        .sheet()
                        .doReadSync();

                // 校验数据
                if (orderList == null || orderList.isEmpty()) {
                    return AjaxResult.error("Excel 文件中没有有效的订单数据");
                }


                // 标准校验：是否为规定模板
                boolean isTemplate = ExcelImportValidato.isValidTemplate(
                        file,
                        ImportTemplateConstants.SF_TEMPLATE_HEAD
                );

                if (!isTemplate) {
                    return AjaxResult.error("请使用系统提供的导入模板，请勿修改表头！");
                }



                // 2. 统一校验（返回错误字符串）
                Map<String,Object> result = bizWaybillOrderService.validateAndGetError(orderList);
                // 3. 有错误 → 直接返回字符串
                if (StringUtils.isNotBlank(result.get("errorMsg").toString())) {
                    return AjaxResult.error(result.get("errorMsg").toString());
                }
                total=orderList.size();
                // 调用异步批量下单方法
              bizWaybillOrderService.asyncBatchInsert((List<BizWaybillOrder>) result.get("orderList"), orderType);
            }
            return AjaxResult.success(String.format("本次导入共【%d】条数据，后台已自动开启对接第三方接口下单，请 1-2 分钟后刷新列表仔细核对导入结果！",total));

        } catch (Exception e) {
            log.error("批量下单异常", e);
            return AjaxResult.error("批量下单失败：" + e.getMessage());
        }
    }



    /**
     * 下载批量下单模板
     */
    @RequiresPermissions("system:order:add")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, @RequestParam("orderType") Integer orderType) throws IOException {
        if (1 == orderType) {
            List<String> productCodes = getProductCodeList(); // 从数据库获取产品类型
            List<String> goodsNames = getGoodsNameList(); // 物品名称
            JDOrderDynamicTemplateHandler handler = new JDOrderDynamicTemplateHandler();
            handler.exportDynamicTemplate(response, productCodes, goodsNames);
        }
        if (2 == orderType) {
            List<String> productCodes = getProductCodeListSf(); // 从数据库获取产品类型
            List<String> goodsNames = getGoodsNameList(); // 物品名称
            SFOrderDynamicTemplateHandler handler = new SFOrderDynamicTemplateHandler();
            handler.exportDynamicTemplate(response, productCodes, goodsNames);
        }
    }

    private List<String> getProductCodeListSf() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        SysDeptRate sysDeptRate = new SysDeptRate();
        sysDeptRate.setDeptId(loginUser.getSysUser().getDeptId());
        sysDeptRate.setCompanyType("2");
        List<SysDeptRate> sysDeptRates = sysDeptRateService.selectSysDeptRateList(sysDeptRate);
        List<String> productNames = new ArrayList<>();
        for (SysDeptRate item : sysDeptRates) {
            if (JDDictConstants.PRODUCT_CODE_SF_01.equals(item.getProductType())) {
                productNames.add("顺丰特快");
            } else if (JDDictConstants.PRODUCT_CODE_SF_02.equals(item.getProductType())) {
                productNames.add("顺丰标快");
            }
        }
        return productNames;
    }

    /**
     * 获取产品类型下拉列表
     */
    private List<String> getProductCodeList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        SysDeptRate sysDeptRate = new SysDeptRate();
        sysDeptRate.setDeptId(loginUser.getSysUser().getDeptId());
        sysDeptRate.setCompanyType("1");
        List<SysDeptRate> sysDeptRates = sysDeptRateService.selectSysDeptRateList(sysDeptRate);
        List<String> productNames = new ArrayList<>();
        for (SysDeptRate item : sysDeptRates) {
            if (JDDictConstants.PRODUCT_CODE_ED_M_0001.equals(item.getProductType())) {
                productNames.add("京东标快");
            } else if (JDDictConstants.PRODUCT_CODE_ED_M_0002.equals(item.getProductType())) {
                productNames.add("京东特快");
            } else if (JDDictConstants.PRODUCT_CODE_FR_M_0004.equals(item.getProductType())) {
                productNames.add("特快重货");
            }
        }
        return productNames;
    }

    /**
     * 获取物品下拉列表
     */
    private List<String> getGoodsNameList() {
        List<SysDictData> dict = dictTypeService.selectDictDataByType("jd_goods_type");
        return dict.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
    }

}
