package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.jarvis.domain.OrderRows;
import com.ruoyi.jarvis.service.IOrderRowsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.jarvis.domain.JDOrder;
import com.ruoyi.jarvis.domain.dto.JDOrderSimpleDTO;
import com.ruoyi.jarvis.service.IJDOrderService;
import com.ruoyi.jarvis.service.IInstructionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * JD订单列表Controller
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/jdorder")
public class JDOrderListController extends BaseController
{

    private final IJDOrderService jdOrderService;
    private final IOrderRowsService orderRowsService;
    private final IInstructionService instructionService;

    public JDOrderListController(IJDOrderService jdOrderService, IOrderRowsService orderRowsService, IInstructionService instructionService) {
        this.jdOrderService = jdOrderService;
        this.orderRowsService = orderRowsService;
        this.instructionService = instructionService;
    }

    /**
     * 查询JD订单列表
     */
    @org.springframework.web.bind.annotation.GetMapping("/list")
    public TableDataInfo list(JDOrder query, HttpServletRequest request) {
        startPage();
        
        // 处理排序参数
        String orderBy = request.getParameter("orderBy");
        String isAsc = request.getParameter("isAsc");
        
        // 处理时间筛选参数
        String beginTimeStr = request.getParameter("beginTime");
        String endTimeStr = request.getParameter("endTime");
        
        if (beginTimeStr != null && !beginTimeStr.isEmpty()) {
            query.getParams().put("beginTime", beginTimeStr);
        }
        if (endTimeStr != null && !endTimeStr.isEmpty()) {
            query.getParams().put("endTime", endTimeStr);
        }
        
        // 处理完成日期筛选参数
        String hasFinishTime = request.getParameter("hasFinishTime");
        if (hasFinishTime != null && "true".equalsIgnoreCase(hasFinishTime)) {
            query.getParams().put("hasFinishTime", true);
        }
        
        // 处理混合搜索参数（订单号/第三方单号/分销标识）
        String orderSearch = request.getParameter("orderSearch");
        if (orderSearch != null && !orderSearch.trim().isEmpty()) {
            query.getParams().put("orderSearch", orderSearch.trim());
        }
        
        java.util.List<JDOrder> list;
        if (orderBy != null && !orderBy.isEmpty()) {
            // 设置排序参数
            query.getParams().put("orderBy", orderBy);
            query.getParams().put("isAsc", isAsc);
            list = jdOrderService.selectJDOrderListWithSort(query);
        } else {
            list = jdOrderService.selectJDOrderList(query);
        }
        
        TableDataInfo dataTable = getDataTable(list);
        List<JDOrder> rows = (List<JDOrder>) dataTable.getRows();
        
        // 如果需要筛选完成日期不为空，先过滤后再关联查询
        if (hasFinishTime != null && "true".equalsIgnoreCase(hasFinishTime)) {
            // 先关联查询所有订单的完成时间
            for (JDOrder jdOrder : rows) {
                OrderRows orderRows = orderRowsService.selectOrderRowsByOrderId(jdOrder.getOrderId());
                if (orderRows != null) {
                    jdOrder.setProPriceAmount(orderRows.getProPriceAmount());
                    jdOrder.setFinishTime(orderRows.getFinishTime());
                    jdOrder.setOrderStatus(orderRows.getValidCode());
                } else {
                    jdOrder.setProPriceAmount(0.0);
                    jdOrder.setFinishTime(null);
                    jdOrder.setOrderStatus(null);
                }
            }
            // 过滤掉完成时间为空的订单
            rows.removeIf(jdOrder -> jdOrder.getFinishTime() == null);
            // 更新总数
            dataTable.setTotal(rows.size());
        } else {
            // 正常关联查询
            for (JDOrder jdOrder : rows) {
                OrderRows orderRows = orderRowsService.selectOrderRowsByOrderId(jdOrder.getOrderId());
                if (orderRows != null) {
                    jdOrder.setProPriceAmount(orderRows.getProPriceAmount());
                    jdOrder.setFinishTime(orderRows.getFinishTime());
                    jdOrder.setOrderStatus(orderRows.getValidCode());
                } else {
                    jdOrder.setProPriceAmount(0.0);
                    jdOrder.setOrderStatus(null);
                }
            }
        }

        return dataTable;
    }

    /**
     * 导出JD订单列表
     */
    @Log(title = "JD订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, JDOrder jdOrder) throws IOException
    {
        String fileName = "JD订单数据";

        List<JDOrder> list = jdOrderService.selectJDOrderList(jdOrder);

        // 设置响应头，指定文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFileName = java.net.URLEncoder.encode(fileName + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        // 添加download-filename响应头，以支持前端工具类
        response.setHeader("download-filename", encodedFileName);

        ExcelUtil<JDOrder> util = new ExcelUtil<JDOrder>(JDOrder.class);
        util.exportExcel(response, list, fileName);
    }

    /**
     * 获取JD订单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(jdOrderService.selectJDOrderById(id));
    }

    /**
     * 新增JD订单
     */
    @Log(title = "JD订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JDOrder jdOrder)
    {
        return toAjax(jdOrderService.insertJDOrder(jdOrder));
    }

    /**
     * 修改JD订单
     */
    @Log(title = "JD订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JDOrder jdOrder)
    {
        return toAjax(jdOrderService.updateJDOrder(jdOrder));
    }

    /**
     * 删除JD订单
     */
    @Log(title = "JD订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(jdOrderService.deleteJDOrderByIds(ids));
    }

    /**
     * 订单搜索工具接口（返回简易字段）
     */
    @Anonymous
    @GetMapping("/tools/search")
    public TableDataInfo searchOrders(
            @RequestParam(required = false) String orderSearch,
            @RequestParam(required = false) String address,
            HttpServletRequest request)
    {
        // startPage会从request中读取pageNum和pageSize参数
        startPage();
        
        JDOrder query = new JDOrder();
        
        // 处理单号搜索（过滤TF、H、F、PDD等关键词）
        if (orderSearch != null && !orderSearch.trim().isEmpty()) {
            String searchKeyword = orderSearch.trim().toUpperCase();
            // 过滤掉TF、H、F、PDD等关键词
            if (searchKeyword.contains("TF") || searchKeyword.contains("H") || 
                searchKeyword.contains("F") || searchKeyword.contains("PDD")) {
                // 如果包含过滤关键词，返回空结果
                return getDataTable(new java.util.ArrayList<>());
            }
            // 至少5个字符
            if (searchKeyword.length() >= 5) {
                query.getParams().put("orderSearch", orderSearch.trim());
            }
        }
        
        // 处理地址搜索（至少3个字符）
        if (address != null && !address.trim().isEmpty()) {
            if (address.trim().length() >= 3) {
                query.setAddress(address.trim());
            }
        }
        
        // 如果没有有效的搜索条件，返回空结果
        if ((orderSearch == null || orderSearch.trim().isEmpty() || orderSearch.trim().length() < 5) &&
            (address == null || address.trim().isEmpty() || address.trim().length() < 3)) {
            return getDataTable(new java.util.ArrayList<>());
        }
        
        java.util.List<JDOrder> list = jdOrderService.selectJDOrderList(query);
        
        // 转换为简易DTO，只返回前端需要的字段，其他字段脱敏
        java.util.List<JDOrderSimpleDTO> simpleList = new java.util.ArrayList<>();
        for (JDOrder jdOrder : list) {
            JDOrderSimpleDTO dto = new JDOrderSimpleDTO();
            
            // 只设置前端需要的字段
            dto.setRemark(jdOrder.getRemark());
            dto.setOrderId(jdOrder.getOrderId());
            dto.setThirdPartyOrderNo(jdOrder.getThirdPartyOrderNo());
            dto.setModelNumber(jdOrder.getModelNumber());
            dto.setAddress(jdOrder.getAddress());
            dto.setIsRefunded(jdOrder.getIsRefunded() != null ? jdOrder.getIsRefunded() : 0);
            dto.setIsRebateReceived(jdOrder.getIsRebateReceived() != null ? jdOrder.getIsRebateReceived() : 0);
            dto.setStatus(jdOrder.getStatus());
            dto.setCreateTime(jdOrder.getCreateTime());
            
            // 关联查询订单状态和赔付金额
            OrderRows orderRows = orderRowsService.selectOrderRowsByOrderId(jdOrder.getOrderId());
            if (orderRows != null) {
                dto.setProPriceAmount(orderRows.getProPriceAmount());
                dto.setOrderStatus(orderRows.getValidCode());
            } else {
                dto.setProPriceAmount(0.0);
                dto.setOrderStatus(null);
            }
            
            simpleList.add(dto);
        }
        
        return getDataTable(simpleList);
    }

    /**
     * 一次性批量更新历史订单：将赔付金额大于0的订单标记为后返到账
     * 此方法只应执行一次，用于处理历史数据
     */
    @Log(title = "批量标记后返到账", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/tools/batch-mark-rebate-received", method = {RequestMethod.POST, RequestMethod.GET})
    public AjaxResult batchMarkRebateReceivedForCompensation() {
        try {
            // 调用批量更新方法
            if (instructionService instanceof com.ruoyi.jarvis.service.impl.InstructionServiceImpl) {
                ((com.ruoyi.jarvis.service.impl.InstructionServiceImpl) instructionService)
                    .batchMarkRebateReceivedForCompensation();
                return AjaxResult.success("批量标记后返到账完成，请查看控制台日志");
            } else {
                return AjaxResult.error("无法执行批量更新操作");
            }
        } catch (Exception e) {
            return AjaxResult.error("批量标记失败: " + e.getMessage());
        }
    }

    /**
     * 生成录单格式文本（Excel可粘贴格式）
     * 根据当前查询条件生成Tab分隔的文本，可以直接粘贴到Excel
     */
    @GetMapping("/generateExcelText")
    public AjaxResult generateExcelText(JDOrder query, HttpServletRequest request) {
        try {
            // 处理时间筛选参数
            String beginTimeStr = request.getParameter("beginTime");
            String endTimeStr = request.getParameter("endTime");
            
            if (beginTimeStr != null && !beginTimeStr.isEmpty()) {
                query.getParams().put("beginTime", beginTimeStr);
            }
            if (endTimeStr != null && !endTimeStr.isEmpty()) {
                query.getParams().put("endTime", endTimeStr);
            }
            
            // 处理混合搜索参数
            String orderSearch = request.getParameter("orderSearch");
            if (orderSearch != null && !orderSearch.trim().isEmpty()) {
                query.getParams().put("orderSearch", orderSearch.trim());
            }
            
            // 处理其他查询参数
            if (query.getRemark() != null && !query.getRemark().trim().isEmpty()) {
                query.setRemark(query.getRemark().trim());
            }
            if (query.getDistributionMark() != null && !query.getDistributionMark().trim().isEmpty()) {
                query.setDistributionMark(query.getDistributionMark().trim());
            }
            if (query.getModelNumber() != null && !query.getModelNumber().trim().isEmpty()) {
                query.setModelNumber(query.getModelNumber().trim());
            }
            if (query.getBuyer() != null && !query.getBuyer().trim().isEmpty()) {
                query.setBuyer(query.getBuyer().trim());
            }
            if (query.getAddress() != null && !query.getAddress().trim().isEmpty()) {
                query.setAddress(query.getAddress().trim());
            }
            if (query.getStatus() != null && !query.getStatus().trim().isEmpty()) {
                query.setStatus(query.getStatus().trim());
            }
            
            // 获取订单列表（不分页，获取所有符合条件的订单）
            List<JDOrder> list = jdOrderService.selectJDOrderList(query);
            
            if (list == null || list.isEmpty()) {
                return AjaxResult.success("暂无订单数据");
            }
            
            // 关联查询订单状态和赔付金额
            for (JDOrder jdOrder : list) {
                OrderRows orderRows = orderRowsService.selectOrderRowsByOrderId(jdOrder.getOrderId());
                if (orderRows != null) {
                    jdOrder.setProPriceAmount(orderRows.getProPriceAmount());
                    // estimateCosPrice 是京粉实际价格
                    if (orderRows.getEstimateCosPrice() != null) {
                        jdOrder.setJingfenActualPrice(orderRows.getEstimateCosPrice());
                    }
                }
            }
            
            // 按 remark 排序
            list.sort((o1, o2) -> {
                String r1 = o1.getRemark() != null ? o1.getRemark() : "";
                String r2 = o2.getRemark() != null ? o2.getRemark() : "";
                return r1.compareTo(r2);
            });
            
            // 生成Excel格式文本（Tab分隔）
            StringBuilder sb = new StringBuilder();
            for (JDOrder o : list) {
                // 日期（格式：yyyy/MM/dd）
                String dateStr = "";
                if (o.getOrderTime() != null) {
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy/MM/dd");
                    dateStr = sdf.format(o.getOrderTime());
                }
                
                // 多多单号（第三方单号，如果没有则使用内部单号）
                String duoduoOrderNo = o.getThirdPartyOrderNo() != null && !o.getThirdPartyOrderNo().trim().isEmpty() 
                    ? o.getThirdPartyOrderNo() : (o.getRemark() != null ? o.getRemark() : "");
                
                // 型号
                String modelNumber = o.getModelNumber() != null ? o.getModelNumber() : "";
                
                // 数量（固定为1）
                String quantity = "1";
                
                // 地址
                String address = o.getAddress() != null ? o.getAddress() : "";
                
                // 姓名（从地址中提取，地址格式通常是"姓名 电话 详细地址"）
                String buyer = "";
                if (address != null && !address.trim().isEmpty()) {
                    String[] addressParts = address.trim().split("\\s+");
                    if (addressParts.length > 0) {
                        buyer = addressParts[0];
                    }
                }
                
                // 售价（固定为0）
                String sellingPriceStr = "0";
                
                // 成本（售价是0，成本也设为空）
                String costStr = "";
                
                // 利润（后返金额）
                Double rebate = o.getRebateAmount() != null ? o.getRebateAmount() : 0.0;
                String profitStr = rebate > 0 
                    ? String.format(java.util.Locale.ROOT, "%.2f", rebate) : "";
                
                // 京东单号
                String orderId = o.getOrderId() != null ? o.getOrderId() : "";
                
                // 物流链接
                String logisticsLink = o.getLogisticsLink() != null ? o.getLogisticsLink() : "";
                
                // 下单付款
                String paymentAmountStr = o.getPaymentAmount() != null 
                    ? String.format(java.util.Locale.ROOT, "%.2f", o.getPaymentAmount()) : "";
                
                // 后返
                String rebateAmountStr = o.getRebateAmount() != null 
                    ? String.format(java.util.Locale.ROOT, "%.2f", o.getRebateAmount()) : "";
                
                // 按顺序拼接：日期、多多单号、型号、数量、姓名、地址、售价、成本、利润、京东单号、物流、下单付款、后返
                sb.append(dateStr).append('\t')
                  .append(duoduoOrderNo).append('\t')
                  .append(modelNumber).append('\t')
                  .append(quantity).append('\t')
                  .append(buyer).append('\t')
                  .append(address).append('\t')
                  .append(sellingPriceStr).append('\t')
                  .append(costStr).append('\t')
                  .append(profitStr).append('\t')
                  .append(orderId).append('\t')
                  .append(logisticsLink).append('\t')
                  .append(paymentAmountStr).append('\t')
                  .append(rebateAmountStr).append('\n');
            }
            
            return AjaxResult.success(sb.toString());
        } catch (Exception e) {
            return AjaxResult.error("生成失败: " + e.getMessage());
        }
    }
}
