package com.jojubanking.boot.module.system.controller.admin.order;

import com.jojubanking.boot.module.system.framework.tjfiles.TjfilesProperties;
import com.jojubanking.boot.module.system.util.xytj.DateDUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.*;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;

import com.jojubanking.boot.framework.common.pojo.PageResult;
import com.jojubanking.boot.framework.common.pojo.CommonResult;
import static com.jojubanking.boot.framework.common.pojo.CommonResult.success;

import com.jojubanking.boot.framework.excel.core.util.ExcelUtils;

import com.jojubanking.boot.framework.operatelog.core.annotations.OperateLog;
import static com.jojubanking.boot.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.jojubanking.boot.module.system.controller.admin.order.vo.*;
import com.jojubanking.boot.module.system.dal.dataobject.order.OrderDO;
import com.jojubanking.boot.module.system.convert.order.OrderConvert;
import com.jojubanking.boot.module.system.service.order.OrderService;

@Api(tags = "管理后台 - 检查项目订单")
@RestController
@RequestMapping("/system/order")
@Validated
public class OrderController {
    @Resource
    private TjfilesProperties tjfilesProperties;

    @Resource
    private OrderService orderService;

    @PostMapping("/create")
    @ApiOperation("创建检查项目订单")
    @PreAuthorize("@ss.hasPermission('system:order:create')")
    public CommonResult<Long> createOrder(@Valid @RequestBody OrderCreateReqVO createReqVO) {
        return success(orderService.createOrder(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新检查项目订单")
    @PreAuthorize("@ss.hasPermission('system:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderUpdateReqVO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除检查项目订单")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        orderService.deleteOrder(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得检查项目订单")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:order:query')")
    public CommonResult<OrderRespVO> getOrder(@RequestParam("id") Long id) {
        OrderDO order = orderService.getOrder(id);
        return success(OrderConvert.INSTANCE.convert(order));
    }

    @GetMapping("/list")
    @ApiOperation("获得检查项目订单列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('system:order:query')")
    public CommonResult<List<OrderRespVO>> getOrderList(@RequestParam("ids") Collection<Long> ids) {
        List<OrderDO> list = orderService.getOrderList(ids);
        return success(OrderConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得检查项目订单分页")
    @PreAuthorize("@ss.hasPermission('system:order:query')")
    public CommonResult<PageResult<OrderRespVO>> getOrderPage(@Valid OrderPageReqVO pageVO) {
        PageResult<OrderDO> pageResult = orderService.getOrderPage(pageVO);
        return success(OrderConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出检查项目订单 Excel")
    @PreAuthorize("@ss.hasPermission('system:order:export')")
    @OperateLog(type = EXPORT)
    public void exportOrderExcel(@Valid OrderExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<OrderDO> list = orderService.getOrderList(exportReqVO);

        // 导出 Excel
        List<OrderExcelVO> datas = OrderConvert.INSTANCE.convertList02(list);

        String tjpath = tjfilesProperties.getTjfilespath();
        String filename = tjpath + DateDUtil.getCurrentDateTime() + "检查项目订单";
        String srcFilePath = filename + ".xlsx";

        ExcelUtils.writeorder(response, srcFilePath, "数据", OrderExcelVO.class, datas);

        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");

        // 创建缓冲输入流
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFilePath));
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;

            // 读取并写入文件
            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }

    }

    @GetMapping("/listsum")
    @ApiOperation("获得检查项目订单分页")
    @PreAuthorize("@ss.hasPermission('system:order:query')")
    public CommonResult<List<OrderSumRespVO>> getOrderPage(@Valid OrderSumPageReqVO pageVO) {
        List<OrderSumRespVO> pageResult = new ArrayList<>();
        if(pageVO.getCreateTime() == null){
            pageResult = orderService.getOrderSumList(pageVO.getBatchno(), pageVO.getSchoolName(), pageVO.getClassName(),
                    pageVO.getItemname(), pageVO.getSex(), "", "");

        }else{
            pageResult = orderService.getOrderSumList(pageVO.getBatchno(), pageVO.getSchoolName(), pageVO.getClassName(),
                    pageVO.getItemname(), pageVO.getSex(), pageVO.getCreateTime()[0], pageVO.getCreateTime()[1]);
        }
        for(int i=0; i<pageResult.size();i++){
            if(StringUtils.isEmpty(pageVO.getBatchno())){
                pageResult.get(i).setBatchno("全部");
            }
            if(StringUtils.isEmpty(pageVO.getSchoolName())){
                pageResult.get(i).setSchoolName("全部");
            }
            if(StringUtils.isEmpty(pageVO.getClassName())){
                pageResult.get(i).setClassName("全部");
            }
            if(pageVO.getSex() == null){
                pageResult.get(i).setSex(3);
            }
        }
        return success(pageResult);
    }

    @GetMapping("/export-excel-sum")
    @ApiOperation("导出检查项目订单 Excel")
    @PreAuthorize("@ss.hasPermission('system:order:export')")
    @OperateLog(type = EXPORT)
    public void exportOrderExcelSum(@Valid OrderSumPageReqVO pageVO,
                                 HttpServletResponse response) throws IOException {

        List<OrderSumRespVO> pageResult = new ArrayList<>();
        if(pageVO.getCreateTime() == null){
            pageResult = orderService.getOrderSumList(pageVO.getBatchno(), pageVO.getSchoolName(), pageVO.getClassName(),
                    pageVO.getItemname(), pageVO.getSex(), "", "");

        }else{
            pageResult = orderService.getOrderSumList(pageVO.getBatchno(), pageVO.getSchoolName(), pageVO.getClassName(),
                    pageVO.getItemname(), pageVO.getSex(), pageVO.getCreateTime()[0], pageVO.getCreateTime()[1]);
        }

        for(int i=0; i<pageResult.size();i++){
            if(StringUtils.isEmpty(pageVO.getBatchno())){
                pageResult.get(i).setBatchno("全部");
            }
            if(StringUtils.isEmpty(pageVO.getSchoolName())){
                pageResult.get(i).setSchoolName("全部");
            }
            if(StringUtils.isEmpty(pageVO.getClassName())){
                pageResult.get(i).setClassName("全部");
            }
            if(pageVO.getSex() == null){
                pageResult.get(i).setSex(3);
            }
        }

        // 导出 Excel
        String tjpath = tjfilesProperties.getTjfilespath();
        String filename = tjpath + DateDUtil.getCurrentDateTime() + "检查项目统计";
        String srcFilePath = filename + ".xlsx";

        List<OrderSumExcelVO> datas = OrderConvert.INSTANCE.convertList03(pageResult);
        ExcelUtils.writeorder(response, srcFilePath, "数据", OrderSumExcelVO.class, datas);

        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");

        // 创建缓冲输入流
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFilePath));
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;

            // 读取并写入文件
            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }

    }

}
