package cn.iocoder.yudao.module.project.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.conf.entity.BaseType;
import cn.iocoder.yudao.module.conf.entity.BaseWarehouse;
import cn.iocoder.yudao.module.conf.service.BaseTypeService;
import cn.iocoder.yudao.module.conf.service.BaseWarehouseService;
import cn.iocoder.yudao.module.project.entity.RepairWares;
import cn.iocoder.yudao.module.project.service.RepairWaresService;
import cn.iocoder.yudao.module.project.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 配件库")
@RestController
@RequestMapping("/repair/wares")
@Validated
public class RepairWaresController {

    @Resource
    private RepairWaresService waresService;

    @Resource
    @Lazy
    private BaseWarehouseService warehouseService;

    @Resource
    @Lazy
    private BaseTypeService typeService;

    /**
     * 创建配件库
     *
     * @param createReqVO RepairWaresSaveReqVO实体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.String>
     * @author PQZ
     * @date 11:20 2024/9/14
     **/
    @PostMapping("/create")
    @Operation(summary = "创建配件库")
//    @PreAuthorize("@ss.hasPermission('repair:wares:create')")
    public CommonResult<RepairWares> createWares(@Valid @RequestBody RepairWaresSaveReqVO createReqVO) {
        return success(waresService.saveWares(createReqVO));
    }

    /**
     * 更新配件库
     *
     * @param updateReqVO RepairWaresSaveReqVO实体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 11:21 2024/9/14
     **/
    @PutMapping("/update")
    @Operation(summary = "更新配件库")
//    @PreAuthorize("@ss.hasPermission('repair:wares:update')")
    public CommonResult<Boolean> updateWares(@Valid @RequestBody RepairWaresSaveReqVO updateReqVO) {
        waresService.saveWares(updateReqVO);
        return success(true);
    }

    /**
     * 删除配件库
     *
     * @param id 产品id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 11:21 2024/9/14
     **/
    @DeleteMapping("/delete")
    @Operation(summary = "删除配件库")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('repair:wares:delete')")
    public CommonResult<Boolean> deleteWares(@RequestParam("id") String id) {
        waresService.deleteWares(id);
        return success(true);
    }

    /**
     * 获得配件库
     *
     * @param id 产品id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<cn.iocoder.yudao.module.project.vo.RepairWaresRespVO>
     * @author PQZ
     * @date 11:21 2024/9/14
     **/
    @GetMapping("/get")
    @Operation(summary = "获得配件库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('repair:wares:query')")
    public CommonResult<RepairWaresRespVO> getWares(@RequestParam("id") String id) {
        return success(waresService.getWares(id));
    }

    /**
     * 获得配件库分页
     *
     * @param pageReqVO RepairWaresPageReqVO 实体
     * @param pageNo    分页参数
     * @param pageSize  分页参数
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage < ?>>
     * @author PQZ
     * @date 11:30 2024/9/14
     **/
    @GetMapping("/page")
    @Operation(summary = "获得配件库分页")
//    @PreAuthorize("@ss.hasPermission('repair:wares:query')")
    public CommonResult<IPage<?>> getWaresPage(RepairWaresPageReqVO pageReqVO,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<RepairWaresRespVO> page = new Page<>(pageNo, pageSize);
        return success(waresService.getWaresPage(pageReqVO, page));
    }

    /**
     * 根据名称获取最新的数据
     *
     * @author 小李
     * @date 18:03 2024/9/25
    **/
    @GetMapping("/getByName")
    @Operation(summary = "根据名称获取最新的数据")
    public CommonResult<?> getWaresByName(@RequestParam("name") String name) {
        return success(waresService.getWaresByName(name));
    }

    /**
     * 查询所有有配件的分类
     * @author vinjor-M
     * @date 10:51 2024/10/22
    **/
    @GetMapping("/getAllTypeList")
    @Operation(summary = "查询所有有配件的分类")
    public CommonResult<?> getAllTypeList() {
        return success(waresService.getAllTypeList());
    }

    /**
     * 下载配件导入模板
     *
     * @author 小李
     * @date 15:35 2024/11/29
    **/
    @GetMapping("/get-import-template")
    @Operation(summary = "下载配件导入模板")
    public void getImportTemplate(HttpServletResponse response) throws Exception {
        List<RepairWaresExcelVO> list = Collections.singletonList(
                RepairWaresExcelVO
                        .builder()
                        .barCode("123")
                        .code("123")
                        .name("模板数据")
                        .model("123")
                        .price(new BigDecimal("100"))
                        .purPrice(new BigDecimal("100"))
                        .type("模板分类")
                        .unit("01")
                        .warehouse("模板仓库")
                        .miniStock(new BigDecimal("0"))
                        .maxStock(new BigDecimal("10"))
                        .stock(new BigDecimal("5"))
//                        .attribute("yc")
                        .carModel("模板车型")
//                        .dataForm("bd")
                        .remark("模板")
                        .build()
        );
        ExcelUtils.write(response, "配件导入模板.xls", "配件信息", RepairWaresExcelVO.class, list);
    }

    /**
     * 导入配件数据
     *
     * @author 小李
     * @date 16:20 2024/11/29
     * @param file Excel 文件
     * @param updateSupport 是否支持更新
    **/
    @PostMapping("/import-data")
    @Operation(summary = "导入配件数据")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    public CommonResult<ImportExcelRespVO> importData(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception{
        List<RepairWaresExcelVO> list = ExcelUtils.read(file, RepairWaresExcelVO.class);
        return success(waresService.importData(list, updateSupport));
    }

    /**
     * 导出数据
     *
     * @author 小李
     * @date 17:20 2024/12/2
     * @param pageReqVO 请求对象
    **/
    @GetMapping("/export")
    @Operation(summary = "导出数据")
    public void exportData(RepairWaresPageReqVO pageReqVO, HttpServletResponse response)throws IOException {
        int pageNo = 1, pageSize = 1000;
        List<RepairWaresExcelVO> list = new ArrayList<>();
        Page<RepairWaresRespVO> page = new Page<>(pageNo, pageSize);
        do {
            IPage<RepairWaresRespVO> waresPage = waresService.getWaresPage(pageReqVO, page);
            List<RepairWaresRespVO> records = waresPage.getRecords();
            
            if (CollUtil.isEmpty(records)){
                break;
            }

            List<RepairWaresExcelVO> convertedRecords = records.stream().map(item -> BeanUtils.toBean(item, RepairWaresExcelVO.class)).collect(Collectors.toList());
            list.addAll(convertedRecords);

            pageNo++;
            page.setCurrent(pageNo);
        }while (true);

        if (CollUtil.isEmpty(list)){
            throw exception0(500, "没有数据可以导出");
        }

        List<BaseWarehouse> warehouses = warehouseService.list();
        Map<String, String> warehousesMap = warehouses.stream().collect(Collectors.toMap(BaseWarehouse::getId, BaseWarehouse::getName));

        List<BaseType> types = typeService.list(new LambdaQueryWrapper<BaseType>().eq(BaseType::getType, "02"));
        Map<String, String> typesMap = types.stream().collect(Collectors.toMap(BaseType::getId, BaseType::getName));

        list.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getWarehouse()) && ObjectUtil.isNotEmpty(warehousesMap.get(item.getWarehouse()))){
                item.setWarehouse(warehousesMap.get(item.getWarehouse()));
            }
            if (ObjectUtil.isNotEmpty(item.getType()) && ObjectUtil.isNotEmpty(typesMap.get(item.getType()))){
                item.setType(typesMap.get(item.getType()));
            }
        });

        ExcelUtils.write(response, "维修配件数据.xls", "数据", RepairWaresExcelVO.class, list);
    }
}