package com.patzn.lims.drug.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.patzn.lims.common.ObjectUtils;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.drug.entity.DrugSampleOos;
import com.patzn.lims.drug.eunms.OosStatusEnum;
import com.patzn.lims.drug.mapper.DrugSampleOosMapper;
import com.patzn.lims.drug.service.IDrugSampleOosService;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-03-13
 */
@Service
public class DrugSampleOosServiceImpl extends BaseServiceImpl<DrugSampleOosMapper, DrugSampleOos> implements IDrugSampleOosService {

    @Override
    public Page<DrugSampleOos> page(Page<DrugSampleOos> page, DrugSampleOos drugSampleOos) {
        QueryWrapper<DrugSampleOos> wrapper = Wrappers.<DrugSampleOos>query(drugSampleOos);
        return this.page(page, wrapper);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean registerSuggestion(DrugSampleOos oos, Account account) {
        PtAssert.fail(null == oos.getSampleId(),"样品ID不能为空");
        PtAssert.fail(StringUtils.isBlank(oos.getDescribable()),"不符合情况描述不能为空");
        PtAssert.fail(StringUtils.isBlank(oos.getSuggestion()),"处理意见不能为空");

        DrugSampleOos dbOos=  getOne(Wrappers.<DrugSampleOos>query().eq("sample_id",oos.getSampleId()).last("LIMIT 1"));
        if (null == dbOos){
            oos.setStatus(OosStatusEnum.SUBMIT);
            oos.setProgress(OosStatusEnum.SUBMIT);
            oos.setHandler(account.getUserName());
            oos.setHandlerId(account.getUserId());
            oos.setHandleTime(new Date());
            return save(oos);
        }
        oos.setId(dbOos.getId());
        return updateById(oos);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean submitOosRegister(Long[] ids, Account account) {
        ObjectUtils.checkNull(ids);
        List<DrugSampleOos> list = list(Wrappers.<DrugSampleOos>query().select("id").in("sample_id",ids));
        if (ids.length!=list.size()){
            PtAssert.fail("请选择待提交的数据");
        }
        DrugSampleOos sampleOos = new DrugSampleOos();
        sampleOos.setStatus(OosStatusEnum.CHECK);
        sampleOos.setProgress(OosStatusEnum.CHECK);
        return update(sampleOos,Wrappers.<DrugSampleOos>query().in("sample_id",ids));
    }
}
