package cn.iocoder.yudao.module.pms.controller.admin.iotsapstock;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotsapstock.vo.IotSapStockPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotsapstock.vo.IotSapStockRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotsapstock.vo.IotSapStockSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotsapstock.IotSapStockDO;
import cn.iocoder.yudao.module.pms.service.iotsapstock.IotSapStockService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_SAP_STOCK_NOT_EXISTS;

@Tag(name = "管理后台 - PMS SAP 库存(通用库存/项目部库存)")
@RestController
@RequestMapping("/pms/iot-sap-stock")
@Validated
public class IotSapStockController {

    @Resource
    private IotSapStockService iotSapStockService;

    @PostMapping("/create")
    @Operation(summary = "创建PMS SAP 库存(通用库存/项目部库存)")
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:create')")
    public CommonResult<Long> createIotSapStock(@Valid @RequestBody IotSapStockSaveReqVO createReqVO) {
        return success(iotSapStockService.createIotSapStock(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新PMS SAP 库存(通用库存/项目部库存)")
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:update')")
    public CommonResult<Boolean> updateIotSapStock(@Valid @RequestBody IotSapStockSaveReqVO updateReqVO) {
        iotSapStockService.updateIotSapStock(updateReqVO);
        return success(true);
    }

    @PostMapping("/batchSetSafetyStock")
    @Operation(summary = "批量设置安全库存")
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:update')")
    public CommonResult<Long> batchSetSafetyStock(@Valid @RequestBody List<IotSapStockSaveReqVO> sapStocks) {
        if (CollUtil.isEmpty(sapStocks)) {
            throw exception(IOT_SAP_STOCK_NOT_EXISTS);
        }
        return success(iotSapStockService.batchSetSafetyStock(sapStocks));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除PMS SAP 库存(通用库存/项目部库存)")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:delete')")
    public CommonResult<Boolean> deleteIotSapStock(@RequestParam("id") Long id) {
        iotSapStockService.deleteIotSapStock(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得PMS SAP 库存(通用库存/项目部库存)")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:query')")
    public CommonResult<IotSapStockRespVO> getIotSapStock(@RequestParam("id") Long id) {
        IotSapStockDO iotSapStock = iotSapStockService.getIotSapStock(id);
        return success(BeanUtils.toBean(iotSapStock, IotSapStockRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得PMS SAP 库存(通用库存/项目部库存)分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:query')")
    public CommonResult<PageResult<IotSapStockRespVO>> getIotSapStockPage(@Valid IotSapStockPageReqVO pageReqVO) {
        PageResult<IotSapStockDO> pageResult = iotSapStockService.getIotSapStockPage(pageReqVO);
        List<IotSapStockDO> sapStockList = iotSapStockService.getIotSapStockList(pageReqVO);
        // 计算符合查询条件的 库存总数量 库存总金额
        BigDecimal totalQuantity;
        BigDecimal totalAmount;
        if (CollUtil.isNotEmpty(sapStockList)) {
            totalQuantity = sapStockList.stream()
                    .map(IotSapStockDO::getQuantity)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            totalAmount = sapStockList.stream()
                    .filter(stock -> ObjUtil.isNotEmpty(stock.getQuantity()) && ObjUtil.isNotEmpty(stock.getUnitPrice()))
                    .map(stock -> stock.getQuantity().multiply(stock.getUnitPrice()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        } else {
            totalQuantity = BigDecimal.ZERO;
            totalAmount = BigDecimal.ZERO;
        }
        PageResult<IotSapStockRespVO> respPage = BeanUtils.toBean(pageResult, IotSapStockRespVO.class);
        if (CollUtil.isNotEmpty(respPage.getList())) {
            respPage.getList().forEach(record -> {
                record.setTotalAmount(totalAmount);
                record.setTotalQuantity(totalQuantity);
            });
        }
        return success(respPage);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出PMS SAP 库存(通用库存/项目部库存) Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-sap-stock:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotSapStockExcel(@Valid IotSapStockPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotSapStockDO> sapStocks = iotSapStockService.getIotSapStockPage(pageReqVO).getList();
        List<IotSapStockRespVO> sapStockResults = BeanUtils.toBean(sapStocks, IotSapStockRespVO.class);
        if (CollUtil.isNotEmpty(sapStockResults)) {
            sapStockResults.forEach(result -> {
                // 创建时间 格式化 yyyy-MM-dd
                if (ObjUtil.isNotEmpty(result.getCreateTime())) {
                    result.setCreateTimeStr(LocalDateTimeUtil.format(result.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
                }
            });
        }
        // 导出 Excel
        ExcelUtils.write(response, "SAP库存列表.xls", "SAP库存列表", IotSapStockRespVO.class,
                sapStockResults);
    }

}