package com.ruoyi.system.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.RestResponse;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.page.RespPage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdGenerator;
import com.ruoyi.system.domain.SysTenant;
import com.ruoyi.system.domain.columns.YjStore;
import com.ruoyi.system.domain.vo.ReqBusinessAddTenant;
import com.ruoyi.system.domain.vo.ReqSearchSysTenant;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysTenantMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.colums.YjStoreMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysTenantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private YjStoreMapper storeMapper;
    @Override
    public List<SysTenant> selectUserTenantList(String userId, String limitTenantUserId) {
        return baseMapper.selectUserTenantList(userId, limitTenantUserId);
    }

    @Override
    public boolean checkUserTenantInUse(String userId, String tenantId) {
        if (StringUtils.isAnyEmpty(userId, tenantId)) {
            return false;
        }
        SysTenant sysTenant = baseMapper.selectInUseUserTenant(userId, tenantId);
        return sysTenant != null;
    }

    /**
     * 查询树
     *
     * @param reqSearchSysTenant
     * @return
     */
    @Override
    public RestResponse searchList(ReqSearchSysTenant reqSearchSysTenant) {
        QueryWrapper qw = new QueryWrapper();
        if (StringUtils.isNotEmpty(reqSearchSysTenant.getTenantName())) {
            qw.like("tenant_name", reqSearchSysTenant.getTenantName());
        }
        if (StringUtils.isNotEmpty(reqSearchSysTenant.getContactName())) {
            qw.like("contact_name", reqSearchSysTenant.getContactName());
        }
        if (StringUtils.isNotEmpty(reqSearchSysTenant.getInUse())) {
            qw.eq("in_use", reqSearchSysTenant.getInUse());
        }
        if (StringUtils.isNoneEmpty(reqSearchSysTenant.getBeginTime(), reqSearchSysTenant.getEndTime())) {
            qw.between("end_time", reqSearchSysTenant.getBeginTime() + " 00:00:00", reqSearchSysTenant.getEndTime() + " 23:59:59");
        }
        qw.eq("delete_flag", "0");
        // 不展示超级管理租户
        qw.ne("super_tenant", "1");

        qw.orderByAsc("in_use");
        qw.orderByDesc("create_time");

        RespPage<SysTenant> page = new RespPage(reqSearchSysTenant.getPageNum(), reqSearchSysTenant.getPageSize());
        RespPage<SysTenant> listPage = page(page, qw);
        return new RestResponse().setData(listPage);
    }

    /**
     * 前端select
     *
     * @return
     */
    public RestResponse treeSelect() {
        QueryWrapper qw = new QueryWrapper();
        qw.select("tenant_id", "tenant_name");
        qw.eq("delete_flag", "0");
        qw.ne("super_tenant", 1);
        qw.orderByDesc("create_time");
        List<SysTenant> list = list(qw);
        return new RestResponse().setData(list);
    }


    /**
     * 详情
     *
     * @param tenantId
     * @return
     */
    public RestResponse detailById(Long tenantId) {
        if (null == tenantId) {
            return new  RestResponse();
        }
        SysTenant detailInfo = getById(tenantId);
        List<String> useDateList = Arrays.asList(DateUtil.format(detailInfo.getBeginTime(), "yyyy-MM-dd"), DateUtil.format(detailInfo.getEndTime(), "yyyy-MM-dd"));
        String[] useDateRange = useDateList.toArray(new String[useDateList.size()]);
        detailInfo.setUseDateRange(useDateRange);
        return new  RestResponse().setData(detailInfo);
    }

    /**
     * 添加
     *
     * @param reqBusinessAddTenant
     * @return
     */
    @Transactional
    public RestResponse addTenant(ReqBusinessAddTenant reqBusinessAddTenant) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        SysTenant sysTenant = new SysTenant();
        BeanUtils.copyProperties(reqBusinessAddTenant, sysTenant);

        sysTenant.setCreateUser(loginUser.getUserId());
        sysTenant.setBeginTime(DateUtil.parse(sysTenant.getBeginTime().toString()));//,"yyyy-MM-dd 00:00:00"
        sysTenant.setEndTime(DateUtil.parse(DateUtil.format(sysTenant.getEndTime(),"yyyy-MM-dd 23:59:59")));//,"yyyy-MM-dd 23:59:59"
        this.save(sysTenant);


            // 保存用户
            if (StringUtils.isAnyEmpty(reqBusinessAddTenant.getUsername(), reqBusinessAddTenant.getPassword())) {
                return RestResponse.failure("请求参数错误,请完善后重试");
            } else if (!reqBusinessAddTenant.getPassword().equals(reqBusinessAddTenant.getCheckPass())) {
                return RestResponse.failure(("新旧密码输入不一致,请稍后重试"));
            }
            // 校验账号是否已被注册
            boolean usernameUnique = UserConstants.UNIQUE.equals(userService.checkUserNameUnique(reqBusinessAddTenant.getUsername()));
            if (!usernameUnique) {
                return RestResponse.failure(("用户名已被注册,请修改后重新提交"));
            }
             SysUser sysUser = reqBusinessAddTenant.transferToSysUser();
            // 校验电话号是否已被注册
            boolean phoneUnique = UserConstants.UNIQUE.equals(userService.checkPhoneUnique(sysUser));
            if (!phoneUnique) {
                return RestResponse.failure(("用户手机号码已被注册,请修改后重新提交"));
            }

            //部门
            SysDept sysDept=new SysDept();
            sysDept.setTenantId(sysTenant.getTenantId());
            sysDept.setDeptName(sysTenant.getTenantName());
            sysDept.setDeptType("2");//默认为校区
            sysDept.setParentId(0l);
            sysDept.setAncestors("0");
            sysDept.setActivationDate(sysTenant.getBeginTime().toString());
            sysDept.setExpiryDate(sysTenant.getEndTime().toString());
            sysDept.setDeptId(IdGenerator.nextId());
            deptMapper.insertDept(sysDept);

            //门店
            YjStore store=new YjStore();
            store.setDeptId(sysDept.getDeptId());
            store.setStoreName(sysDept.getDeptName());
            storeMapper.insertYjStore(store);



            sysUser.setTenantId(sysTenant.getTenantId());
            sysUser.setCreateBy(loginUser.getUserId());
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
            sysUser.setDeptId(sysDept.getDeptId());
            sysUser.setStatus("0");
            sysUser.setRoleIds(new Long[]{100l});
            userService.insertUser(sysUser);

            sysDept.setLeaderId(sysUser.getUserId());
            deptMapper.updateDept(sysDept);


            //角色menu
//            roleMenuMapper.insertForNewTenant(sysTenant.getTenantId());

        return RestResponse.success();
    }

    /**
     * 更新
     *
     * @param sysTenant
     * @return
     */
    public RestResponse updateTenant(SysTenant sysTenant) {
        if (StringUtils.isEmpty(sysTenant.getTenantId())) {
            return RestResponse.failure("操作失败,请稍后重试");
        }
        SysTenant dbTenant = this.getById(sysTenant.getTenantId());
        if(null != dbTenant && dbTenant.getSuperTenant()) {
            return RestResponse.failure("此租户信息不允许变更");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        sysTenant.setBeginTime(DateUtil.parse(sysTenant.getBeginTime().toString()));
        sysTenant.setEndTime(DateUtil.parse(DateUtil.format(sysTenant.getEndTime(),"yyyy-MM-dd 23:59:59")));
        sysTenant.setLastUpdateUser(loginUser.getUserId());
        sysTenant.setLastUpdateTime(new Date());
        boolean updateTenant = this.updateById(sysTenant);
        if (updateTenant) {
            return RestResponse.success();
        } else {
            return RestResponse.failure("操作失败,请稍后重试");
        }
    }

    /**
     * 删除
     *
     * @param tenantIds
     * @return
     */
    public RestResponse deleteById(String[] tenantIds)
    {
        if (null == tenantIds || tenantIds.length == 0) {
            return RestResponse.failure("操作失败,请稍后重试");
        }

        for (String tenantId : tenantIds) {

            SysTenant dbTenant = this.getById(tenantId);
            if(null != dbTenant && dbTenant.getSuperTenant()) {
                return RestResponse.failure(dbTenant.getTenantName() + ",此租户信息不允许删除");
            }

            // 是否有会员/课程/班级
           int contentCount = baseMapper.tenantHaveContent(tenantId);
            if (contentCount > 0) {
                return RestResponse.failure("租户下有会员,无法删除");
            }
            int deptCount = deptMapper.selectCount(new QueryWrapper<SysDept>()
                    .eq("tenant_id", tenantId)
                    .eq("delete_flag", "0"));
            if (deptCount > 0) {
                return RestResponse.failure("租户下有场馆,无法删除");
            }
        }
        String joinedString = String.join(",", tenantIds);
        boolean deleteTenant = this.update(new UpdateWrapper<SysTenant>()
                .set("delete_flag","1")
                .in("tenant_id",joinedString));
//        this.removeByIds(Arrays.asList(tenantIds));
        if (deleteTenant) {
            return RestResponse.success();
        } else {
            return RestResponse.failure("操作失败,请稍后重试");
        }
    }

    //过期租户修改状态 (定时器触发事件)
    @Transactional
    @Override
    public int expireTenant() {
        int updatedRows=baseMapper.expireTenant();
        System.out.println("今天开始的过期租户修改状态任务已启动，影响记录数：" + updatedRows);
        return updatedRows;
    }

}
