package co.yixiang.yshop.module.mp.controller.app.mini;

import cn.hutool.core.util.RandomUtil;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.module.mp.controller.app.mini.vo.AppCustomerServiceVO;
import co.yixiang.yshop.module.mp.dal.dataobject.customerservice.CustomerServiceDO;
import co.yixiang.yshop.module.mp.framework.cp.config.WxCpConfiguration;
import co.yixiang.yshop.module.mp.service.customerservice.CustomerServiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpKfService;
import me.chanjar.weixin.cp.bean.kf.WxCpKfAccountLink;
import me.chanjar.weixin.cp.bean.kf.WxCpKfAccountLinkResp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author pepis
 * @apiNote 用户 APP - 客服
 **/
@Slf4j
@RestController
@Tag(name = "用户 APP - 客服")
@RequestMapping("/cp/kf")
public class AppCustomerServiceController {
    @Resource
    private CustomerServiceService customerServiceService;

    @SneakyThrows
    @GetMapping
    @Operation(summary = "获取客服")
    public CommonResult<AppCustomerServiceVO> getCustomerService() {
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        //客服列表
        List<CustomerServiceDO> list = customerServiceService.list();
        CustomerServiceDO customerServiceDO = RandomUtil.randomEle(list);
        AppCustomerServiceVO appCustomerServiceVO = new AppCustomerServiceVO();
        appCustomerServiceVO.setCorpId(WxCpConfiguration.corpId);
        try {
            WxCpKfAccountLink link = new WxCpKfAccountLink();
            link.setOpenKfid(customerServiceDO.getOpenKfid());
            WxCpKfAccountLinkResp accountLink = kfService.getAccountLink(link);
            appCustomerServiceVO.setAccountLink(accountLink.getUrl());
        } catch (WxErrorException e) {
            log.warn("获取客服链接失败:{}", customerServiceDO.getOpenKfid());
            throw new RuntimeException(e);
        }
        return CommonResult.success(appCustomerServiceVO);
    }
}
