package org.jeecg.modules.toolSheet.controller;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.api.model.CabinetStocks;
import org.jeecg.modules.api.service.CabinetConnectService;
import org.jeecg.modules.stock.entity.StockLog;
import org.jeecg.modules.stock.service.IStockLogService;
import org.jeecg.modules.tool.entity.Tool;
import org.jeecg.modules.tool.service.IToolService;
import org.jeecg.modules.toolSheet.entity.ToolSheet;
import org.jeecg.modules.toolSheet.service.IToolSheetService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 工器具台账
 * @Author: jeecg-boot
 * @Date: 2025-01-15
 * @Version: V1.0
 */
@Api(tags = "工器具台账")
@RestController
@RequestMapping("/toolSheet/toolSheet")
@Slf4j
public class ToolSheetController extends JeecgController<ToolSheet, IToolSheetService> {
    @Autowired
    private IToolSheetService toolSheetService;
    @Autowired
    private IToolService toolService;
    @Autowired
    private IStockLogService stockLogService;
    @Autowired
    private CabinetConnectService cabinetConnectService;
    @Value("${spring.active}")
    private String activeProfile;

    /**
     * 分页列表查询
     *
     * @param toolSheet
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工器具台账-分页列表查询")
    @ApiOperation(value = "工器具台账-分页列表查询", notes = "工器具台账-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ToolSheet>> queryPageList(ToolSheet toolSheet,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<ToolSheet> queryWrapper = QueryGenerator.initQueryWrapper(toolSheet, req.getParameterMap());
        Page<ToolSheet> page = new Page<ToolSheet>(pageNo, pageSize);
        IPage<ToolSheet> pageList = toolSheetService.page(page, queryWrapper);
        pageList.getRecords().forEach(item -> {
            Tool tool = toolService.getById(item.getToolId());
            item.setCheckRequire(tool.getCheckRequire());
            item.setStockWarning(tool.getStockWarning());
        });
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param toolSheet
     * @return
     */
    @AutoLog(value = "工器具台账-添加")
    @ApiOperation(value = "工器具台账-添加", notes = "工器具台账-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:bu_tool_sheet:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ToolSheet toolSheet) {
        toolSheetService.save(toolSheet);
        StockLog stockLog = new StockLog();
        stockLog.setItem(toolSheet.getId());
        stockLog.setType(1);
        stockLog.setIoType(1);
        stockLog.setQuantity(Double.valueOf(toolSheet.getNum()));
        stockLog.setOperator(toolSheet.getCreateBy());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param toolSheet
     * @return
     */
    @AutoLog(value = "工器具台账-编辑")
    @ApiOperation(value = "工器具台账-编辑", notes = "工器具台账-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:bu_tool_sheet:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ToolSheet toolSheet) {
        toolSheetService.updateById(toolSheet);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工器具台账-通过id删除")
    @ApiOperation(value = "工器具台账-通过id删除", notes = "工器具台账-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:bu_tool_sheet:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        toolSheetService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工器具台账-批量删除")
    @ApiOperation(value = "工器具台账-批量删除", notes = "工器具台账-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:bu_tool_sheet:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.toolSheetService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工器具台账-通过id查询")
    @ApiOperation(value = "工器具台账-通过id查询", notes = "工器具台账-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ToolSheet> queryById(@RequestParam(name = "id", required = true) String id) {
        ToolSheet toolSheet = toolSheetService.getById(id);
        if (toolSheet == null) {
            return Result.error("未找到对应数据");
        }
        Tool tool = toolService.getById(toolSheet.getToolId());
        toolSheet.setCheckRequire(tool.getCheckRequire());
        return Result.OK(toolSheet);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param toolSheet
     */
    //@RequiresPermissions("org.jeecg.modules.demo:bu_tool_sheet:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ToolSheet toolSheet) {
        return super.exportXls(request, toolSheet, ToolSheet.class, "工器具台账");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("bu_tool_sheet:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return toolSheetService.importExcel(request, response);
    }

    @RequiresRoles({"admin"})
    @PostMapping("/asyncTool2Cabinet")
    public Result<?> asyncTool() {
        List<ToolSheet> toolSheets = toolSheetService.list();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<CabinetStocks> cabinetStocks = toolSheets.stream().map(x -> {
            CabinetStocks stocks = new CabinetStocks();
            stocks.setToolId(x.getId());
            stocks.setToolCode(x.getCode());
            stocks.setCalibrationTime(x.getLastCheckDate().toInstant().atZone(ZoneId.of("Asia/Shanghai")).format(formatter));
            stocks.setStatus(x.getStatus());
            Tool tool = toolService.getById(x.getToolId());
            if (tool != null) {
                stocks.setToolType(tool.getId());
                stocks.setTypeName(tool.getName());
                stocks.setToolName(tool.getName() + "(" + tool.getModel() + ")");
            }
            return stocks;
        }).toList();

        if ("prod".equals(activeProfile)) {
            cabinetConnectService.sendToolInfo(cabinetStocks);
        }
        return Result.ok();
    }

}
