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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.res.entity.LmsLabel;
import com.patzn.lims.res.mapper.LmsLabelMapper;
import com.patzn.lims.res.service.ILmsLabelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhaokai
 * @since 2019-08-26
 */
@Service
public class LmsLabelServiceImpl extends BaseServiceImpl<LmsLabelMapper, LmsLabel> implements ILmsLabelService {


    @Override
    public Page<LmsLabel> page(Page<LmsLabel> page, LmsLabel lmsLabel) {
        QueryWrapper wrapper = Wrappers.query(lmsLabel);
        // 倒序排列
        wrapper.orderBy(true,true,"ctime", false);
        return this.page(page, wrapper);
    }


    @Override
    public List<LmsLabel> list(LmsLabel lmsLabel) {
        return this.list(Wrappers.query(lmsLabel));
    }

    @Override
    public Boolean saveOrUpdateObj(LmsLabel label, Account account) {
        PtAssert.fail(label == null, "标签不能为空!");
        PtAssert.fail(label.getType() == null, "请选择标签类型!");
        PtAssert.fail(StringUtils.isBlank(label.getCode()), "标签内容不能为空!");
        // 每种类型只能添加一个
        QueryWrapper wrapper = Wrappers.query(label).eq("type", label.getType().getValue());
        if (label.getId() != null) {
            wrapper.ne("id", label.getId());
        }
        int count = count(wrapper);
        PtAssert.fail(count > 0, "已经存在: " + label.getType().getDisplay());
        if (label.getId() == null) {
            // 新增
            label.setUid(account.getUserId());
            label.setUname(account.getUserName());
            label.setCtime(new Date());
            label.setDeleted(0);
            save(label);
        } else {
            // 更新
            label.setLid(account.getUserId());
            label.setLname(account.getUserName());
            label.setLtime(new Date());
            updateById(label);
        }
        return true;
    }

    @Override
    public String search(Integer type, Account account) {
        PtAssert.fail(type == null, "标签类型不能为空!");
        List<LmsLabel> codes = list(Wrappers.query(new LmsLabel()).eq("type", type).last("limit 1"));
        if (CollectionUtils.isEmpty(codes)) {
            // 空的查询企业 ID 是 0 的
            List<LmsLabel> codesAdmin = baseMapper.selectObj(type, 0L);
            PtAssert.fail(CollectionUtils.isEmpty(codesAdmin), "请联系管理员配置标签代码！");
            return codesAdmin.get(0).getCode();
        }
        return codes.get(0).getCode();
    }
}
