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

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.iotlockstock.vo.IotLockStockPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotlockstock.vo.IotLockStockRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotlockstock.vo.IotLockStockSaveReqVO;
import cn.iocoder.yudao.module.pms.convert.iotlockstock.IotLockStockConvert;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotlockstock.IotLockStockDO;
import cn.iocoder.yudao.module.pms.service.iotlockstock.IotLockStockService;
import cn.iocoder.yudao.module.system.api.saporg.SapOrgApi;
import cn.iocoder.yudao.module.system.api.saporg.dto.SapOrgRespDTO;
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.Map;
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.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_LOCK_STOCK_NOT_EXISTS;

@Tag(name = "管理后台 - PMS 本地 库存")
@RestController
@RequestMapping("/pms/iot-lock-stock")
@Validated
public class IotLockStockController {

    @Resource
    private IotLockStockService iotLockStockService;
    @Resource
    private SapOrgApi sapOrgApi;

    @PostMapping("/create")
    @Operation(summary = "创建PMS 本地 库存")
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:create')")
    public CommonResult<Long> createIotLockStock(@Valid @RequestBody IotLockStockSaveReqVO createReqVO) {
        return success(iotLockStockService.createIotLockStock(createReqVO));
    }

    @PostMapping("/manualWarehouse")
    @Operation(summary = "手动新增入库")
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:create')")
    public CommonResult<Long> manualWarehouse(@Valid @RequestBody List<IotLockStockSaveReqVO> reqVO) {
        if (CollUtil.isEmpty(reqVO)) {
            throw exception(IOT_LOCK_STOCK_NOT_EXISTS);
        }
        return success(iotLockStockService.manualWarehouse(reqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新PMS 本地 库存")
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:update')")
    public CommonResult<Boolean> updateIotLockStock(@Valid @RequestBody IotLockStockSaveReqVO updateReqVO) {
        iotLockStockService.updateIotLockStock(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除PMS 本地 库存")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:delete')")
    public CommonResult<Boolean> deleteIotLockStock(@RequestParam("id") Long id) {
        iotLockStockService.deleteIotLockStock(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得PMS 本地 库存")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:query')")
    public CommonResult<IotLockStockRespVO> getIotLockStock(@RequestParam("id") Long id) {
        IotLockStockDO iotLockStock = iotLockStockService.getIotLockStock(id);
        // 组装 工厂 成本中心名称
        SapOrgRespDTO factoryRespDTO = sapOrgApi.getSapOrg(iotLockStock.getFactoryId());
        SapOrgRespDTO costCenterRespDTO = sapOrgApi.getSapOrg(iotLockStock.getCostCenterId());
        iotLockStock.setFactory(factoryRespDTO.getFactoryName());
        iotLockStock.setCostCenter(costCenterRespDTO.getCostCenterName());
        return success(BeanUtils.toBean(iotLockStock, IotLockStockRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得PMS 本地 库存分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:query')")
    public CommonResult<PageResult<IotLockStockRespVO>> getIotLockStockPage(@Valid IotLockStockPageReqVO pageReqVO) {
        PageResult<IotLockStockDO> pageResult = iotLockStockService.getIotLockStockPage(pageReqVO);
        List<IotLockStockDO> lockStockList = iotLockStockService.getIotLockStocks(pageReqVO);
        // 计算符合查询条件的 库存总数量 库存总金额
        BigDecimal totalQuantity;
        BigDecimal totalAmount;
        if (CollUtil.isNotEmpty(lockStockList)) {
            totalQuantity = lockStockList.stream()
                    .map(IotLockStockDO::getQuantity)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            totalAmount = lockStockList.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;
        }
        // 拼接 工厂 成本中心 库存地点
        Map<Long, SapOrgRespDTO> factoryMap = sapOrgApi.getSapOrgMap(
                convertList(pageResult.getList(), IotLockStockDO::getFactoryId));
        Map<Long, SapOrgRespDTO> costCenterMap = sapOrgApi.getSapOrgMap(
                convertList(pageResult.getList(), IotLockStockDO::getCostCenterId));
        return success(new PageResult<>(IotLockStockConvert.INSTANCE.convertList(pageResult.getList(), factoryMap, costCenterMap, totalQuantity, totalAmount),
                pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出PMS 本地 库存 列表 Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-lock-stock:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotLockStockExcel(@Valid IotLockStockPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotLockStockDO> lockStocks = iotLockStockService.getIotLockStockPage(pageReqVO).getList();

        // 拼接 工厂 成本中心 库存地点
        Map<Long, SapOrgRespDTO> factoryMap = sapOrgApi.getSapOrgMap(
                convertList(lockStocks, IotLockStockDO::getFactoryId));
        Map<Long, SapOrgRespDTO> costCenterMap = sapOrgApi.getSapOrgMap(
                convertList(lockStocks, IotLockStockDO::getCostCenterId));
        BigDecimal totalQuantity = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<IotLockStockRespVO> lockStockResults = IotLockStockConvert.INSTANCE.convertList(lockStocks, factoryMap, costCenterMap, totalQuantity, totalAmount);
        if (CollUtil.isNotEmpty(lockStockResults)) {
            lockStockResults.forEach(result -> {
                if (ObjUtil.isNotEmpty(result.getStorageTime())) {
                    // 创建时间 格式化 yyyy-MM-dd
                    result.setStorageTimeStr(LocalDateTimeUtil.format(result.getStorageTime(), DatePattern.NORM_DATETIME_PATTERN));
                }
            });
        }
        // 导出 Excel
        ExcelUtils.write(response, "本地库存列表.xls", "本地库存列表", IotLockStockRespVO.class,
                lockStockResults);
    }

}