package com.huiju.estateagents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.entity.SysOrgParams;
import com.huiju.estateagents.mapper.SysOrgParamsMapper;
import com.huiju.estateagents.service.ISysOrgParamsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织参数配置表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-01
 */
@Service
public class SysOrgParamsServiceImpl extends ServiceImpl<SysOrgParamsMapper, SysOrgParams> implements ISysOrgParamsService {
    @Autowired
    SysOrgParamsMapper sysOrgParamsMapper;

    @Override
    public SysOrgParams getParamByCode(String paramCode, Integer orgId) {
        QueryWrapper<SysOrgParams> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("param_code", paramCode);
        queryWrapper.last("limit 1");

        return sysOrgParamsMapper.selectOne(queryWrapper);
    }

    /**
     * 从模板中导入系统参数, 支持多次导入
     * 已经导入的不会再次导入
     * @param orgId
     * @return
     */
    @Override
    public boolean importParamsFromTemplate(Integer orgId) {
        // 查询模板列表, org 为 0 代表为模板数据
        QueryWrapper<SysOrgParams> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", 0);

        List<SysOrgParams> tpls = sysOrgParamsMapper.selectList(queryWrapper);
        List<SysOrgParams> willSave = new ArrayList<>();

        for(SysOrgParams param: tpls) {
            QueryWrapper<SysOrgParams> query = new QueryWrapper<>();
            query.eq("org_id", orgId);
            query.eq("param_code", param.getParamCode());

            // 使用 count 查询是否该参数已经存在
            // 如果存在, 则不处理
            int count = this.count(query);

            if (count == 0) {
                param.setParamId(null);
                param.setOrgId(orgId);
                willSave.add(param);
            }
        }

        if (willSave.size() > 0) {
            return this.saveBatch(willSave);
        }

        return true;
    }
}
