package com.org.hktshop.controller.order;

import com.org.hktshop.dto.HktOrderAdminSearchDto;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.service.order.HktOrderService;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.controller.BaseController;
import com.org.hktshop.dto.PageQueryDto;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.order.HktOrder;
import com.org.hktshop.service.user.HktUserService;
import com.org.hktshop.utils.HttpCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@RestController
@RequestMapping("/")
@Api(tags = "管理端订单接口")
public class HktAdminOrderController extends BaseController {

    @Autowired
    private HktOrderService hktOrderService;

    @Autowired
    private HktUserService hktUserService;


    /**
     * 删除订单
     *
     * @param id
     * @return
     */
    @GetMapping("async/order/deleteOrder")
    @ApiOperation(value = "删除订单", notes = "删除订单")
    public BaseResult deleteOrder(@RequestParam("id") String id) {
        try {
            HktOrder order = new HktOrder();
            order.setId(id);
            hktOrderService.deleteHktOrder(order);
            return BaseResult.success();
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    /**
     * 修改订单
     *
     * @param hktOrder
     * @return
     */
    @PostMapping("async/order/updateOrder")
    @ApiOperation(value = "修改订单", notes = "修改订单")
    public BaseResult updateOrder(@RequestBody HktOrder hktOrder) {
        try {
            hktOrderService.updateHktOrder(hktOrder);
            return BaseResult.success();
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }


    @PostMapping("async/order/getOrdersByAdminSearch")
    @ApiOperation(value = "通过条件查询物流和自提订单", notes = "通过条件查询物流和自提订单")
    public BaseResult<Page<HktOrder>> getOrdersByAdminSearch(@RequestBody PageQueryDto<HktOrderAdminSearchDto> pageQueryDto) {
        try {
            Page<HktOrder> hktOrders = hktOrderService.getOrdersByAdminSearch(pageQueryDto);
            return BaseResult.successWithData(hktOrders);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    /****
     * 管理端查看订单明细
     * @param id
     * @return
     */
    @GetMapping("async/order/getOrderOderById")
    @ApiOperation(value = "通过订单id查询订单信息", notes = "通过订单id查询订单信息")
    public BaseResult<HktOrder> getHktOrderOderSn(@RequestParam("id") String id) {
        try {
            HktOrder order = new HktOrder();
            order.setId(id);
            HktOrder hktOrder = hktOrderService.getHktOrder(order);
            return BaseResult.successWithData(hktOrder);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }


    @GetMapping("async/order/orderSummary")
    @ApiOperation(value = "管理后台 订单统计", notes = "管理后台 订单统计")
    public BaseResult orderSummary() {
        try {
            Map<String, Object> retMap = hktOrderService.OrderSummary();
            return BaseResult.successWithData(retMap);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }


    /**
     * 商品导出
     */
    @ApiOperation(value = "订单导出", notes = "订单导出")
    @GetMapping(value = "order/excel/orderExport")
    public ResponseEntity<ByteArrayResource> downloadCategoryImportExcel(@RequestParam String orderSn){
        ByteArrayOutputStream bos = null;
        try {
            HktOrder hktOrder = new HktOrder();
            hktOrder.setOrderSn(orderSn);
            HktOrder ho = hktOrderService.getHktOrder(hktOrder);
            HktUser hktUser = new HktUser();
            hktOrder.setId(ho.getUserId());
            HktUser hus = hktUserService.queryUser(hktUser);
            ho.setUserId(hus.getName());
            HSSFWorkbook sheets =hktOrderService.getOrderSheet(ho);
            bos = new ByteArrayOutputStream();
            sheets.write(bos);
            //excel字节码
            byte[] excelBytes = bos.toByteArray();
            //用时间做excel名
            String sheetName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment;fileName=" + sheetName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity.ok().headers(headers).contentLength(excelBytes.length)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new ByteArrayResource(excelBytes));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
