package com.ruoyi.system.service.impl;

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

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.EnterprisePhoto;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.EnterpriseApply;
import com.ruoyi.system.service.IEnterpriseApplyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 企业信息审核Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-02-20
 */
@Service
public class EnterpriseApplyServiceImpl implements IEnterpriseApplyService 
{

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private EnterpriseApplyMapper enterpriseApplyMapper;

    @Autowired
    private EnterprisePhotoMapper enterprisePhotoMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;
    @Autowired
    private SysUserMapper userMapper;


    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleDeptMapper sysRoleDeptMapper;



    /**
     * 查询企业信息审核
     * 
     * @param id 企业信息审核主键
     * @return 企业信息审核
     */
    @Override
    public EnterpriseApply selectEnterpriseApplyById(Long id)
    {
        return enterpriseApplyMapper.selectEnterpriseApplyById(id);
    }

    /**
     * 查询企业信息审核列表
     * 
     * @param enterpriseApply 企业信息审核
     * @return 企业信息审核
     */
    @Override
    public List<EnterpriseApply> selectEnterpriseApplyList(EnterpriseApply enterpriseApply)
    {
        return enterpriseApplyMapper.selectEnterpriseApplyList(enterpriseApply);
    }

    /**
     * 新增企业信息审核
     * 
     * @param enterpriseApply 企业信息审核
     * @return 结果
     */
    @Override
    @Transactional
    public int insertEnterpriseApply(EnterpriseApply enterpriseApply)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        enterpriseApply.setUserId(user.getUserId());
        enterpriseApply.setUserName(user.getUserName());
        enterpriseApply.setUserPhone(user.getPhonenumber());
        enterpriseApply.setCreateTime(DateUtils.getNowDate());
        enterpriseApply.setUpdateTime(DateUtils.getNowDate());
        int count = enterpriseApplyMapper.insertEnterpriseApply(enterpriseApply);
        //保存图片信息
        List<EnterprisePhoto> enterprisePhotoList  = enterpriseApply.getEnterprisePhotoList();
        for (EnterprisePhoto enterprisePhoto : enterprisePhotoList) {
            enterprisePhoto.setEnterpriseId(enterpriseApply.getId());
            enterprisePhotoMapper.insertEnterprisePhoto(enterprisePhoto);
        }
        return count;
    }

    /**
     * 修改企业信息审核
     * 
     * @param enterpriseApply 企业信息审核
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEnterpriseApply(EnterpriseApply enterpriseApply)
    {
        try{
            //修改图片信息
            //删除所有图片信息
            enterprisePhotoMapper.deleteEnterprisePhotoByEnterpriseId(enterpriseApply.getId());
            //保存图片信息
            List<EnterprisePhoto> enterprisePhotoList  = enterpriseApply.getEnterprisePhotoList();
            for (EnterprisePhoto enterprisePhoto : enterprisePhotoList) {
                enterprisePhoto.setEnterpriseId(enterpriseApply.getId());
                enterprisePhotoMapper.insertEnterprisePhoto(enterprisePhoto);
            }
            enterpriseApply.setUpdateTime(DateUtils.getNowDate());
            //重置申请状态和打回理由
            enterpriseApply.setIsAudit("0");
            enterpriseApply.setAuditOpinion("");
            return enterpriseApplyMapper.updateEnterpriseApply(enterpriseApply);
        }catch (Exception e){
            e.getMessage();
            return 0;
        }
    }

    /**
     * 批量删除企业信息审核
     * 
     * @param ids 需要删除的企业信息审核主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseApplyByIds(Long[] ids)
    {
        return enterpriseApplyMapper.deleteEnterpriseApplyByIds(ids);
    }

    /**
     * 删除企业信息审核信息
     * 
     * @param id 企业信息审核主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseApplyById(Long id)
    {
        return enterpriseApplyMapper.deleteEnterpriseApplyById(id);
    }

    @Override
    @Transactional
    public int edit(EnterpriseApply enterpriseApply) {
        try{
            //enterpriseApply.setUpdateTime(DateUtils.getNowDate());
            if("1".equals(enterpriseApply.getIsAudit() )){
                //审核通过
                // 删除用户与角色关联
                userRoleMapper.deleteUserRoleByUserId(enterpriseApply.getUserId());
                //生成管理员角色与人员中间表
                SysRole info = roleMapper.checkRoleKeyUnique("conservator");
                if(info == null){
                    //新增一个管理员角色
                    info = new SysRole();
                    info.setRoleName("管理员");
                    info.setRoleKey("conservator");
                    info.setRoleSort(3);
                    info.setDataScope("1");
                    info.setStatus("0");
                    info.setDelFlag("0");
                    info.setRemark("管理员");
                    roleMapper.insertRole(info);
                }
                // 新增用户与角色管理
                Long[] roleIds = {info.getRoleId()};
                sysUserServiceImpl.insertUserRole(enterpriseApply.getUserId(),roleIds);

                //新增部门信息
                SysDept dept = new SysDept();
                dept.setParentId(0L);
                dept.setAncestors( "0," + dept.getParentId());
                dept.setDeptName(enterpriseApply.getName());
                dept.setLeader(enterpriseApply.getLegalPersonName());
                dept.setPhone(enterpriseApply.getPhone());
                deptMapper.insertDept(dept);
                //新增角色与部门关联
                List<SysRoleDept> list = new ArrayList<SysRoleDept>();
                SysRoleDept rd = new SysRoleDept();
                rd.setRoleId(info.getRoleId());
                rd.setDeptId(dept.getDeptId());
                list.add(rd);
                sysRoleDeptMapper.batchRoleDept(list);
                //修改人员信息（新增部门信息）
                SysUser applyForUser = new SysUser();
                applyForUser.setUserId(enterpriseApply.getUserId());
                applyForUser.setDeptId(dept.getDeptId());
                applyForUser.setApplyFor("1");
                userMapper.updateUser(applyForUser);
                //删除登录tocken
                String userKey = redisCache.getCacheObject(CacheConstants.LOGIN_USER_ID+String.valueOf(enterpriseApply.getUserId()));
                redisCache.deleteObject(userKey);
            }
            return enterpriseApplyMapper.updateEnterpriseApply(enterpriseApply);
        }catch (Exception e){
            e.getMessage();
            return 0;
        }
    }
}
