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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.BaseServiceImpl;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.res.entity.LmsBaseDict;
import com.patzn.lims.res.mapper.LmsBaseDictMapper;
import com.patzn.lims.res.service.ILmsBaseDictService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-08-28
 */
@Service
public class LmsBaseDictServiceImpl extends BaseServiceImpl<LmsBaseDictMapper, LmsBaseDict> implements ILmsBaseDictService {


    @Override
    public Page<LmsBaseDict> page(Page<LmsBaseDict> page, LmsBaseDict lmsBaseDict) {
        QueryWrapper wrapper = Wrappers.query(lmsBaseDict);
        if (null != lmsBaseDict.getType()) {
            wrapper.like("type", lmsBaseDict.getType());
            lmsBaseDict.setType(null);
        }
        if (StringUtils.isNotBlank(lmsBaseDict.getName())) {
            wrapper.like("name", lmsBaseDict.getName());
            lmsBaseDict.setName(null);
        }
        wrapper.orderBy(true,true,"type").orderBy(true,true,"sort");
        return page(page, wrapper);
    }


    @Override
    public List<LmsBaseDict> getDictAllTree(String name) {
        return list(Wrappers.query(new LmsBaseDict()).select("id,pid,name")
                .like(StringUtils.isNotEmpty(name), "name", name)
                .eq("status", 1));
    }

    @Override
    public LmsBaseDict getDictByNameType(LmsBaseDict dict) {
        PtAssert.fail(StringUtils.isBlank(dict.getName()), "字典名称不能为空");
        PtAssert.fail(StringUtils.isBlank(dict.getType()), "字典类别不能为空");
        return super.getOne(Wrappers.query(new LmsBaseDict()).eq("name", dict.getName()).eq("type", dict.getType()).eq("status", 1).last("LIMIT 1"));
    }

    @Override
    public List<LmsBaseDict> getDictQuery(LmsBaseDict dict) {
        PtAssert.fail(StringUtils.isBlank(dict.getType()), "字典类别不能为空");
        return super.list(Wrappers.query(new LmsBaseDict()).
                like(StringUtils.isNotBlank(dict.getName()), "name", dict.getName()).eq(null != dict.getStatus(), "status", dict.getStatus()).eq("type", dict.getType()));
    }

    @Override
    public List<LmsBaseDict> getDictAllByClass(String classType, String name) {
        return list(Wrappers.query(new LmsBaseDict()).select("id,pid,name,code,remark")
                .eq(StringUtils.isNotEmpty(classType), "type", classType)
                .eq(StringUtils.isNotEmpty(name), "name", name)
                .eq("status", 1).orderBy(true,true,"sort"));
    }

    @Override
    public List<LmsBaseDict> getDictDetailByClass(String name) {
        return list(Wrappers.query(new LmsBaseDict()).select("id,pid,name,code")
                .eq(StringUtils.isNotEmpty(name), "type", name)
                .eq("status", 1).orderBy(true,true,"sort"));
    }


    @Override
    public LmsBaseDict getByKey(String key) {
        return baseMapper.selectByKey(key);
    }


    @Override
    public String getCode(String type, String name) {
        LmsBaseDict baseDict = super.getOne(Wrappers.query(new LmsBaseDict()).eq("type", type)
                .eq("name", name).last("LIMIT 1"));
        PtAssert.fail(StringUtils.isBlank(baseDict.getCode()),
                String.format("枚举类型{%s}，属性{%s} 不存在编码值，请联系管理员", type, name));
        return baseDict.getCode();
    }

    @Override
    public String getCodeByKeyword(String type, String key) {
        LmsBaseDict baseDict = super.getOne(Wrappers.query(new LmsBaseDict()).eq("type", type)
                .eq("key", key).eq("status", 1).last("LIMIT 1"));
        if (null != baseDict && StringUtils.isNotEmpty(baseDict.getCode())) {
            return baseDict.getCode();
        }
        return "";
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean initBaseDict(Long companyId) {
        List<LmsBaseDict> bdList = baseMapper.selectBaseDictList();
        if (CollectionUtils.isEmpty(bdList)) {
            return true;
        }
        super.remove(Wrappers.query(new LmsBaseDict()).eq("company_id", companyId));
        return super.saveBatch(bdList.stream().map(e -> {
            e.setId(null);
            e.setCompanyId(companyId);
            return e;
        }).collect(toList()));
    }


    @Override
    public List<LmsBaseDict> getDictTypeNoRepeat() {
        return baseMapper.getDictTypeNoRepeat(LoginHelper.getAccount().getCompanyId());
    }

    @Override
    public List<LmsBaseDict> getNoRepeatlByType(String type) {
        return super.list(Wrappers.query(new LmsBaseDict()).select("name", "type").groupBy("name,type"));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean baseDictImport(MultipartFile file) {
        return false;
    }

    @Override
    public List<LmsBaseDict> getNameByType(String type) {
        return super.list(Wrappers.query(new LmsBaseDict()).select("name,type").eq("type", type).eq("status", 1));
    }

    @Override
    public void export(HttpServletResponse response, Long currentCompanyId) {

    }

    @Override
    public List<List<LmsBaseDict>> listDict(String[] classTypeList) {
        if (ArrayUtils.isEmpty(classTypeList)) {
            return new ArrayList<>();
        }
        List<List<LmsBaseDict>> lists = new ArrayList<>();
        for (String classType : classTypeList) {
            lists.add(getDictAllByClass(classType, null));
        }
        return lists;
    }
}
