package com.fs.xiaoshouyi.controller;

import com.fs.common.core.domain.AjaxResult;
import com.fs.common.utils.ServletUtils;
import com.fs.framework.service.TokenService;
import com.fs.xiaoshouyi.dto.BindXsyAccountRequest;
import com.fs.xiaoshouyi.service.XsyCompanyBindService;
import com.fs.xiaoshouyi.service.XsyUserBindService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/xsy/bind")
@RequiredArgsConstructor
public class XsyBindController {

    @Autowired
    private XsyUserBindService bindService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private XsyCompanyBindService xsyCompanyBindService;


    /**
     * 绑定销售易账号
     */
    @PreAuthorize("@ss.hasPermi('xsy:bind:bind')")
    @PostMapping("/bind")
    public AjaxResult bind(@RequestBody BindXsyAccountRequest req) {
        Long companyId = tokenService.getLoginUser(ServletUtils.getRequest()).getCompany().getCompanyId();
        boolean account = xsyCompanyBindService.isCompanyBoundAccount(companyId, req.getAccountId());
        if (!account) {
            throw new RuntimeException("当前员工所在公司未绑定该销售易账号，不能绑定");
        }
        bindService.bind(req.getCompanyUserId(), req.getAccountId());
        return AjaxResult.success();
    }

    /**
     * 解绑
     */
    @PreAuthorize("@ss.hasPermi('xsy:bind:unbind')")
    @PostMapping("/unbind")
    public AjaxResult unbind(@RequestBody BindXsyAccountRequest req) {
        bindService.unbind(req.getCompanyUserId());
        return AjaxResult.success();
    }

    /**
     * 查询绑定
     */
    @PreAuthorize("@ss.hasPermi('xsy:bind:query')")
    @GetMapping("/get")
    public AjaxResult get(@RequestParam Long companyUserId) {
        Long accountId = bindService.getBindAccountId(companyUserId);
        return AjaxResult.success(accountId);
    }
}