package com.zbf.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbf.common.annotation.Log;
import com.zbf.common.core.controller.BaseController;
import com.zbf.common.core.controller.ManualPagination;
import com.zbf.common.core.domain.AjaxResult;
import com.zbf.common.core.domain.model.LoginUser;
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.TCkOrderdetail;
import com.zbf.system.domain.TMiStock;
import com.zbf.system.domain.TMiStockUpdate;
import com.zbf.system.domain.TMiXnStock;
import com.zbf.system.service.ITBaseStorageService;
import com.zbf.system.service.ITMiStockService;
import com.zbf.system.service.ITMiXnStockService;
import com.zbf.system.service.ITOverdueService;
import com.zbf.web.controller.section.EnhanceDataList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


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

    private final ITMiXnStockService tMiStockService;

    private final ITOverdueService overdueService;

    private final ITBaseStorageService storageService;

    /**
     * 查询库存列表
     */
    @ApiOperation("查询库存列表")
    @PreAuthorize("@ss.hasPermi('system:stock:list')")
    @GetMapping("/list")
    @EnhanceDataList(entityType = TMiXnStock.class)
    public TableDataInfo list(TMiXnStock tMiStock) {
        startPage();
        tMiStock.setDeptId(getDeptId());
        if (tMiStock.getDate()!=null){
            String[] date = tMiStock.getDate();
            tMiStock.setStartTime(date[0]);
            tMiStock.setEndTime(date[1]);
        }
        List<TMiXnStock> list = tMiStockService.selectTMiStockList(tMiStock);
        return getDataTable(list);
    }
    /**
     * 导入
     */
    @Log(title = "出库数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<TMiXnStock> util = new ExcelUtil<TMiXnStock>(TMiXnStock.class);
        List<TMiXnStock> trList = util.importExcel(file.getInputStream());
        String message = tMiStockService.importData(trList, "");
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TMiXnStock> util = new ExcelUtil<TMiXnStock>(TMiXnStock.class);
        util.importTemplateExcel(response,"虚拟库存");
    }

    @GetMapping("/lists")
    @EnhanceDataList(entityType = TMiXnStock.class)
    public AjaxResult lists(TMiXnStock tMiStock) {
        if (tMiStock.getDate()!=null){
            String[] date = tMiStock.getDate();
            tMiStock.setStartTime(date[0]);
            tMiStock.setEndTime(date[1]);
        }
        List<TMiXnStock> 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, TMiXnStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        if (tMiStock.getDate()!=null){
            tMiStock.setStartTime(tMiStock.getDate()[0]);
            tMiStock.setEndTime(tMiStock.getDate()[1]);
        }
        List<TMiXnStock> list = tMiStockService.selectTMiStockList(tMiStock);
        ExcelUtil<TMiXnStock> util = new ExcelUtil<TMiXnStock>(TMiXnStock.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(TMiXnStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        return success(tMiStockService.getTotal(tMiStock));
    }

    @ApiOperation("统计查询库存列表")
    @PreAuthorize("@ss.hasPermi('system:stock:list')")
    @GetMapping("/countList")
    public TableDataInfo countList(TMiXnStock tMiStock) {
        tMiStock.setDeptId(getDeptId());
        List<TMiXnStock> 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 TMiXnStock 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 TMiXnStock 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(TMiXnStock tMiStock) {
        //超期呆滞天数
        String overdueDate = overdueService.getOverdueFromToday();
        if (StringUtils.isNotEmpty(overdueDate)) {
            tMiStock.setOverdueDate(overdueDate);
            startPage();
            List<TMiXnStock> list = tMiStockService.selectTMiStockList(tMiStock);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }

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


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

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

    /**
     * 手持盘点库存查询
     */
    @ApiOperation("手持盘点库存信息查询")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping("/pdaPanGoodsList")
    public AjaxResult pdaPanGoodsList(TMiXnStock 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) {
        TMiXnStock tMiStock = new TMiXnStock();
        tMiStock.setLocationId(tMiStockUpdate.getFromLoc());
        List<TMiXnStock> list = tMiStockService.list(new LambdaQueryWrapper<>(tMiStock).eq(TMiXnStock::getLocationId, tMiStockUpdate.getFromLoc()));
        return AjaxResult.success(list);
    }

    /**
     * 手持更换容器 托盘物料查询
     */
    @ApiOperation("手持更换容器 托盘物料查询")
    @PreAuthorize("@ss.hasPermi('system:stock:query')")
    @GetMapping("/getCtlNoGoods")
    public AjaxResult getCtlNoGoods(TMiXnStock 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));
    }
}
