package cn.iocoder.yudao.module.system.service.biz;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MaterialConfigPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MaterialConfigSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.excel.MaterialConfigExcelVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.MaterialConfigDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.MaterialConfigMapper;
import cn.iocoder.yudao.module.system.dal.mysql.dict.DictDataMapper;
import com.mzt.logapi.context.LogRecordContext;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.CONFIG_NOT_EXISTS;

/**
 * @Author: jinyd
 * @CreateTime: 2025/3/10  9:05
 * @Description:
 * @Version: 4.0
 */

@Service
@Validated
public class MaterialConfigServiceImpl implements MateriaConfigService {

    @Resource
    private MaterialConfigMapper materialConfigMapper;

    @Resource
    private DictDataMapper dictDataMapper;

    @Override
    public Long createConfig(MaterialConfigSaveReqVO createReqVO) {
        // 插入
        MaterialConfigDO config = BeanUtils.toBean(createReqVO, MaterialConfigDO.class);
        materialConfigMapper.insert(config);
        // 返回
        return config.getId();
    }

    @Override
    public void updateConfig(MaterialConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateConfigExists(updateReqVO.getId());
        // 更新
        MaterialConfigDO updateObj = BeanUtils.toBean(updateReqVO, MaterialConfigDO.class);
        materialConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteConfig(Long id) {
        // 校验存在
        validateConfigExists(id);
        // 删除
        materialConfigMapper.deleteById(id);
    }

    private void validateConfigExists(Long id) {
        if (materialConfigMapper.selectById(id) == null) {
            throw exception(CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public MaterialConfigDO getConfig(Long id) {
        return materialConfigMapper.selectById(id);
    }

    @Override
    public PageResult<MaterialConfigDO> getConfigPage(MaterialConfigPageReqVO pageReqVO) {
        PageResult<MaterialConfigDO> materialConfigDOPageResult = materialConfigMapper.selectPage(pageReqVO);
        List<MaterialConfigDO> list = materialConfigDOPageResult.getList();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setSerialNumber(i + 1);
        }
        return materialConfigDOPageResult;
    }

    @Override
    public Map<String, Object> importMaterialExcel(List<MaterialConfigExcelVO> list, Integer orgType, Long tenantId) {
        List<DictDataDO> dictDataDOS = dictDataMapper.selectList(new LambdaQueryWrapperX<DictDataDO>().eq(DictDataDO::getDictType, "material_type"));
        Map<String, String> dictDataMap= new HashMap<>();
        if (dictDataDOS == null || dictDataDOS.size() == 0) return null;
        dictDataDOS.forEach(dictDataDO -> dictDataMap.put(dictDataDO.getLabel(), dictDataDO.getValue()));
        for (int i = 0; i < list.size(); i++) {
            MaterialConfigExcelVO materialConfigExcelVO = list.get(i);
            String type = dictDataMap.get(materialConfigExcelVO.getType());
            if (!dictDataMap.containsKey(materialConfigExcelVO.getType())) {
                throw exception(new ErrorCode(1000, "导入失败！第" + (i + 1) + "行，物资类型不存在"));
            }
            MaterialConfigDO materialConfigDO = materialConfigMapper.selectOne(new LambdaQueryWrapperX<MaterialConfigDO>()
                    .eq(MaterialConfigDO::getName, materialConfigExcelVO.getName())
                    .eq(MaterialConfigDO::getType, type));
            MaterialConfigDO udpateDO = new MaterialConfigDO();
            if (null == materialConfigDO) {
                udpateDO.setName(materialConfigExcelVO.getName());
                udpateDO.setType(type);
                udpateDO.setUnit(materialConfigExcelVO.getUnit());
                udpateDO.setSafetyStock(materialConfigExcelVO.getSafetyStock());
                udpateDO.setSpecification(materialConfigExcelVO.getSpecification());
                udpateDO.setDescription(materialConfigExcelVO.getDescription());
                udpateDO.setStatus(2);
                udpateDO.setOrgType(orgType);
                udpateDO.setTenantId(tenantId);
                materialConfigMapper.insert(udpateDO);
            } else {
                udpateDO.setId(materialConfigDO.getId());
                udpateDO.setName(materialConfigExcelVO.getName());
                udpateDO.setType(type);
                udpateDO.setUnit(materialConfigExcelVO.getUnit());
                udpateDO.setSafetyStock(materialConfigExcelVO.getSafetyStock());
                udpateDO.setSpecification(materialConfigExcelVO.getSpecification());
                udpateDO.setDescription(materialConfigExcelVO.getDescription());
                udpateDO.setStatus(2);
                udpateDO.setOrgType(orgType);
                udpateDO.setTenantId(tenantId);
                materialConfigMapper.updateById(udpateDO);
            }
        }
        LogRecordContext.putVariable("size", list.size());
        Map<String,Object> map = new HashMap<>();
        map.put("successCount",list.size());
        map.put("failCount",0);
        map.put("errorList",null);
        return map;
    }
}
