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.SlaughterRelationDTO;
import com.ruoyi.app.domain.Purchaser;
import com.ruoyi.app.domain.request.AddSlaughterRelationBatch;
import com.ruoyi.app.domain.request.ExportSlaughterRelation;
import com.ruoyi.app.domain.request.ReqGetSlaughterRelation;
import com.ruoyi.app.domain.request.ReqSlaughterRelation;
import com.ruoyi.app.domain.response.RespGetSlaughterRelation;
import com.ruoyi.common.utils.DateUtils;
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.domain.SlaughterRelation;
import com.ruoyi.app.service.ISlaughterRelationService;
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/slaughterRelation")
public class SlaughterRelationController extends BaseController
{
    @Autowired
    private ISlaughterRelationService slaughterRelationService;

    /**
     * 供应商血码数量列表
     */
    @ApiOperation("供应商血码数量列表")
    @GetMapping("/supplierList")
    public TableDataInfo supplierList(ReqGetSlaughterRelation req)
    {
        startPage();
        List<RespGetSlaughterRelation> list = slaughterRelationService.selectSupplierList(req);
        return getDataTable(list);
    }

    /**
     * 查询血码关系列表
     */
    @ApiOperation("查询血码关系列表")
    @GetMapping("/list")
    public TableDataInfo list(ReqSlaughterRelation req)
    {
        startPage();
        List<SlaughterRelation> list = slaughterRelationService.selectSlaughterRelationList(req);
        return getDataTable(list);
    }

    /**
     * 导出血码关系列表
     */
    @ApiOperation("导出血码关系列表")
    @PreAuthorize("@ss.hasPermi('app:slaughterRelation:export')")
    @Log(title = "血码关系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExportSlaughterRelation req)
    {
        List<SlaughterRelationDTO> list = slaughterRelationService.exportSlaughterRelationList(req);
        list.forEach(item -> item.setQrcode(item.getSlaughterCode()));
        ExcelUtil<SlaughterRelationDTO> util = new ExcelUtil<>(SlaughterRelationDTO.class);
        util.exportExcel(response, list, "血码关系数据");
    }

    /**
     * 获取血码关系详细信息
     */
    @ApiOperation("获取血码关系详细信息")
    @PreAuthorize("@ss.hasPermi('app:slaughterRelation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(slaughterRelationService.selectSlaughterRelationById(id));
    }

    /**
     * 新增血码关系
     */
    @ApiOperation("新增血码关系")
    @PreAuthorize("@ss.hasPermi('app:slaughterRelation:add')")
    @Log(title = "血码关系", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SlaughterRelation slaughterRelation)
    {
        if (!slaughterRelationService.checkCodeUnique(slaughterRelation))
        {
            return error("新增血码关系失败，血码'" + slaughterRelation.getSlaughterCode() + "'已存在");
        }
        SlaughterRelation check = slaughterRelationService.checkPurchaserUnique(slaughterRelation);
        if (StringUtils.isNotNull(check))
        {
            Purchaser purchaser = check.getPurchaser();
            return error("新增血码关系失败，该供应商下肉商'" + purchaser.getPurchaserName() + "'已存在");
        }
        slaughterRelation.setCreateBy(getUsername());
        return toAjax(slaughterRelationService.insertSlaughterRelation(slaughterRelation));
    }

    /**
     * 批量新增血码关系
     */
    @ApiOperation("批量新增血码关系")
    @PreAuthorize("@ss.hasPermi('app:slaughterRelation:add')")
    @Log(title = "血码关系", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addBatch")
    public AjaxResult addBatch(@Validated @RequestBody AddSlaughterRelationBatch req)
    {
        //生成新对象
        List<SlaughterRelation> relationArr = req.getRelationArr().stream()
                .map(item -> {
                    SlaughterRelation newrelation = new SlaughterRelation();
                    newrelation.setPurchaserId(item.getPurchaserId());
                    newrelation.setSlaughterCode(item.getSlaughterCode());
                    newrelation.setSupplierId(req.getSupplierId());
                    newrelation.setCreateTime(DateUtils.getNowDate());
                    newrelation.setCreateBy(getUsername());
                    return newrelation;
                })
                .collect(Collectors.toList());
        //先判断本身数组内是否有重复的
        Set<String> uniqueIds = new HashSet<>();
        Set<String> uniqueCodes = new HashSet<>();
        for (SlaughterRelation relation : relationArr) {
            String key = String.valueOf(relation.getPurchaserId());
            //noinspection ConstantConditions  忽略错误的IDEA提示
            if (!uniqueIds.add(key)) {
                return error("新增血码关系失败，存在同一肉商配置多个血码的情况");
            }
            String code = relation.getSlaughterCode();
            //noinspection ConstantConditions  忽略错误的IDEA提示
            if (!uniqueCodes.add(code)) {
                return error("新增血码关系失败，存在多个肉商配置同一血码的情况");
            }
        }
        //校验数据库的
        for (SlaughterRelation relation : relationArr) {

            if (!slaughterRelationService.checkCodeUnique(relation))
            {
                return error("新增血码关系失败，血码'" + relation.getSlaughterCode() + "'已存在");
            }
            SlaughterRelation check = slaughterRelationService.checkPurchaserUnique(relation);
            if (StringUtils.isNotNull(check))
            {
                Purchaser purchaser = check.getPurchaser();
                return error("新增血码关系失败，该供应商下肉商'" + purchaser.getPurchaserName() + "'已存在");
            }
        }
        return toAjax(slaughterRelationService.insertSlaughterRelationBatch(relationArr));
    }

    /**
     * 修改血码关系
     */
    @ApiOperation("修改血码关系")
    @PreAuthorize("@ss.hasPermi('app:slaughterRelation:edit')")
    @Log(title = "血码关系", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SlaughterRelation slaughterRelation)
    {
        if (!slaughterRelationService.checkCodeUnique(slaughterRelation))
        {
            return error("修改血码关系失败，血码'" + slaughterRelation.getSlaughterCode() + "'已存在");
        }
        SlaughterRelation check = slaughterRelationService.checkPurchaserUnique(slaughterRelation);
        if (StringUtils.isNotNull(check) && check.getId().longValue() != slaughterRelation.getId().longValue())
        {
            Purchaser purchaser = check.getPurchaser();
            return error("修改血码关系失败，该供应商下肉商'" + purchaser.getPurchaserName() + "'已存在");
        }
        slaughterRelation.setUpdateBy(getUsername());
        return toAjax(slaughterRelationService.updateSlaughterRelation(slaughterRelation));
    }

    /**
     * 删除血码关系
     */
    @ApiOperation("删除血码关系")
    @PreAuthorize("@ss.hasPermi('app:slaughterRelation:remove')")
    @Log(title = "血码关系", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(slaughterRelationService.deleteSlaughterRelationByIds(ids));
    }

    /**
     * 查询全部血码关系列表
     */
    @ApiOperation("查询全部血码关系列表")
    @GetMapping("/optionselect")
    public AjaxResult optionselect(ReqSlaughterRelation req)
    {

        List<SlaughterRelation> list = slaughterRelationService.selectSlaughterRelationList(req);
        return success(list);
    }
}
