package com.zt.plat.module.qms.common.data.service;

import cn.hutool.core.collection.CollUtil;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataCollectionFieldDO;
import com.zt.plat.module.qms.common.data.dal.mapper.DataCollectionFieldMapper;
import com.zt.plat.module.qms.common.data.controller.vo.DataCollectionFieldPageReqVO;
import com.zt.plat.module.qms.common.data.controller.vo.DataCollectionFieldRespVO;
import com.zt.plat.module.qms.common.data.controller.vo.DataCollectionFieldSaveReqVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DATA_COLLECTION_FIELD_NOT_EXISTS;

/**
 * 数据集字段 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class DataCollectionFieldServiceImpl implements DataCollectionFieldService {

    @Resource
    private DataCollectionFieldMapper dataCollectionFieldMapper;

    @Override
    public CommonResult<String> saveFields(List<DataCollectionFieldSaveReqVO> fieldList, Long dcId, String newVersionFlag) {
        List<DataCollectionFieldDO> updateList = new ArrayList<>();
        List<DataCollectionFieldDO> insertList = new ArrayList<>();
        if(fieldList == null)
            fieldList = new ArrayList<>();
        if("1".equals(newVersionFlag)){
            //新版本，所有字段都做插入处理
            for (DataCollectionFieldSaveReqVO field : fieldList) {
                DataCollectionFieldDO entity = BeanUtils.toBean(field, DataCollectionFieldDO.class);
                entity.setId(null);
                entity.setDataCollectionId(dcId);
                insertList.add(entity);
            }
            if(!insertList.isEmpty())
                dataCollectionFieldMapper.insertBatch(insertList);
            return CommonResult.success("保存成功");
        }
        for(DataCollectionFieldSaveReqVO field : fieldList){
            DataCollectionFieldDO entity = BeanUtils.toBean(field, DataCollectionFieldDO.class);
            entity.setDataCollectionId(dcId);
            if(field.getId() != null)
                updateList.add(entity);
            else
                insertList.add(entity);
        }
        if(!insertList.isEmpty())
            dataCollectionFieldMapper.insertBatch(insertList);
        if(!updateList.isEmpty())
            dataCollectionFieldMapper.updateBatch(updateList);
        return CommonResult.success("保存成功");
    }


    @Override
    public CommonResult<String> deleteFields(String deleteFieldIds, Long dcId) {
        if(ObjectUtils.isEmpty(deleteFieldIds))
            return CommonResult.success("");
        List<Long> ids = Arrays.asList(deleteFieldIds.split(",")).stream().map(Long::parseLong).toList();
        dataCollectionFieldMapper.deleteByIds(ids);
        return CommonResult.success("删除成功");
    }

    @Override
    public DataCollectionFieldRespVO createDataCollectionField(DataCollectionFieldSaveReqVO createReqVO) {
        // 插入
        DataCollectionFieldDO dataCollectionField = BeanUtils.toBean(createReqVO, DataCollectionFieldDO.class);
        dataCollectionFieldMapper.insert(dataCollectionField);
        // 返回
        return BeanUtils.toBean(dataCollectionField, DataCollectionFieldRespVO.class);
    }

    @Override
    public void updateDataCollectionField(DataCollectionFieldSaveReqVO updateReqVO) {
        // 校验存在
        validateDataCollectionFieldExists(updateReqVO.getId());
        // 更新
        DataCollectionFieldDO updateObj = BeanUtils.toBean(updateReqVO, DataCollectionFieldDO.class);
        dataCollectionFieldMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataCollectionField(Long id) {
        // 校验存在
        validateDataCollectionFieldExists(id);
        // 删除
        dataCollectionFieldMapper.deleteById(id);
    }

    @Override
        public void deleteDataCollectionFieldListByIds(List<Long> ids) {
        // 校验存在
        validateDataCollectionFieldExists(ids);
        // 删除
        dataCollectionFieldMapper.deleteByIds(ids);
        }

    private void validateDataCollectionFieldExists(List<Long> ids) {
        List<DataCollectionFieldDO> list = dataCollectionFieldMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DATA_COLLECTION_FIELD_NOT_EXISTS);
        }
    }

    private void validateDataCollectionFieldExists(Long id) {
        if (dataCollectionFieldMapper.selectById(id) == null) {
            throw exception(DATA_COLLECTION_FIELD_NOT_EXISTS);
        }
    }

    @Override
    public DataCollectionFieldDO getDataCollectionField(Long id) {
        return dataCollectionFieldMapper.selectById(id);
    }

    @Override
    public PageResult<DataCollectionFieldDO> getDataCollectionFieldPage(DataCollectionFieldPageReqVO pageReqVO) {
        return dataCollectionFieldMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DataCollectionFieldDO> queryEffectiveListByDataCollectionId(Long dataCollectionId) {
        LambdaQueryWrapper<DataCollectionFieldDO> queryWrapper = new LambdaQueryWrapper<DataCollectionFieldDO>()
                .eq(DataCollectionFieldDO::getDataCollectionId, dataCollectionId)
                .eq(DataCollectionFieldDO::getCancelFlag, 0)
                .orderByAsc(DataCollectionFieldDO::getSortNo);
        return dataCollectionFieldMapper.selectList(queryWrapper);
    }
}