package com.zhongzheng.framework.web.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.zhongzheng.common.core.domain.entity.SysUser;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.SecurityUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.framework.mybatisplus.CustomTenantLineHandler;
import com.zhongzheng.modules.system.bo.SysTenantAddBo;
import com.zhongzheng.modules.system.bo.SysTenantEditBo;
import com.zhongzheng.modules.system.bo.SysTenantQueryBo;
import com.zhongzheng.modules.system.domain.SysTenant;
import com.zhongzheng.modules.system.mapper.SysTenantMapper;
import com.zhongzheng.modules.system.service.ISysTenantService;
import com.zhongzheng.modules.system.service.ISysUserService;
import com.zhongzheng.modules.system.vo.SysTenantVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统商户Service业务层处理
 *
 * @author hjl
 * @date 2021-08-03
 */
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private ISysUserService userService;

    @Override
    public SysTenantVo queryById(Long tenantId){
        SysTenant db = this.baseMapper.selectById(tenantId);
        return BeanUtil.toBean(db, SysTenantVo.class);
    }

    @Override
    public List<SysTenantVo> queryList(SysTenantQueryBo bo) {
        LambdaQueryWrapper<SysTenant> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStatus() != null, SysTenant::getStatus, bo.getStatus());
        lqw.like(StrUtil.isNotBlank(bo.getTenantName()), SysTenant::getTenantName, bo.getTenantName());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<SysTenantVo> entity2Vo(Collection<SysTenant> collection) {
        List<SysTenantVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, SysTenantVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<SysTenant> page = (Page<SysTenant>)collection;
            Page<SysTenantVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(SysTenantAddBo bo) {
        return this.createTenant(bo);
    }

    @Override
    public Boolean updateByEditBo(SysTenantEditBo bo) {
        SysTenant update = BeanUtil.toBean(bo, SysTenant.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysTenant entity){
        //TODO 做一些数据校验,如唯一约束
        if(checkNameUnique(entity)){
            throw new CustomException("公司名已存在");
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    private boolean checkNameUnique(SysTenant entity) {
        SysTenant info = getOne(new LambdaQueryWrapper<SysTenant>()
                .eq(SysTenant::getTenantName,entity.getTenantName())
                .last("limit 1"));
        if (Validator.isNotNull(info)) {
            return true;
        }
        return false;
    }


    public boolean createTenant(SysTenantAddBo bo){
        SysTenant add = BeanUtil.toBean(bo, SysTenant.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        this.save(add);
        //创建属于新公司的admin用户
        Long tenantId = add.getTenantId();
        ServletUtils.getRequestAttributes().getResponse().setHeader("TenantId",String.valueOf(tenantId));
        SysUser user = new SysUser();
        user.setUserName("admin");
        user.setNickName(bo.getTenantName());
        user.setCreateBy("SAAS-"+SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(bo.getPassword()));
        userService.insertUser(user);
        return true;
    }

}
