package com.ruoyi.web.controller.app;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.app.DTO.ValidDistributeListDTO;
import com.ruoyi.app.DTO.ValidSlaughterCodeDTO;
import com.ruoyi.app.model.Purchaser;
import com.ruoyi.app.model.request.AddDistributeBatch;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtil;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.app.model.DistributeBatch;
import com.ruoyi.app.service.IDistributeBatchService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 分销批次Controller
 * 
 * @author coede
 * @date 2025-03-19
 */
@Api("分销批次信息管理")
@RestController
@RequestMapping("/app/distributeBatch")
public class DistributeBatchController extends BaseController
{
    @Autowired
    private IDistributeBatchService distributeBatchService;

    /**
     * 查询分销批次列表
     */
    @ApiOperation("查询分销批次列表")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:list')")
    @GetMapping("/list")
    public TableDataInfo list(DistributeBatch distributeBatch)
    {
        startPage();
        List<DistributeBatch> list = distributeBatchService.selectDistributeBatchList(distributeBatch);
        return getDataTable(list);
    }

    /**
     * 查询指定血码还未关闭的分销批次，也就是可以继续绑吊钩，
     * 通过判断24小时内的分销批次
     */
    @ApiOperation("血码可用批次")
    @GetMapping("/getValidList")
    public AjaxResult getValidList(DistributeBatch distributeBatch)
    {

        List<ValidDistributeListDTO> list = distributeBatchService.selectValidDistribute(distributeBatch);
        return success(list);
    }

    /**
     * 获取存在未完成（24小时内）的分销批次的血码
     */
    @ApiOperation("可用血码")
    @GetMapping("/getValidCodeList")
    public AjaxResult getValidCodeList()
    {

        List<ValidSlaughterCodeDTO> list = distributeBatchService.selectValidCode();
        return success(list);
    }

    /**
     * 导出分销批次列表
     */
    @ApiOperation("导出分销批次列表")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:export')")
    @Log(title = "分销批次", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DistributeBatch distributeBatch)
    {
        List<DistributeBatch> list = distributeBatchService.selectDistributeBatchList(distributeBatch);
        ExcelUtil<DistributeBatch> util = new ExcelUtil<DistributeBatch>(DistributeBatch.class);
        util.exportExcel(response, list, "分销批次数据");
    }

    /**
     * 获取分销批次详细信息
     */
    @ApiOperation("获取分销批次详细信息")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(distributeBatchService.selectDistributeBatchById(id));
    }

    /**
     * 新增分销批次
     */
    @ApiOperation("新增分销批次")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:add')")
    @Log(title = "分销批次", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody DistributeBatch distributeBatch)
    {
        if(!distributeBatchService.checkTotalLessThanAmount(distributeBatch)){
            return error("新增分销批次失败，分销数量输入错误");
        }
        distributeBatch.setCreateBy(getUsername());
        return toAjax(distributeBatchService.insertDistributeBatch(distributeBatch));
    }

    /**
     * 批量新增分销批次
     */
    @ApiOperation("批量新增分销批次")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:add')")
    @Log(title = "分销批次", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addBatch")
    public AjaxResult addBatch(@Validated @RequestBody AddDistributeBatch req)
    {
        //生成新对象
        List<DistributeBatch> distributeArr = req.getDistributeArr().stream()
                .peek(item -> {
                    item.setEntranceBatchId(req.getEntranceBatchId());
                    item.setCreateTime(DateUtils.getNowDate());
                    item.setCreateBy(getUsername());
                })
                .collect(Collectors.toList());
        //先判断本身数组内是否有重复的
        Set<String> uniqueIds = new HashSet<>();
        for (DistributeBatch distribute : distributeArr) {
            String key = String.valueOf(distribute.getPurchaserId());
            //noinspection ConstantConditions  忽略错误的IDEA提示
            if (!uniqueIds.add(key)) {
                return error("新增分销批次失败，本次添加存在相同的肉商");
            }
        }
        //校验数据库的
        int add = 0;
        for (DistributeBatch distribute : distributeArr) {
            add += NumberUtil.getIntValue(distribute.getAmount());
            DistributeBatch check = distributeBatchService.checkPurchaserUnique(distribute);
            if (StringUtils.isNotNull(check))
            {
                Purchaser purchaser = check.getPurchaser();
                return error("新增分销批次失败，该批次下肉商'" + purchaser.getPurchaserName() + "'已存在");
            }
        }
        //判断分销数量是否超过批次实际数量
        DistributeBatch distributeBuild = new DistributeBatch();
        distributeBuild.setEntranceBatchId(req.getEntranceBatchId());
        distributeBuild.setAmount(add);
        if(!distributeBatchService.checkTotalLessThanAmount(distributeBuild)){
            return error("新增分销批次失败，分销数量输入错误");
        }
        return toAjax(distributeBatchService.insertDistributeBatchByBatch(distributeArr));
    }

    /**
     * 修改分销批次
     */
    @ApiOperation("修改分销批次")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:edit')")
    @Log(title = "分销批次", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody DistributeBatch distributeBatch)
    {
        DistributeBatch check = distributeBatchService.checkPurchaserUnique(distributeBatch);
        if (StringUtils.isNotNull(check)&& check.getId().longValue() != distributeBatch.getId().longValue())
        {
            Purchaser purchaser = check.getPurchaser();
            return error("修改分销批次失败，该批次下肉商'" + purchaser.getPurchaserName() + "'已存在");
        }
        //判断分销数量是否超过批次实际数量
        if(!distributeBatchService.checkTotalLessThanAmount(distributeBatch)){
            return error("修改分销批次失败，分销数量输入错误");
        }

        distributeBatch.setUpdateBy(getUsername());
        return toAjax(distributeBatchService.updateDistributeBatch(distributeBatch));
    }

    /**
     * 删除分销批次
     */
    @ApiOperation("删除分销批次")
    // @PreAuthorize("@ss.hasPermi('app:distributeBatch:remove')")
    @Log(title = "分销批次", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(distributeBatchService.deleteDistributeBatchByIds(ids));
    }
}
