package ${packageName}.service.impl;

import model.domain.core.com.my.common.LoginUser;
import exception.com.my.common.ServiceException;
import utils.com.my.common.StringUtils;
import bean.utils.com.my.common.BeanValidators;
import uuid.utils.com.my.common.SnowflakeIdWorker;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import java.util.List;
import cache.com.my.bus.BusCache;
import org.apache.commons.collections4.CollectionUtils;
#foreach ($column in $columns)
        #if($column.javaField == 'createTime' || $column.javaField == 'updateTime')
import utils.com.my.common.DateUtils;
            #break
        #end
    #end
#if($table.sub)
import ${packageName}.domain.${subClassName};
    #end
import ${packageName}.mapper.${ClassName}Mapper;
import ${packageName}.domain.${ClassName};
import ${packageName}.service.I${ClassName}Service;

/**
 * ${functionName}Service业务层处理
 *
 * @author ${author}
 * @date ${datetime}
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ${ClassName}ServiceImpl implements I${ClassName}Service {

    private final ${ClassName}Mapper ${className}Mapper;

    private final Validator validator;

    private final BusCache busCache;
    /**
     * 查询${functionName}
     *
     * @param ${pkColumn.javaField} ${functionName}主键
     * @return ${functionName}
     */
    @Override
    public ${ClassName} selectBy${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}) {
        return ${className}Mapper.selectBy${pkColumn.capJavaField}(${pkColumn.javaField});
    }

    /**
     * 查询${functionName}列表
     *
     * @param ${className} ${functionName}
     * @return ${functionName}
     */
    @Override
    public List<${ClassName}> selectList(${ClassName} ${className}) {
        return ${className}Mapper.selectList(${className});
    }

    /**
     * 新增${functionName}
     *
     * @param ${className} ${functionName}
     * @return 结果
     */
        #if($table.sub)
        @Transactional
        #end
    @Override
    public int insert(${ClassName} ${className}) {
        #foreach ($column in $columns)
            #if($column.javaField == 'id')
                ${className}.setId(new SnowflakeIdWorker(0, 0).nextId());
            #end
            #if($column.javaField == 'createTime')
                ${className}.setCreateTime(DateUtils.getNowDate());
            #end
            #if($column.javaField == 'updateTime')
                ${className}.setUpdateTime(DateUtils.getNowDate());
            #end
            #if($column.javaField == 'status')
                ${className}.setStatus(0);
            #end
        #end
        #if($table.sub)
            int rows = ${className}Mapper.insert${ClassName}(${className});
            insert${subClassName}(${className});
            return rows;
        #else
            return ${className}Mapper.insert(${className});
        #end
    }

    /**
     * 修改${functionName}
     *
     * @param ${className} ${functionName}
     * @return 结果
     */
    #if($table.sub)
    @Transactional
    #end
    @Override
    public int update(${ClassName} ${className}) {
        #foreach ($column in $columns)
            #if($column.javaField == 'updateTime')
                ${className}.setUpdateTime(DateUtils.getNowDate());
            #end
        #end
        #if($table.sub)
                ${className}Mapper.delete${subClassName}By${subTableFkClassName}(${className}.get${pkColumn.capJavaField}())
            ;
            insert${subClassName}(${className});
        #end
        return ${className}Mapper.update(${className});
    }

    /**
     * 批量删除${functionName}
     *
     * @param ${pkColumn.javaField}s 需要删除的${functionName}主键
     * @return 结果
     */
    #if($table.sub)
    @Transactional
    #end
    @Override
    public int deleteBy${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s) {
        #if($table.sub)
                ${className}Mapper.deleteBy${subTableFkClassName}s(${pkColumn.javaField}s);
        #end
        return ${className}Mapper.deleteBy${pkColumn.capJavaField}s(${pkColumn.javaField}s);
    }

    /**
     * 删除${functionName}信息
     *
     * @param ${pkColumn.javaField} ${functionName}主键
     * @return 结果
     */
    #if($table.sub)
    @Transactional
    #end
    @Override
    public int deleteBy${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}) {
        #if($table.sub)
                ${className}Mapper.deleteBy${subTableFkClassName}(${pkColumn.javaField});
        #end
        return ${className}Mapper.deleteBy${pkColumn.capJavaField}(${pkColumn.javaField});
    }

    /**
     * 逻辑删除${functionName}信息
     *
     * @param ${pkColumn.javaField} ${functionName}主键
     * @return 结果
     */
    #if($table.sub)
    @Transactional
    #end
    @Override
    public int logicDelete(${pkColumn.javaType} ${pkColumn.javaField}) {

        return ${className}Mapper.logicDelete(${pkColumn.javaField});
    }

    #if($table.sub)
    /**
     * 新增${subTable.functionName}信息
     *
     * @param ${className} ${functionName}对象
     */
    public void insert${subClassName}(${ClassName} ${className}) {
        List<${subClassName}> ${subclassName}List = ${className}.get${subClassName}List();
        ${pkColumn.javaType} ${pkColumn.javaField} = ${className}.get${pkColumn.capJavaField}();
        if (StringUtils.isNotNull(${subclassName}List)) {
            List<${subClassName}> list = new ArrayList<${subClassName}>();
            for (${subClassName} ${subclassName} :${subclassName}List)
            {
                ${subclassName}.set${subTableFkClassName}(${pkColumn.javaField});
                list.add(${subclassName});
            }
            if (list.size() > 0) {
                    ${className}Mapper.batch(list);
            }
        }
    }

    #end
    /**
     * 导入${functionName}数据
     *
     * @param ${className}List ${functionName}数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param loginUser 操作用户
     * @return 结果
     */
    @Override
    public String import${ClassName}(List<${ClassName}> ${className}List, Boolean isUpdateSupport, LoginUser loginUser) {
        if (CollectionUtils.isEmpty(${className}List)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (${ClassName} ${className} : ${className}List) {
            try {

                BeanValidators.validateWithException(validator, ${className});
                ${className}.setId(new SnowflakeIdWorker(0, 0).nextId());
                ${className}.setCreateTime(DateUtils.getNowDate());
                ${className}.setUpdateTime(DateUtils.getNowDate());
                ${className}.setCreateBy(loginUser.getUserId().toString());
                ${className}.setDeptId(loginUser.getDeptId());
                ${className}.setCustomsCode(busCache.getOrgDeptById(loginUser.getDeptId()).getCustomsCode());
                ${className}.setStatus(0);
                ${className}Mapper.insert(${className});
                successNum++;
                successMsg.append("<br/>" + successNum + "、 " + loginUser.getUsername() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、" + loginUser.getUsername() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
