package cn.cslg.report.service.business.InvalidReReport;

import cn.cslg.report.common.model.dto.invalidReReport.InvalidReasonFieldDTO;
import cn.cslg.report.common.model.dto.invalidReReport.InvalidReasonFieldSortDTO;
import cn.cslg.report.common.model.dto.invalidReReport.InvalidReasonFieldVO;
import cn.cslg.report.common.utils.Response;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.invalidReReport.*;
import cn.cslg.report.mapper.InvalidReReport.InvalidReasonFiledMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class InvalidReasonFieldService extends ServiceImpl<InvalidReasonFiledMapper, InvalidReasonField> {
    private final LoginUtils loginUtils;
    private final InvalidReasonFieldValueService invalidReasonFieldValueService;

    public String addOrUpdate(InvalidReasonFieldDTO invalidReasonFieldDTO) {
        //根据字段名或字段键查询
        LambdaQueryWrapper<InvalidReasonField> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w->w.eq(InvalidReasonField::getFieldKey, invalidReasonFieldDTO.getFieldKey())
                .or()
                .eq(InvalidReasonField::getFieldName, invalidReasonFieldDTO.getFieldName()))
                .eq(InvalidReasonField::getReportId,invalidReasonFieldDTO.getReportId());
        if (invalidReasonFieldDTO.getId() != null) {
            wrapper.ne(InvalidReasonField::getId,invalidReasonFieldDTO.getId());
        }
        List<InvalidReasonField> invalidReasonFields = this.list(wrapper);
        if (invalidReasonFields.size() > 0) {
            return Response.error("自定义字段名或键值已存在");
        }
        InvalidReasonField invalidReasonField = new InvalidReasonField();
        if (invalidReasonFieldDTO.getId() != null) {
            invalidReasonField = this.getById(invalidReasonFieldDTO.getId());
            invalidReasonField.setFieldKey(invalidReasonFieldDTO.getFieldKey());
            invalidReasonField.setFieldName(invalidReasonFieldDTO.getFieldName());
            invalidReasonField.updateById();
            return Response.success("修改自定义字段成功");
        } else {
            LambdaQueryWrapper<InvalidReasonField> wrapper1 =new LambdaQueryWrapper<>();
            wrapper1.eq(InvalidReasonField::getReportId,invalidReasonFieldDTO.getReportId());
            int sort= Long.valueOf(this.count(wrapper1)).intValue()+1;
            BeanUtils.copyProperties(invalidReasonFieldDTO, invalidReasonField);
            invalidReasonField.setCreateId(loginUtils.getId());
            invalidReasonField.setFieldState(invalidReasonFieldDTO.getFieldState());
            invalidReasonField.setFieldSort(sort);
            invalidReasonField.insert();
            return Response.success("添加自定义字段成功");
        }

    }


    public String updateSort(List<InvalidReasonFieldSortDTO> invalidReasonFieldDTOs) {
      //过滤获得所有自定义字段的id
        List<Integer> ids =invalidReasonFieldDTOs.stream().map(InvalidReasonFieldSortDTO::getId).collect(Collectors.toList());
           if(ids.size()==0){
               return Response.error("无自定义字段");
           }
           //根据自定义字段id批量查询自定义字段
        LambdaQueryWrapper<InvalidReasonField> wrapper =new LambdaQueryWrapper<>();
           wrapper.in(InvalidReasonField::getId,ids);
           List<InvalidReasonField> invalidReasonFields =this.list(wrapper);
           invalidReasonFields.forEach(item->{

               InvalidReasonFieldSortDTO   invalidReasonFieldDTO=invalidReasonFieldDTOs.stream()
                       .filter(tem->item.getId().equals(tem.getId())).findFirst().orElse(new InvalidReasonFieldSortDTO());
               if(invalidReasonFieldDTO.getFieldSort()!=null){
                   item.setFieldSort(invalidReasonFieldDTO.getFieldSort());
               }
               if(invalidReasonFieldDTO.getFieldState()!=null){
                   item.setFieldState(invalidReasonFieldDTO.getFieldState());
               }
           });
           this.updateBatchById(invalidReasonFields);
           return  Response.success("变更顺序成功");
    }





    public String queryFields(Integer reportId) {
        //根据报告id查询
        LambdaQueryWrapper<InvalidReasonField> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InvalidReasonField::getReportId, reportId);
        List<InvalidReasonField> invalidReasonFields = this.list(wrapper);
        List<InvalidReasonFieldVO> invalidReasonFieldVOS = new ArrayList<>();
        invalidReasonFields.forEach(item -> {
            InvalidReasonFieldVO invalidReasonFieldVO = new InvalidReasonFieldVO();
            BeanUtils.copyProperties(item, invalidReasonFieldVO);
            invalidReasonFieldVOS.add(invalidReasonFieldVO);
        });
        return Response.success(invalidReasonFieldVOS);
    }

    public String deleteFields(List<Integer> fieldIds) {
        if(fieldIds==null||fieldIds.size()<=0){
            return Response.error("请选择自定义栏位");
        }
        //先删除自定义字段值关联
        LambdaQueryWrapper<InvalidReasonFieldValue> wrapper =new LambdaQueryWrapper<>();
        wrapper.in(InvalidReasonFieldValue::getInvalidReasonFieldId,fieldIds);
        invalidReasonFieldValueService.remove(wrapper);
        this.removeByIds(fieldIds);
        return Response.success("删除成功");

    }

    //添加默认自定义栏位
    public void addDefault(Integer reportId) {
        //查询默认自定义栏位
        LambdaQueryWrapper<InvalidReasonField> wrapper =new LambdaQueryWrapper<>();
        wrapper.isNull(InvalidReasonField::getReportId);
        List<InvalidReasonField> invalidReasonFields=this.list(wrapper);

      for(int i=0;i<invalidReasonFields.size();i++){
          InvalidReasonField item=invalidReasonFields.get(i);
            item.setReportId(reportId);
            item.setId(null);
            item.setFieldSort(i+1);
        };
        this.saveBatch(invalidReasonFields);

    }
}