package com.cf.imes.module.executor.controller.admin.order;

import com.cf.imes.module.executor.controller.admin.order.vo.order.*;
import com.cf.imes.module.executor.util.OrderExcelUtil;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
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.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.object.BeanUtils;

import static com.cf.imes.framework.common.pojo.CommonResult.success;

import com.cf.imes.framework.excel.core.util.ExcelUtils;

import com.cf.imes.framework.operatelog.core.annotations.OperateLog;

import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.cf.imes.module.executor.dal.dataobject.order.OrderDO;
import com.cf.imes.module.executor.service.order.OrderService;


import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Tag(name = "管理后台 - 生产单表 order_{N}")
@RestController
@RequestMapping("/executor/order")
@Validated
public class OrderController {

    @Resource
    private OrderService orderService;

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @PostMapping("/create")
    @Operation(summary = "创建生产单表 order_{N}")
    @PreAuthorize("@ss.hasPermission('executor:order:create')")
    public CommonResult<Long> createOrder(@Valid @RequestBody OrderSaveReqVO createReqVO) {
        return success(orderService.createOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产单表 order_{N}")
    @PreAuthorize("@ss.hasPermission('executor:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderSaveReqVO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产单表 order_{N}")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('executor:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        orderService.deleteOrder(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产单表 order_{N}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('executor:order:query')")
    public CommonResult<OrderRespVO> getOrder(@RequestParam("id") Long id) {
        OrderDO order = orderService.getOrder(id);
        return success(BeanUtils.toBean(order, OrderRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产单表 order_{N}分页")
    @PreAuthorize("@ss.hasPermission('executor:order:query')")
    public CommonResult<PageResult<OrderRespVO>> getOrderPage(@Valid OrderPageReqVO pageReqVO) {
        PageResult<OrderDO> pageResult = orderService.getOrderPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, OrderRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产单表 order_{N} Excel")
    @PreAuthorize("@ss.hasPermission('executor:order:export')")
    @OperateLog(type = EXPORT)
    public void exportOrderExcel(@Valid OrderPageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<OrderDO> list = orderService.getOrderPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "生产单表 order_{N}.xls", "数据", OrderRespVO.class,
                BeanUtils.toBean(list, OrderRespVO.class));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入生产单模板")
    public void importTemplate(HttpServletResponse response) {
        try {
            // path是指想要下载的文件的路径
            File file = new File(ResourceUtils.getURL("classpath:").getPath() + "\\files\\生产单上传样式.xlsx");
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @PostMapping("/import")
    @Operation(summary = "导入生产单")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true"),
            @Parameter(name = "upload", description = "是否上传表头、表体(1,只上传表头；2，包含板材信息", required = true)
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public void importExcel(@RequestParam("file") MultipartFile file,
                            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport,
                            @RequestParam(value = "upload") int upload,
                            @Valid @RequestBody OrderSaveReqVO createReqVO) throws Exception {
        success(orderService.createOrder(createReqVO));
//        有板材，返回包含金额，出现错误进行上传
        if (upload == 2) {
//            BigDecimal money = orderService.importOrderList(file, updateSupport , updateSupport);
        }

        return;
    }

}