package com.zehong.web.controller.userRelation;

import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.exception.BusinessException;
import com.zehong.common.core.page.TableDataInfo;
import com.zehong.common.enums.BusinessType;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.system.domain.TUserRelation;
import com.zehong.system.service.ISysUserService;
import com.zehong.system.service.ITUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户关联Controller
 * 
 * @author zehong
 * @date 2023-07-11
 */
@RestController
@RequestMapping("/user/relation")
public class TUserRelationController extends BaseController
{
    @Autowired
    private ITUserRelationService tUserRelationService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询用户关联列表
     */
    //@PreAuthorize("@ss.hasPermi('system:relation:list')")
    @GetMapping("/list")
    public TableDataInfo list(TUserRelation tUserRelation)
    {
        startPage();
        List<TUserRelation> list = tUserRelationService.selectTUserRelationList(tUserRelation);
        return getDataTable(list);
    }

    /**
     * 导出用户关联列表
     */
    //@PreAuthorize("@ss.hasPermi('system:relation:export')")
    @Log(title = "用户关联", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TUserRelation tUserRelation)
    {
        List<TUserRelation> list = tUserRelationService.selectTUserRelationList(tUserRelation);
        ExcelUtil<TUserRelation> util = new ExcelUtil<TUserRelation>(TUserRelation.class);
        return util.exportExcel(list, "用户关联数据");
    }

    /**
     * 获取用户关联详细信息
     */
   // @PreAuthorize("@ss.hasPermi('system:relation:query')")
    @GetMapping(value = "/{relationId}")
    public AjaxResult getInfo(@PathVariable("relationId") Long relationId)
    {
        return AjaxResult.success(tUserRelationService.selectTUserRelationById(relationId));
    }

    /**
     * 新增用户关联
     */
    //@PreAuthorize("@ss.hasPermi('system:relation:add')")
    @Log(title = "用户关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TUserRelation tUserRelation)
    {
        validateRelationUser(tUserRelation);
        return toAjax(tUserRelationService.insertTUserRelation(tUserRelation));
    }


    /**
     * 校验关联信息
     * @param tUserRelation 关联信息
     */
    private void validateRelationUser(TUserRelation tUserRelation){
        SysUser sysUser = sysUserService.selectUserByUserName(tUserRelation.getAccount());
        if (StringUtils.isNull(sysUser)){
            throw new UsernameNotFoundException("登录用户：" + tUserRelation.getAccount() + " 不存在");
        }
        boolean isPass = SecurityUtils.matchesPassword(tUserRelation.getPassword(),sysUser.getPassword());
        if(!isPass){
            throw new BusinessException("密码错误");
        }
        TUserRelation relation = new TUserRelation();
        relation.setRelationUserId(sysUser.getUserId());
        relation.setUserId(tUserRelation.getUserId());
        List<TUserRelation> relations = tUserRelationService.selectTUserRelationList(relation);
        if(!CollectionUtils.isEmpty(relations)){
            throw new BusinessException("关联账户已存在！");
        }
        if(tUserRelation.getUserId().equals(sysUser.getUserId())){
            throw new BusinessException("不能关联当前账户");
        }
        tUserRelation.setRelationUserId(sysUser.getUserId());
        //关联对方账号
        relationEachOther(sysUser.getUserId(),tUserRelation.getUserId());
    }

    /**
     * 关联对方账号
     * @param userId 账号
     * @param relationUserId 对方账号
     */
    private void relationEachOther(Long userId, Long relationUserId) {
        TUserRelation relation = new TUserRelation();
        relation.setUserId(userId);
        relation.setRelationUserId(relationUserId);
        List<TUserRelation> relations = tUserRelationService.selectTUserRelationList(relation);
        if(CollectionUtils.isEmpty(relations)){
            tUserRelationService.insertTUserRelation(relation);
        }
    }

    /**
     * 修改用户关联
     */
    //@PreAuthorize("@ss.hasPermi('system:relation:edit')")
    @Log(title = "用户关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TUserRelation tUserRelation)
    {
        return toAjax(tUserRelationService.updateTUserRelation(tUserRelation));
    }

    /**
     * 删除用户关联
     */
    //@PreAuthorize("@ss.hasPermi('system:relation:remove')")
    @Log(title = "用户关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{relationIds}")
    public AjaxResult remove(@PathVariable Long[] relationIds)
    {
        return toAjax(tUserRelationService.deleteTUserRelationByIds(relationIds));
    }
}
