/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.dispatch.service.impl;

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.common.oauth.util.SecurityUtils;
import com.tofly.dispatch.dto.DispatchExpertQuery;
import com.tofly.dispatch.entity.DispatchExpert;
import com.tofly.dispatch.entity.DispatchExpertR;

import com.tofly.dispatch.service.DispatchExpertRService;
import com.tofly.dispatch.service.DispatchExpertService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.dispatch.mapper.DispatchExpertMapper;


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

/**
 * 专家库管理
 *
 * @author admin
 * @date Thu Nov 10 00:00:00 CST 2022
 */
@Service("dispatchexpertService")
public class DispatchExpertServiceImpl extends ServiceImpl<DispatchExpertMapper, DispatchExpert> implements DispatchExpertService {

  @Autowired
  private DispatchExpertRService dispatchExpertRService;
    public boolean selectByName(String expertName, long id) {
        QueryWrapper<DispatchExpert> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("EXPERT_NAME", expertName);
        if (id>0) {
            queryWrapper.ne("ID", id);
        }
        Integer count = baseMapper.selectCount(queryWrapper);

        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean saveDispatchExpert(DispatchExpert dispatchExpert, boolean isAdd) {
        if(isAdd){
           if(!selectByName(dispatchExpert.getExpertName(),0L)){
               throw new RuntimeException("专家库已经存在，不能新建");
           }
          return super.save(dispatchExpert);

        }else{
            if(!selectByName(dispatchExpert.getExpertName(),dispatchExpert.getId())){
                throw new RuntimeException("专家库已经存在，不能修改");
            }
            return super.updateById(dispatchExpert);

        }

    }

    @Override
    public boolean deleteByIds(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        QueryWrapper<DispatchExpertR> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("DISPATCH_EXPERT_ID", list);

        Integer count_check = dispatchExpertRService.count(queryWrapper);
        if (count_check > 0) {
            throw new RuntimeException("专家在调度方案中使用到，不能删除");
        }
        return this.removeByIds(list);
    }

    @Override
    public Page<DispatchExpert> getPageData(Page page, DispatchExpertQuery query) {

        if (query.getStartTime() != null && query.getStartTime() != null) {
            if (query.getStartTime().getTime() > query.getEndTime().getTime()) {
                throw new RuntimeException("开始时间不能大于结束时间");
            }
        }

        return this.baseMapper.getPageData(page, query);
    }
}
