package com.ruoyi.oa.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.oa.domain.SysOaWarehouseMaster;
import com.ruoyi.oa.domain.bo.SysOaWarehouseDetailBo;
import com.ruoyi.oa.domain.bo.SysOaWarehouseMasterBo;
import com.ruoyi.oa.domain.dto.MonthlyStatsDTO;
import com.ruoyi.oa.domain.dto.SummaryFilterDTO;
import com.ruoyi.oa.domain.vo.SummaryCardVo;
import com.ruoyi.oa.listener.SysOaWarehouseListener;
import com.ruoyi.oa.service.ISysOaWarehouseMasterService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.oa.domain.vo.SysOaWarehouseVo;
import com.ruoyi.oa.domain.bo.SysOaWarehouseBo;
import com.ruoyi.oa.service.ISysOaWarehouseService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 仓库管理
 *
 * @author liuzongkun999
 * @date 2024-11-02
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oa/oaWarehouse")
public class SysOaWarehouseController extends BaseController {

    private final ISysOaWarehouseService iSysOaWarehouseService;

    private final ISysOaWarehouseMasterService iSysOaWarehouseMasterService;

    /**
     * 查询仓库管理列表
     */
    @GetMapping("/list")
    public TableDataInfo<SysOaWarehouseVo> list(SysOaWarehouseBo bo, PageQuery pageQuery) {
        return iSysOaWarehouseService.queryPageList(bo, pageQuery);
    }

       /**
     * 查询仓库管理列表
     */
    @GetMapping("/listThreshold")
    public TableDataInfo<SysOaWarehouseVo> listThreshold(SysOaWarehouseBo bo, PageQuery pageQuery) {
        return iSysOaWarehouseService.queryPageListThreshold(bo, pageQuery,true);
    }


       /**
     * 查询仓库管理列表
     */
    @GetMapping("/listNotThreshold")
    public TableDataInfo<SysOaWarehouseVo> listNotThreshold(SysOaWarehouseBo bo, PageQuery pageQuery) {
        return iSysOaWarehouseService.queryPageListThreshold(bo, pageQuery,false);
    }


    /**
     * 通过一个name查询多个字段
     */
    @GetMapping("/listByMultiQuery")
    public TableDataInfo<SysOaWarehouseVo> listByMultiQuery(SysOaWarehouseBo bo, PageQuery pageQuery) {
        return iSysOaWarehouseService.listByMultiQuery(bo, pageQuery);
    }


    /**
     * 导出仓库管理列表
     */
    @Log(title = "仓库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysOaWarehouseBo bo, HttpServletResponse response) {
        List<SysOaWarehouseVo> list = iSysOaWarehouseService.queryList(bo);
        ExcelUtil.exportExcel(list, "仓库管理", SysOaWarehouseVo.class, response);
    }

    /**
     * 获取仓库管理详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<SysOaWarehouseVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iSysOaWarehouseService.queryById(id));
    }

    /**
     * 新增仓库管理
     */
    @Log(title = "仓库管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysOaWarehouseBo bo) {
        return toAjax(iSysOaWarehouseService.insertByBo(bo)>0);
    }



    /**
     * 修改仓库管理
     */
    @Log(title = "仓库管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysOaWarehouseBo bo) {
        return toAjax(iSysOaWarehouseService.updateByBo(bo));

    }

    /**
     * 删除仓库管理
     *
     * @param ids 主键串
     */
    @Log(title = "仓库管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iSysOaWarehouseService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    /**
     * 新增仓库管理
     */
    @Log(title = "仓库管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/insert")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody List<SysOaWarehouseBo> boList) {
        return toAjax(iSysOaWarehouseService.insertBatch(boList));
    }


    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "入库工单导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<SysOaWarehouseVo> result = ExcelUtil.importExcel(file.getInputStream(), SysOaWarehouseVo.class,
                new SysOaWarehouseListener(true));
        SysOaWarehouseMasterBo sysOaWarehouseMaster = new SysOaWarehouseMasterBo();
        sysOaWarehouseMaster.setType(1L);
        List<SysOaWarehouseDetailBo> list = new ArrayList<>();
        result.getList().forEach(item -> {
            SysOaWarehouseDetailBo bo = new SysOaWarehouseDetailBo();
            bo.setWarehouseId(item.getId());
            bo.setAmount(item.getInventory());
            bo.setSignPrice(item.getPrice());
            list.add(bo);
        });
        sysOaWarehouseMaster.setWarehouseList(list);
        sysOaWarehouseMaster.setMasterNum(UUID.randomUUID().toString());
        iSysOaWarehouseMasterService.insertByBo(sysOaWarehouseMaster);
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "投诉工单", SysOaWarehouseVo.class, response);
    }

    @GetMapping("/recent")
    public R<List<SysOaWarehouseVo>> selectRecentOutbound(@RequestParam(name = "limit", defaultValue = "10") int limit){
        return R.ok(iSysOaWarehouseService.selectRecentOutbound(limit));
    }

    @GetMapping("/cards")
    public R<List<SummaryCardVo>> summaryCards(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            LocalDateTime beginTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            LocalDateTime endTime,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String brand,
            @RequestParam(required = false) String supplier
    ) {
        SummaryFilterDTO filter = new SummaryFilterDTO();
        filter.setBeginTime(beginTime);
        filter.setEndTime(endTime);
        filter.setName(name);
        filter.setBrand(brand);
        filter.setSupplier(supplier);
        return R.ok(iSysOaWarehouseService.getSummaryCards(filter));
    }


    /**
     * 获取某年 1–12 月的入库/出库/库存快照数据
     * @param month 可选参数，格式 yyyy-MM-dd；只读取其年份
     */
    @GetMapping("/monthly")
    public R<MonthlyStatsDTO> monthly( @RequestParam(required = false) String month ) {
        return R.ok(iSysOaWarehouseService.getMonthlyStats(month));
    }
}
