package com.tuoheng.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuoheng.common.common.BaseQuery;
import com.tuoheng.common.common.BaseServiceImpl;
import com.tuoheng.common.utils.CommonUtils;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.system.entity.Tenant;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.entity.UserRole;
import com.tuoheng.system.mapper.TenantMapper;
import com.tuoheng.system.mapper.UserMapper;
import com.tuoheng.system.mapper.UserRoleMapper;
import com.tuoheng.system.query.TenantQuery;
import com.tuoheng.system.service.ITenantService;
import com.tuoheng.system.service.IUserRoleService;
import com.tuoheng.system.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 后台租户管理表 服务实现类
 * </p>
 *
 * @author
 * @since 2022-12-30
 */
@Service
public class TenantServiceImpl implements ITenantService  {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private TenantMapper tenantMapper;

    public JsonResult getList(BaseQuery query) {
        TenantQuery tenantQuery = (TenantQuery) query;
        // 查询条件
        QueryWrapper<Tenant> queryWrapper = new QueryWrapper<>();
        // 角色名称
        if (!StringUtils.isEmpty(tenantQuery.getName())) {
            queryWrapper.like("name", tenantQuery.getName());
        }
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");

        // 查询分页数据
        IPage<Tenant> page = new Page<>(tenantQuery.getPage(), tenantQuery.getLimit());

        return JsonResult.success(page);
    }

    @Override
    public JsonResult edit(Tenant entity) {
        return null;
    }


    public JsonResult add(Tenant tenant,User user){
        Tenant tenantHas= this.selectByTenantCode(tenant.getCode());
        if (tenantHas!=null){
            return JsonResult.error("租户已存在！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("mark",1);
        queryWrapper.eq("username",user.getUsername());
        int count = userMapper.selectCount(queryWrapper);
        if(count>0){
            return JsonResult.error("用户已存在！");
        }
        user.setTenantId(0);
        user.setPassword(CommonUtils.password(user.getPassword())).setCreateTime(new Date());
        userMapper.insert(user);
        int userId = user.getId();
        userRoleMapper.insert(new UserRole().setRoleId(1).setUserId(userId));
        tenant.setUserId(userId).setCreateTime(new Date());
        tenantMapper.insert(tenant);
        return JsonResult.success();
    }
    public JsonResult editByCenter(Tenant tenant,User user){
        Tenant tenantHas= this.selectByTenantCode(tenant.getCode());
        if (tenantHas==null){
            return JsonResult.error("租户不存在！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("mark",1);
        queryWrapper.eq("id",tenantHas.getUserId());
        User userHas = userMapper.selectOne(queryWrapper);
        if(userHas==null){
            return JsonResult.error("用户不存在！");
        }
        user.setTenantId(0);
        user.setUpdateTime(new Date());
        user.setPassword(CommonUtils.password(userHas.getPassword())).setId(userHas.getId());
        userMapper.updateById(user);
        int userId = user.getId();
        tenant.setUserId(userId).setUpdateTime(new Date());
        tenantMapper.updateById(tenant);
        return JsonResult.success();
    }

    public JsonResult delByCenter(String code){
        Tenant tenantHas= this.selectByTenantCode(code);
        if (tenantHas==null){
            return JsonResult.error("租户不存在！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("mark",1);
        queryWrapper.eq("id",tenantHas.getUserId());
        User userHas = userMapper.selectOne(queryWrapper);
        if(userHas==null){
            return JsonResult.error("用户不存在！");
        }
        userMapper.deleteById(userHas.getId());

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("user_id",userHas.getId());
        userRoleMapper.delete(queryWrapper1);

        tenantMapper.deleteById(tenantHas.getId());
        return JsonResult.success();
    }

    public JsonResult updatePasswordByCenter(String code,String password){
        Tenant tenantHas= this.selectByTenantCode(code);
        if (tenantHas==null){
            return JsonResult.error("租户不存在！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("mark",1);
        queryWrapper.eq("id",tenantHas.getUserId());
        User userHas = userMapper.selectOne(queryWrapper);
        if(userHas==null){
            return JsonResult.error("用户不存在！");
        }
        userHas.setPassword(CommonUtils.password(password)).setUpdateTime(new Date());
        userMapper.updateById(userHas);
        return JsonResult.success();
    }
    @Override
    public JsonResult deleteByIds(Integer[] tenantIds) {
        return null;
    }


    public int getCurrentTenantId() {
        //try {
            User principal = (User) SecurityUtils.getSubject().getPrincipal();
            //principal.setTenantId(principal.getTenantId() == null ? -1 : principal.getTenantId());
            if (principal.getTenantId() == 0) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("mark", 1);
                queryWrapper.eq("user_id", principal.getId());
                //Tenant tenant = tenantMapper.selectOne(queryWrapper);
                return tenantMapper.selectOne(queryWrapper).getId();
            }
            return principal.getTenantId();
        /*}catch (Exception e){
            e.printStackTrace();
            return -1;
        }*/
    }

    public int getCurrentUserId() {
        User principal = (User) SecurityUtils.getSubject().getPrincipal();
        return principal.getId();
    }

    @Override
    public Tenant selectByTenantCode(String code) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("code",code);
        wrapper.eq("mark",1);
       List list = tenantMapper.selectList(wrapper);
       if(list.size()>0){
           return (Tenant) list.get(0);
       }
        return null;
    }

}
