package com.bonus.material.warehousing.service.Impl;

import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.devchange.domain.MapBean;
import com.bonus.material.device.domain.vo.DevMergeVo;
import com.bonus.material.device.service.DevMergeService;
import com.bonus.material.toolProcess.domain.ToolApplyDetailsEntity;
import com.bonus.material.toolProcess.service.ToolApplyService;
import com.bonus.material.warehousing.domain.WarehousingEntity;
import com.bonus.material.warehousing.mapper.WarehousingMapper;
import com.bonus.material.warehousing.service.WarehousingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.bonus.common.biz.constant.MaterialConstants.ADMIN_ID;
import static com.bonus.common.biz.constant.MaterialConstants.PROVINCE_COMPANY_DEPT_ID;

@Service
@Slf4j
public class WarehousingServiceImpl implements WarehousingService {
    @Resource
    private WarehousingMapper mapper;
    @Resource
    private ToolApplyService toolApplyService;
    @Resource
    private DevMergeService devMergeService;

    /**
     * 新增入库记录
     *
     * @param warehousing 入库实体
     * @return 是否成功
     */
    @Override
    public AjaxResult add(WarehousingEntity warehousing) {
        try {
            warehousing.setCreateUser(SecurityUtils.getLoginUser().getSysUser().getNickName());
            warehousing.setUserId(SecurityUtils.getLoginUser().getUserid());
            int insert = mapper.insert(warehousing);
            return insert > 0 ? AjaxResult.success(warehousing) : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 根据id删除入库记录（逻辑删除）
     *
     * @param id 主键id
     * @return 是否成功
     */
    @Override
    public AjaxResult deleteById(Integer id) {
        try {
            int insert = mapper.deleteById(id);
            return insert > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 根据id更新入库记录
     *
     * @param warehousing 入库实体
     * @return 是否成功
     */
    @Override
    public AjaxResult updateById(WarehousingEntity warehousing) {
        try {
            int insert = mapper.updateById(warehousing);
            return insert > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 根据id查询入库记录
     *
     * @param id 主键id
     * @return 入库实体
     */
    @Override
    public AjaxResult getById(Integer id) {
        try {
            WarehousingEntity warehousingEntity = mapper.selectById(id);
            return ObjectUtils.isNotEmpty(warehousingEntity) ? AjaxResult.success(warehousingEntity) : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 条件查询入库记录列表
     *
     * @param warehousing 查询条件
     * @return 入库记录列表
     */
    @Override
    public List<WarehousingEntity> list(WarehousingEntity warehousing) {
        try {
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            Long userId = SecurityUtils.getLoginUser().getUserid();
            // 管理员和省公司可查看所有数据
//            if (userId != null && deptId != null
//                    && !userId.equals(ADMIN_ID)
//                    && !deptId.equals(PROVINCE_COMPANY_DEPT_ID)) {
//                warehousing.setCompanyId(deptId);
//            }
            if(ADMIN_ID.equals(userId)){
                warehousing.setCompanyId(1L);
            }else{
                warehousing.setCompanyId(deptId);
            }
            List<WarehousingEntity> warehousingEntities = mapper.selectList(warehousing);
            return ObjectUtils.isNotEmpty(warehousingEntities) ? warehousingEntities : new ArrayList<WarehousingEntity>();
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ArrayList<WarehousingEntity>();
        }
    }

    /**
     * 批量提交
     *
     * @param ids
     * @return
     */
    @Override
    public AjaxResult batchSubmission(Integer[] ids) {
        try {
            // 1. 空值/空数组校验：提前终止无效请求
            if (ObjectUtils.isEmpty(ids) || ids.length == 0) {
                return AjaxResult.error("批量提交失败：未选择数据");
            }
            for (Integer id : ids) {
                WarehousingEntity entity = mapper.selectById(id);
                if (entity.getMaNum() == 0 && entity.getToolNum() == 0) {
                    return AjaxResult.error("存在装备数和工具数均为0的申请单，提交失败");
                }
            }
            Integer num = mapper.batchSubmission(ids);
            return num > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 批量同意
     *
     * @param ids
     * @return
     */
    @Override
    public AjaxResult batchApproval(Integer[] ids) {
        try {
            String nickName = SecurityUtils.getLoginUser().getSysUser().getNickName();
            Integer num = mapper.batchApproval(ids, nickName);
            if (num > 0) {
                for (Integer id : ids) {
                    WarehousingEntity entity = mapper.selectById(id);
                    if (ObjectUtils.isNotEmpty(entity)) {
                        if (ObjectUtils.isNotEmpty(entity.getApplyId())) {
                            ToolApplyDetailsEntity toolApplyDetailsEntity = new ToolApplyDetailsEntity();
                            toolApplyDetailsEntity.setApplyId(Long.valueOf(entity.getApplyId()));
                            toolApplyDetailsEntity.setStatus("2");
                            toolApplyService.updateAllDetail(toolApplyDetailsEntity);
                        }

                        if (ObjectUtils.isNotEmpty(entity.getOrderId())) {
                            if (ObjectUtils.isNotEmpty(entity.getOrderId())) {
                                DevMergeVo devMergeVo = new DevMergeVo();
                                devMergeVo.setId(entity.getOrderId());
                                devMergeVo.setStatus("1");
                                List<String> list = mapper.getMaIds(entity.getOrderId());
                                String maIdsStr = list.stream()
                                        .filter(str -> str != null && !str.trim().isEmpty()) // 可选：过滤空值/空白符
                                        .collect(Collectors.joining(","));
                                devMergeVo.setDevIds(maIdsStr);
                                devMergeService.checkDevice(devMergeVo);
                            }
                        }

                    }

                }
            }
            return num > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 批量驳回
     *
     * @param ids
     * @return
     */
    @Override
    public AjaxResult batchRejection(Integer[] ids) {
        try {
            Integer num = mapper.batchRejection(ids);
            return num > 0 ? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * @param id
     * @return
     */
    @Override
    public AjaxResult getDevDetails(Integer id) {
        return AjaxResult.success(mapper.getDevDetails(id));
    }
}
