package com.cf.imes.module.manage.controller.admin.plate;

import com.cf.imes.module.manage.controller.admin.plate.vo.plate.*;
import com.cf.imes.module.manage.service.plate.PlateExcelUtil;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.web.bind.annotation.*;
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 java.util.*;
import java.io.IOException;

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.manage.dal.dataobject.plate.PlateDO;
import com.cf.imes.module.manage.service.plate.PlateService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 板材信息表 plate")
@RestController
@RequestMapping("/manage/plate")
@Validated
public class PlateController {

    @Resource
    private PlateService plateService;

    @PostMapping("/create")
    @Operation(summary = "创建板材信息表 plate_{N}")
    @PreAuthorize("@ss.hasPermission('manage:plate:create')")
    public CommonResult<Long> createPlate(@Valid @RequestBody PlateSaveReqVO createReqVO) {
        return success(plateService.createPlate(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新板材信息表 plate_{N}")
    @PreAuthorize("@ss.hasPermission('manage:plate:update')")
    public CommonResult<Boolean> updatePlate(@Valid @RequestBody PlateSaveReqVO updateReqVO) {
        plateService.updatePlate(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除板材信息表 plate_{N}")
    @Parameters({
            @Parameter(name = "id", description = "编号", required = true),
            @Parameter(name = "organId", description = "板材所属组织ID")
    })
    @PreAuthorize("@ss.hasPermission('manage:plate:delete')")
    public CommonResult<Boolean> deletePlate(@RequestParam("id") Long id,
                                             @RequestParam(value = "organId",required = false) Long organId) {
        plateService.deletePlate(id,organId);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得板材信息表 plate_{N}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('manage:plate:query')")
    public CommonResult<PlateRespVO> getPlate(@RequestParam("id") Long id) {
        PlateDO plate = plateService.getPlate(id);
        return success(BeanUtils.toBean(plate, PlateRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得板材信息表 plate_{N}分页")
    @PreAuthorize("@ss.hasPermission('manage:plate:query')")
    public CommonResult<PageResult<PlateRespVO>> getPlatePage(@Valid PlatePageReqVO pageReqVO) {
        PageResult<PlateDO> pageResult = plateService.getPlatePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PlateRespVO.class));
    }

    @GetMapping("/export")
    @Operation(summary = "导出板材信息")
    @PreAuthorize("@ss.hasPermission('manage:plate:export')")
    @OperateLog(type = EXPORT)
    public void exportPlateExcel(@Valid PlatePageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PlateDO> list = plateService.getPlatePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "板材信息表 plate_{N}.xls", "数据", PlateRespVO.class,
                BeanUtils.toBean(list, PlateRespVO.class));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入用户模板")
    @PreAuthorize("@ss.hasPermission('manage:plate:export')")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<PlateImportExcelVO> list = Arrays.asList(
                PlateImportExcelVO.builder().goodsId("SP1123456").goodsName("xixih").material("颗粒板").width(String.valueOf(1212.3)).height(String.valueOf(12131.6))
                        .thickness(String.valueOf(0.2)).brand("鹅厂").spec("大厂").remark("测试").price(String.valueOf(33333.2)).color("黑色").texture("交换机1").build(),
                PlateImportExcelVO.builder().goodsId("SP1123457").goodsName("2L").material("yuanma@cf.com").width(String.valueOf(21.6)).height(String.valueOf(12231.6))
                        .thickness(String.valueOf(5.3)).brand("kkkkkk").spec("大厂").remark("测试").price(String.valueOf(333.555)).color("黑色").texture("交换机2").build()
        );
        // 输出
        ExcelUtils.write(response, "板材导入模板.xlsx", "板材列表", PlateImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入板材")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true"),
            @Parameter(name = "organId", description = "板材所属组织ID")
    })
    @PreAuthorize("@ss.hasPermission('manage:plate:import')")
    public void importExcel(@RequestParam("file") MultipartFile file,
                                                       @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport,
                                                       @RequestParam(value = "organId") Long organId,
                                                       HttpServletResponse response) throws Exception {
        PlateExcelUtil plateExcelUtil = new PlateExcelUtil();
        List<PlateImportExcelVO> list = plateExcelUtil.read(file, PlateImportExcelVO.class);
//        判断文件是否导入成功
        if (!plateExcelUtil.getFlag())
            ExcelUtils.write(response, "板材导入模板.xlsx", "板材列表", PlateImportExcelVO.class, list);
        else {
            PlateImportRespVO respVO = plateService.importPlateList(list, updateSupport, organId);// 成功，批量导入
        }

        plateExcelUtil.clear();
    }

}