package com.zbf.web.controller.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbf.common.core.controller.ManualPagination;
import com.zbf.system.domain.RfidQuantityUpdateRequest;
import com.zbf.system.domain.RfidQueryRequest;
import com.zbf.system.service.ITBaseStorageService;
import com.zbf.web.controller.section.EnhanceDataList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zbf.common.annotation.Log;
import com.zbf.common.core.controller.BaseController;
import com.zbf.common.core.domain.AjaxResult;
import com.zbf.common.core.page.TableDataInfo;
import com.zbf.common.enums.BusinessType;
import com.zbf.common.utils.StringUtils;
import com.zbf.common.utils.poi.ExcelUtil;
import com.zbf.system.domain.TMiStock;
import com.zbf.system.domain.TMiStockUpdate;
import com.zbf.system.service.ITMiStockService;
import com.zbf.system.service.ITOverdueService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;


/**
 * 库存Controller
 *
 * @author tony
 * @date 2024-06-12
 */
@RestController
@RequestMapping("/system/stock")
@Api(value = "库存控制器", tags = {"库存管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TMiStockController extends BaseController {

    private final ITMiStockService tMiStockService;

    private final ITOverdueService overdueService;

    private final ITBaseStorageService storageService;

    /**
     * 查询库存列表
     */
    @ApiOperation("查询库存列表")
    @PreAuthorize("@ss.hasPermi('system:stock:list')")
    @GetMapping("/list")
    @EnhanceDataList(entityType = TMiStock.class)
    public TableDataInfo list(TMiStock tMiStock) {
        startPage();
        tMiStock.setDeptId(getDeptId());
        if (tMiStock.getDate()!=null){
            String[] date = tMiStock.getDate();
            tMiStock.setStartTime(date[0]);
            tMiStock.setEndTime(date[1]);
        }
        List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
        return getDataTable(list);
    }

    @GetMapping("/lists")
    @EnhanceDataList(entityType = TMiStock.class)
    public AjaxResult lists(TMiStock tMiStock) {
        if (tMiStock.getDate()!=null){
            String[] date = tMiStock.getDate();
            tMiStock.setStartTime(date[0]);
            tMiStock.setEndTime(date[1]);
        }
        List<TMiStock> list = tMiStockService.select(tMiStock);
        return AjaxResult.success(list);
    }

    /**
     * 导出库存列表
     */
    @ApiOperation("导出库存列表")
    @PreAuthorize("@ss.hasPermi('system:stock:export')")
    @Log(title = "库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TMiStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        if (tMiStock.getDate()!=null){
            tMiStock.setStartTime(tMiStock.getDate()[0]);
            tMiStock.setEndTime(tMiStock.getDate()[1]);
        }
        List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
        ExcelUtil<TMiStock> util = new ExcelUtil<TMiStock>(TMiStock.class);
        util.exportExcel(response, list, "库存数据");
    }

    /**
     * 获取库存详细信息
     */
    @ApiOperation("获取库存详细信息")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping(value = "/{stockId}")
    public AjaxResult getInfo(@PathVariable("stockId") String stockId) {
        return success(tMiStockService.getById(stockId));
    }

    /**
     * 根据条件查询库存总数
     */
    @ApiOperation("获取库存总数")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping(value = "/queryTotal")
    public AjaxResult getTotal(TMiStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        return success(tMiStockService.getTotal(tMiStock));
    }

    @ApiOperation("统计查询库存列表")
    @PreAuthorize("@ss.hasPermi('system:stock:list')")
    @GetMapping("/countList")
    public TableDataInfo countList(TMiStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        List<TMiStock> list = tMiStockService.selectCountStockList(tMiStock);
        return ManualPagination.pagination(list);
    }


    /**
     * 新增库存
     */
    @ApiOperation("新增库存")
    @PreAuthorize("@ss.hasPermi('system:stock:add')")
    @Log(title = "库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMiStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        return toAjax(tMiStockService.save(tMiStock));
    }

    /**
     * 修改库存
     */
    @ApiOperation("修改库存")
    @PreAuthorize("@ss.hasPermi('system:stock:edit')")
    @Log(title = "库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TMiStock tMiStock) {
        return toAjax(tMiStockService.updateById(tMiStock));
    }

    /**
     * 删除库存
     */
    @ApiOperation("删除库存")
    @PreAuthorize("@ss.hasPermi('system:stock:remove')")
    @Log(title = "库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{stockIds}")
    public AjaxResult remove(@PathVariable String[] stockIds) {
        return toAjax(tMiStockService.removeByIds(Arrays.asList(stockIds)));
    }


    /**
     * 冻结库存操作
     *
     * @param  库存ID数组
     * @return 返回操作结果
     */
    @GetMapping("/frozen")
    public AjaxResult frozen(@RequestParam(name = "stockIds", required = true) String stockIdsStr,
                             @RequestParam(name = "value", required = true) String value) {
        // 将逗号分隔的字符串转换为ID列表
        List<String> ids = Arrays.asList(stockIdsStr.split(","));

        // 调用服务层方法进行处理
        boolean success = tMiStockService.freezeStockByIds(ids, value);

        // 根据操作结果返回相应的AjaxResult
        return success ? AjaxResult.success("库存已成功冻结。") : AjaxResult.error("库存冻结失败。");
    }

    /**
     * 解冻
     *
     * @param stockIds
     * @return
     */
    @GetMapping("/thaw/{stockIds}")
    public AjaxResult thaw(@PathVariable String[] stockIds) {
        // 将数组转换为列表
        List<String> ids = Arrays.asList(stockIds);
        // 调用服务层方法进行处理
        boolean success = tMiStockService.thawStockByIds(ids);
        // 根据操作结果返回相应的AjaxResult
        return success ? AjaxResult.success("库存已成功解冻。") : AjaxResult.error("库存解冻失败。");
    }

    @ApiOperation("查询超期呆滞列表")
    @PreAuthorize("@ss.hasPermi('system:stock:overdue')")
    @GetMapping("/overdueByParam")
    public TableDataInfo overdueListByParam(TMiStock tMiStock) {
        //超期呆滞天数
        String overdueDate = overdueService.getOverdueFromToday();
        if (StringUtils.isNotEmpty(overdueDate)) {
            tMiStock.setOverdueDate(overdueDate);
            startPage();
            List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }

    @ApiOperation("查询超期呆滞列表")
    @PreAuthorize("@ss.hasPermi('system:stock:overdue')")
    @GetMapping("/overdue")
    public TableDataInfo overdueList(TMiStock tMiStock) {
        //超期呆滞
        tMiStock.setFlag("1");
        startPage();
        List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
        return getDataTable(list);
    }


    @ApiOperation("查询超期呆滞列表")
    @PreAuthorize("@ss.hasPermi('system:stock:overdue')")
    @GetMapping("/overInsured")
    public TableDataInfo overInsured(TMiStock tMiStock) {
        startPage();
        List<TMiStock> list =  tMiStockService.overInsured(tMiStock);
        return getDataTable(list);
    }

    /**
     * 手持库存查询
     */
    @ApiOperation("库存信息查询")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping("/goodsStatistics")
    public AjaxResult goodsStatistics(TMiStock tMiStock) {
        return success(tMiStockService.inventoryStatisticsGoods(tMiStock));
    }

    /**
     * 手持盘点库存查询
     */
    @ApiOperation("手持盘点库存信息查询")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping("/pdaPanGoodsList")
    public AjaxResult pdaPanGoodsList(TMiStock tMiStock) {
        return success(tMiStockService.selectPanGoodsList(tMiStock));
    }

    /**
     * 手持盘点当日变化库位查询
     */
    @ApiOperation("手持盘点当日库位信息查询")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping("/dayLocation")
    public AjaxResult dayLocation() {
        return success(tMiStockService.selectPanTimeLocation());
    }

    /**
     * 手持移位
     */
    @ApiOperation("手持移位")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @PostMapping("/reLocation")
    public AjaxResult reLocation(@RequestBody TMiStockUpdate tMiStockUpdate) {
        return success(tMiStockService.changeLocation(tMiStockUpdate));
    }

    @ApiOperation("查询物料")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @PostMapping("/getStock")
    public AjaxResult getStock(@RequestBody TMiStockUpdate tMiStockUpdate) {
        TMiStock tMiStock = new TMiStock();
        tMiStock.setLocationId(tMiStockUpdate.getFromLoc());
        List<TMiStock> list = tMiStockService.list(new LambdaQueryWrapper<>(tMiStock).eq(TMiStock::getLocationId, tMiStockUpdate.getFromLoc()));
        return AjaxResult.success(list);
    }

    /**
     * 手持更换容器 托盘物料查询
     */
    @ApiOperation("手持更换容器 托盘物料查询")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping("/getCtlNoGoods")
    public AjaxResult getCtlNoGoods(TMiStock tMiStock) {
        return success(tMiStockService.selectTMiStockListByCtl(tMiStock));
    }

    /**
     * 手持更换容器
     */
    @ApiOperation("手持更换容器")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @PostMapping("/changeCtlNo")
    public AjaxResult changeCtlNo(@RequestBody TMiStockUpdate tMiStockUpdate) {
        return success(tMiStockService.changeCtlNo(tMiStockUpdate));
    }

    /**
     * 手持拆分,合并容器
     */
    @ApiOperation("手持拆分合并容器")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @PostMapping("/splitCtlNo")
    public AjaxResult splitCtlNo(@RequestBody TMiStockUpdate tMiStockUpdate) {
        return success(tMiStockService.splitCtlNo(tMiStockUpdate));
    }

    @PostMapping("/queryByRfid")
    public AjaxResult queryByRfid(@RequestBody RfidQueryRequest request) {

            return AjaxResult.success(tMiStockService.rfid(request));
    }

    /**
     * 更新RFID数量
     */
    @ApiOperation("更新RFID数量")
    @PreAuthorize("@ss.hasPermi('system:stock:edit')")
    @Log(title = "RFID数量更新", businessType = BusinessType.UPDATE)
    @PostMapping("/updateRfidQuantity")
    public AjaxResult updateRfidQuantity(@Validated @RequestBody RfidQuantityUpdateRequest request) {
        try {
            return AjaxResult.success(tMiStockService.updateRfidQuantity(request));
        } catch (Exception e) {
            logger.error("RFID数量更新失败", e);
            return AjaxResult.error("RFID数量更新失败: " + e.getMessage());
        }
    }
}
