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.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.service.IJDOrderService;
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;

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

    /**
     * 查询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);
        }
        
        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());
                } else {
                    jdOrder.setProPriceAmount(0.0);
                    jdOrder.setFinishTime(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());
                } else {
                    jdOrder.setProPriceAmount(0.0);
                }
            }
        }

        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));
    }
}
