package com.cf.imes.module.executor.controller.admin.manage.parts;

import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.excel.core.util.ExcelUtils;
import com.cf.imes.framework.operatelog.core.annotations.OperateLog;
import com.cf.imes.module.executor.controller.admin.manage.parts.vo.PartsCadPageReqVO;
import com.cf.imes.module.executor.controller.admin.manage.parts.vo.PartsImportExcelVO;
import com.cf.imes.module.executor.controller.admin.manage.parts.vo.PartsPageReqVO;
import com.cf.imes.module.executor.controller.admin.manage.parts.vo.PartsRespVO;
import com.cf.imes.module.executor.controller.admin.manage.parts.vo.PartsSaveReqVO;
import com.cf.imes.module.executor.dal.dataobject.orderParts.PartsDO;
import com.cf.imes.module.executor.service.manage.parts.PartsExcelListener;
import com.cf.imes.module.executor.service.manage.parts.PartsService;
import com.cf.imes.module.executor.util.file.ExcelReadUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.List;

import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.IMPORT;


@Tag(name = "管理后台 - 配件管理")
@RestController
@RequestMapping("/manage/parts/")
@Validated
public class PartsController {

    @Resource
    private PartsService partsService;

    final String IMPORT_TEMPLATE = "配件导入模板.xlsx";

    @PostMapping("/create")
    @Operation(summary = "创建配件")
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:create','base:accessory:create')")
    public CommonResult<Long> create(@Valid @RequestBody PartsSaveReqVO createReqVO) {
        return success(partsService.create(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新配件")
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:update','base:accessory:update')")
    public CommonResult<Boolean> update(@Valid @RequestBody PartsSaveReqVO updateReqVO) {
        partsService.update(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除配件")
    @Parameters({
            @Parameter(name = "id", description = "编号", required = true, example = "1024"),
            @Parameter(name = "organId", description = "板材所属组织ID", example = "1024")
    })
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:delete','base:accessory:delete')")
    public CommonResult<Boolean> delete(@RequestParam("id") Long id,
                                        @RequestParam(value = "organId",required = false, defaultValue = "0") Long organId) {
        partsService.delete(id, organId);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得配件")
    @Parameters({
            @Parameter(name = "id", description = "编号", required = true, example = "1024"),
            @Parameter(name = "organId", description = "板材所属组织ID", example = "1024")
    })
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:update','base:accessory:update')")
    public CommonResult<PartsRespVO> get(@RequestParam("id") Long id,
                                         @RequestParam(value = "organId", required = false, defaultValue = "0") Long organId) {
        PartsDO partsDO = partsService.get(id, organId);
        return success(BeanUtils.toBean(partsDO, PartsRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得配件分页")
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:query','base:accessory:query')")
    public CommonResult<PageResult<PartsRespVO>> getPage(@Valid PartsPageReqVO pageReqVO) {
        PageResult<PartsDO> pageResult = partsService.getPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PartsRespVO.class));
    }

    @GetMapping("/webcad/page")
    @Operation(summary = "获得配件分页")
    public CommonResult<PageResult<PartsRespVO>> webCadGetPage(@Valid PartsPageReqVO pageReqVO) {
        PageResult<PartsDO> pageResult = partsService.webCadGetPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PartsRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出配件文件")
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:export','base:accessory:export')")
    @OperateLog(type = EXPORT)
    public void exportExcel(@Valid PartsPageReqVO pageReqVO,
                            HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PartsDO> list = partsService.getPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "配件表.xls", "数据", PartsRespVO.class,
                BeanUtils.toBean(list, PartsRespVO.class));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入配件模板")
    @Parameter(name = "value", description = "文件类型", required = true, example = "0")
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:export-template','base:accessory:export-template')")
    public void importTemplate(HttpServletResponse response, @RequestParam("value") @NotEmpty(message = "文件路径不能为空") String value) {
        partsService.exportTemplate(response, value);
    }

    @PostMapping("/import")
    @Operation(summary = "导入配件")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新", example = "true"),
            @Parameter(name = "organId", description = "配件所属组织ID")
    })
    @OperateLog(type = IMPORT)
    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:import','base:accessory:import')")
    public void importExcel(@RequestParam("file") MultipartFile file,
                            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport,
                            @RequestParam(value = "organId", required = false, defaultValue = "0") Long organId,
                            HttpServletResponse response) throws Exception {

        ExcelReadUtil excelReadUtil = new ExcelReadUtil();
        PartsExcelListener listener = new PartsExcelListener();
        List<PartsImportExcelVO> list = excelReadUtil.read(file, PartsImportExcelVO.class, listener);

        if (!excelReadUtil.getFlag())
            ExcelUtils.write(response, IMPORT_TEMPLATE, "配件列表", PartsImportExcelVO.class, list);
        else {
            if (list.isEmpty()){
                PartsImportExcelVO partsImportExcelVO = PartsImportExcelVO.builder().result("导入失败，请保证导入文件中包含配件数据").build();
                list.add(partsImportExcelVO);
                ExcelUtils.write(response, IMPORT_TEMPLATE, "配件列表", PartsImportExcelVO.class, list);
            } else {
                partsService.importPartsList(list, updateSupport, organId);// 成功，批量导入
            }
        }
    }

    @GetMapping("/cad/page")
    @Operation(summary = "cad获得配件分页")
//    @PreAuthorize("@ss.hasAnyPermissions('system:accessory:query','base:accessory:query')")
    public CommonResult<PageResult<PartsRespVO>> getCadPage(@Valid PartsCadPageReqVO pageReqVO) {
        PageResult<PartsDO> pageResult = partsService.getCadPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PartsRespVO.class));
    }

    @GetMapping("/webcad/all")
    @Operation(summary = "获取全部配件信息")
    public CommonResult<List<PartsRespVO>> getPlateAll(@RequestParam("category") String category) {
        List<PartsDO> list = partsService.getPartAll(category);
        return success(BeanUtils.toBean(list, PartsRespVO.class));
    }
}
