package com.fdkankan.platform.order.controller.manager;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.controller.BaseController;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.platform.order.service.IDownloadOrderService;
import com.fdkankan.platform.user.request.RequestOrder;
import com.fdkankan.platform.user.vo.ResponseOrder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.net.URLEncoder;

@Log4j2
@RestController
@RequestMapping("/api/manager/downloadOrder")
public class ManagerDownLoadOrderController extends BaseController {

    @Autowired
    private IDownloadOrderService downloadOrderService;

    /**
     * 获取订单列表
     * @return
     */
    @PostMapping(value = {"/list"})
    public Page<ResponseOrder> list(@RequestBody RequestOrder param) throws Exception {
         return downloadOrderService.getOrderList(param);
    }

    /**
     * 获取订单详情
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public ResponseOrder detail(@RequestBody RequestOrder param) throws Exception {
         return downloadOrderService.findByOrderId(param.getOrderId());
    }

    /**
     * 订单发货确认
     */
    @GetMapping(value = "/export")
    public void export(String type, String orderSn, String phoneNum, String expressNum, String startDate, String endDate,String tradeNum) throws Exception {
        RequestOrder param = new RequestOrder();
        param.setType(type);
        param.setOrderSn(orderSn);
        param.setPhoneNum(phoneNum);
        param.setTradeNum(tradeNum);
        param.setExpressNum(expressNum);
        param.setStartDate(startDate);
        param.setEndDate(endDate);
        String filePath  = downloadOrderService.export(param);
        if(ObjectUtils.isEmpty(filePath)){
            throw new BusinessException(-1,"下载失败，请重试");
        }
        String fileName = URLEncoder.encode(new File(filePath).getName(), "UTF-8");

        String agent = request.getHeader("User-Agent");
        if (agent != null && (agent.contains("MSIE")||agent.contains("Trident"))) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
        response.setContentType(request.getServletContext().getMimeType(fileName));
        File file = new File(filePath);
        response.setContentLength((int) file.length());
        output(response, file);
    }


}
