package com.zhyc.module.feed.controller;

import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.zhyc.module.feed.domain.SgFormulaList;
import com.zhyc.module.feed.service.ISgFormulaListService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhyc.common.annotation.Log;
import com.zhyc.common.core.controller.BaseController;
import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.common.enums.BusinessType;
import com.zhyc.module.feed.domain.SgFormulaManagement;
import com.zhyc.module.feed.service.ISgFormulaManagementService;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 配方管理Controller
 *
 * @author HashMap
 * @date 2025-08-09
 */
@RestController
@RequestMapping("/feed/FormulaManagement")
public class SgFormulaManagementController extends BaseController {
    private final ISgFormulaManagementService sgFormulaManagementService;
    private final ISgFormulaListService sgFormulaListService;

    public SgFormulaManagementController(ISgFormulaManagementService sgFormulaManagementService, ISgFormulaListService sgFormulaListService) {
        this.sgFormulaManagementService = sgFormulaManagementService;
        this.sgFormulaListService = sgFormulaListService;
    }

    /**
     * 查询配方管理列表
     */
    @PreAuthorize("@ss.hasPermi('feed:FormulaManagement:list')")
    @GetMapping("/list")
    public TableDataInfo list(SgFormulaManagement sgFormulaManagement) {
        startPage();
        // 非查询详情时设定BatchId为0查询配方模板
        if (null != sgFormulaManagement && !Objects.equals(sgFormulaManagement.getQueryType(), "query")) {
            sgFormulaManagement.setBatchId("0");
        }
        List<SgFormulaManagement> FormulaManagement = sgFormulaManagementService.selectSgFormulaManagementList(sgFormulaManagement);
        for (SgFormulaManagement sgFormulaManagementItem : FormulaManagement) {
            SgFormulaManagement query = new SgFormulaManagement();
            query.setFormulaId(sgFormulaManagementItem.getFormulaId());
            query.setQueryType("Sub");
            List<SgFormulaManagement> subFormula = sgFormulaManagementService.selectSgFormulaManagementList(query);
            sgFormulaManagementItem.setSubFormulaList(subFormula);
        }
        return getDataTable(FormulaManagement);
    }

    /**
     * 导出配方管理列表
     */
    @PreAuthorize("@ss.hasPermi('feed:FormulaManagement:export')")
    @Log(title = "配方管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SgFormulaManagement sgFormulaManagement) {
        List<SgFormulaManagement> list = sgFormulaManagementService.selectSgFormulaManagementList(sgFormulaManagement);
        ExcelUtil<SgFormulaManagement> util = new ExcelUtil<>(SgFormulaManagement.class);
        util.exportExcel(response, list, "配方管理数据");
    }

    /**
     * 获取配方管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('feed:FormulaManagement:query')")
    @GetMapping(value = "/{formulaId}")
    public AjaxResult getInfo(@PathVariable("formulaId") String formulaId) {
        return success(sgFormulaManagementService.selectSgFormulaManagementByFormulaId(formulaId));
    }

    /**
     * 新增配方管理
     */
    @PreAuthorize("@ss.hasPermi('feed:FormulaManagement:add')")
    @Log(title = "配方管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody SgFormulaManagement sgFormulaManagement) {
        if (null == sgFormulaManagement)
            throw new RuntimeException("ERROR: 数据为空");
        sgFormulaManagement.setUserId(getUserId());
        sgFormulaManagement.setDeptId(getDeptId());
        if (Objects.equals(sgFormulaManagement.getBatchId(), "0")) {
            SgFormulaManagement exist = sgFormulaManagementService.selectSgFormulaManagementByFormulaId(sgFormulaManagement.getFormulaId());
            if (exist != null) {
                throw new RuntimeException("WARNING: 配方编码重复,录入失败");
            }
        } else {
            SgFormulaManagement exist = new SgFormulaManagement();
            exist.setFormulaId(sgFormulaManagement.getFormulaId());
            exist.setBatchId(sgFormulaManagement.getBatchId());
            if (!sgFormulaManagementService.selectSgFormulaManagementList(exist).isEmpty()) {
                throw new RuntimeException("WARNING: 批号重复,录入失败");
            }
        }
        List<SgFormulaList> sgFormulaList = sgFormulaManagement.getSgFormulaList();
        for (SgFormulaList sgFormulaListItem : sgFormulaList) {
            // 前端引用模板数据时会引用主键Code,在插入前置为空
            sgFormulaListItem.setCode(null);
            sgFormulaListItem.setFormulaId(sgFormulaManagement.getFormulaId());
            sgFormulaListItem.setBatchId(sgFormulaManagement.getBatchId());
            sgFormulaListService.insertSgFormulaList(sgFormulaListItem);
        }
        return toAjax(sgFormulaManagementService.insertSgFormulaManagement(sgFormulaManagement));
    }

    /**
     * 修改配方管理
     */
    @PreAuthorize("@ss.hasPermi('feed:FormulaManagement:edit')")
    @Log(title = "配方管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody SgFormulaManagement sgFormulaManagement) {
        List<SgFormulaList> sgFormulaList = sgFormulaManagement.getSgFormulaList();
        if (null != sgFormulaManagement.getFormulaId() && null != sgFormulaManagement.getBatchId()) {
            SgFormulaList delete = new SgFormulaList();
            delete.setFormulaId(sgFormulaManagement.getFormulaId());
            delete.setBatchId(sgFormulaManagement.getBatchId());
            sgFormulaListService.deleteSgFormulaListByFormulaIdAndBatchId(delete);
        } else {
            throw new RuntimeException("FormulaID & BatchID不能为空");
        }

        // 配方表同步更新
        for (SgFormulaList sgFormulaListItem : sgFormulaList) {
            sgFormulaListItem.setBatchId(sgFormulaManagement.getBatchId());
            sgFormulaListItem.setFormulaId(sgFormulaManagement.getFormulaId());
            sgFormulaListService.insertSgFormulaList(sgFormulaListItem);
        }

        // 通知配料清单刷新数据
        SgFeedListController.refresh = true;
        return toAjax(sgFormulaManagementService.updateSgFormulaManagement(sgFormulaManagement));
    }

    /**
     * 删除配方管理
     */
    @PreAuthorize("@ss.hasPermi('feed:FormulaManagement:remove')")
    @Log(title = "配方管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{formulaId}/{batchId}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable String formulaId, @PathVariable String batchId) {
        SgFormulaManagement sgFormulaManagement = new SgFormulaManagement();
        sgFormulaManagement.setFormulaId(formulaId);
        sgFormulaManagement.setBatchId(batchId);
        if (sgFormulaManagement.getBatchId().equals("0")) {
            sgFormulaManagement.setBatchId(null);
            List<SgFormulaManagement> list = sgFormulaManagementService.selectSgFormulaManagementList(sgFormulaManagement);
            if (list.size() > 1) {
                throw new RuntimeException("WARNING 该配方正被使用,无法删除");
            }
            sgFormulaManagement.setBatchId(batchId);
        }
        // 前置检查完毕 执行删除
        sgFormulaManagement.setBatchId(batchId);

        // 通知配料清单刷新数据
        SgFeedListController.refresh = true;
        return toAjax(sgFormulaManagementService.deleteSgFormulaManagement(sgFormulaManagement));
    }
}
