/*
 * Author: Zev
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.trouble.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.gpsboot.common.Constant;
import com.tofly.pojo.trouble.dto.ToubletypeDto;
import com.tofly.pojo.trouble.vo.ToubletypeVo;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.trouble.ToubletypeMapper;
import com.tofly.gpsboot.service.trouble.TroubleService;
import com.tofly.pojo.trouble.Toubletype;
import com.tofly.gpsboot.service.trouble.ToubletypeService;
import com.tofly.pojo.trouble.Trouble;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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


/**
 * 隐患原因分类信息表：TF_YWPN_TOUBLETYPE_D
 *
 * @author admin
 * @date Thu Mar 18 00:00:00 CST 2021
 */
@Service("toubletypeService")
public class ToubletypeServiceImpl extends ServiceImpl<ToubletypeMapper, Toubletype> implements ToubletypeService {

    @Autowired
    private TroubleService troubleService;

    @Override
    public List<ToubletypeVo> viewConversion(List<Toubletype> infoList) {
        /// 无转换类型
        return JSONArray.parseArray(JSON.toJSONString(infoList), ToubletypeVo.class);
    }

    @Override
    public Page<ToubletypeVo> getToubletypePage(Page page, ToubletypeDto parDto) {
        Toubletype toubletype = JSON.parseObject(JSON.toJSONString(parDto),Toubletype.class);
        QueryWrapper<Toubletype> wrapper = new QueryWrapper();
        String name = parDto.getName();
        if(!StringUtils.isEmpty(name)){
            wrapper.like("NAME",name);
        }
        wrapper.setEntity(toubletype);
        Page infoPageList = this.page(page, wrapper);
        infoPageList.setRecords(this.viewConversion(infoPageList.getRecords()));
        return infoPageList;
    }

    @Override
    public void deleteTroubleTypeInfo(String idLists) throws BusinessException {
        // 判断当前是否有关联数据 工地
        List<Long> longList = Arrays.stream(idLists.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        List<Trouble> list = troubleService.list(new QueryWrapper<Trouble>().lambda().in(Trouble::getTypeId, longList));
        if(null!=list && list.size()>0){
            throw new BusinessException(Constant.TROUBLE_TYPE_NO_DELETE_CODE,Constant.TROUBLE_TYPE_NO_DELETE);
        }else {
            this.removeByIds(longList);
        }
    }
}
