package com.bonus.sgzb.material.service.impl;

import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.material.config.ExceptionEnum;
import com.bonus.sgzb.material.config.PageResultVo;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.MaWholeSetMapper;
import com.bonus.sgzb.material.service.MaWholeSetService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 整套抱杆操作实现层
 * @Author ma_sh
 * @create 2024/4/15 17:17
 */
@Service
@Slf4j
public class MaWholeSetServiceImpl implements MaWholeSetService {

    @Resource
    private MaWholeSetMapper mapper;

    /**
     * 新增整套抱杆管理
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insert(MaWholeSetDto dto) {
        if (dto == null) {
            return AjaxResult.error("参数不能为空！！！");
        }
        if (dto.getParentId() == null) {
            return AjaxResult.error("父级id不能为空");
        }
        int count = selectByParentId(dto.getParentId());
        if (count != 0) {
            return AjaxResult.error("该物品类型已经绑定相关配件，无法再次绑定，请重新选择！！！");
        }
        if (CollectionUtils.isNotEmpty(dto.getWholeList())) {
            for (MaWhole maWhole : dto.getWholeList()) {
                maWhole.setParentId(dto.getParentId());
            }
        }
        int res = 0;
        try {
            res = insertMaWholeSet(dto.getWholeList());
            if (res == 0) {
                log.error("insertMaWholeSet方法插入异常");
                throw new RuntimeException("insertMaWholeSet方法插入异常");
            }
        } catch (Exception e) {
            log.error("新增计划管理异常:{}",e.getMessage());
            return AjaxResult.error(ExceptionEnum.SAVE_TO_DATABASE.getCode(), ExceptionEnum.SAVE_TO_DATABASE.getMsg());
        }
        return AjaxResult.success("新增成功", res);
    }

    /**
     * 查询整套抱杆管理
     * @param dto
     * @return
     */
    @Override
    public PageResultVo<MaWholeVo> selectList(MaWholeSetDto dto) {
        List<MaWholeVo> list = mapper.selectList(dto);
        PageHelper.startPage(dto.getPageNum() == 0 ? 1 : dto.getPageNum(), dto.getPageSize());
        PageResultVo pageResult = new PageResultVo();
        // 分页信息
        PageInfo<MaWholeVo> pageInfo = new PageInfo<>(list);
        pageResult.setTotalCount(pageInfo.getTotal());
        pageResult.setTotalPageCount(pageInfo.getPages());
        pageResult.setResult(list);
        pageResult.setPageNum(dto.getPageNum());
        pageResult.setPageSize(dto.getPageSize());
        return pageResult;
    }

    /**
     * 查询整套抱杆明细
     * @param dto
     * @return
     */
    @Override
    public List<MaWholeVo> selectListById(MaWholeSetDto dto) {
        return mapper.selectListById(dto);
    }

    /**
     * 根据id删除
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteById(MaWholeSetDto dto) {
        if (dto.getId() == null) {
            return AjaxResult.error("删除标识id为空，无法进行删除");
        }
        int res = 0;
        try {
            res = deleteMaWhole(dto.getId());
            if (res == 0) {
                throw new RuntimeException("删除失败");
            }
        } catch (Exception e) {
            log.error("删除异常:{}",e.getMessage());
            return AjaxResult.error(ExceptionEnum.DELETE_TO_DATABASE.getCode(), ExceptionEnum.DELETE_TO_DATABASE.getMsg());
        }
        return AjaxResult.success("删除成功", res);
    }

    /**
     * 根据id删除整套配件信息
     * @param id
     * @return
     */
    private int deleteMaWhole(Integer id) {
        return mapper.deleteById(id);
    }

    /**
     * 修改整套抱杆管理
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(MaWholeSetDto dto) {
        log.info("修改整套抱杆管理传参：{}", dto);
        int count = selectByParentId(dto.getParentId());
        if (!dto.getId().equals(dto.getParentId()) && count != 0) {
            return AjaxResult.error("该物品类型已经配套相关配件，无法再次绑定，请重新提交修改！！！");
        }
        if (CollectionUtils.isNotEmpty(dto.getWholeList())) {
            for (MaWhole maWhole : dto.getWholeList()) {
                maWhole.setParentId(dto.getParentId());
            }
        }
        int res = 0;
        try {
            res = deleteMaWhole(dto.getId());
            if (res == 0) {
                log.error("deleteById方法删除异常");
                throw new RuntimeException("deleteById方法删除异常");
            }
            res = insertMaWholeSet(dto.getWholeList());
            if (res == 0) {
                log.error("insertMaWholeSet方法插入异常");
                throw new RuntimeException("insertMaWholeSet方法插入异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(ExceptionEnum.UPDATE_TO_DATABASE.getCode(), ExceptionEnum.UPDATE_TO_DATABASE.getMsg());
        }
        return AjaxResult.success("修改成功", res);
    }

    /**
     * 修改时查询整套抱杆明细
     * @param id
     * @return
     */
    @Override
    public MaWholeTreeVo selectListTree(Integer id) {
        //根据id去ma_whole_set表中查询typeId
        List<Integer> typeId = mapper.selectTypeId(id);
        //先根据id去查询物质类型树树级id
        TreeSelectId selectId = mapper.selectTypeTree(id);
        //根据typeId查询对应树id
        List<TreeSelectId> ids = mapper.selectId(typeId);
        List<MaWholeVo> voList = mapper.select(id);
        MaWholeTreeVo treeVo = new MaWholeTreeVo();
        treeVo.setTypeList(selectId);
        treeVo.setList(ids);
        treeVo.setVoList(voList);
        return treeVo;
    }

    /**
     * 方法提取，新增ma_whole_set表
     * @param wholeList
     * @return
     */
    private int insertMaWholeSet(List<MaWhole> wholeList) { return mapper.insert(wholeList); }

    /**
     * 根据parentId查询，去重
     * @param parentId
     * @return
     */
    private int selectByParentId(Integer parentId) {
        return mapper.selectByParentId(parentId);
    }
}
