package com.fs.chat.controller;

import cn.hutool.json.JSONUtil;
import com.fs.chat.config.QwConfig;
import com.fs.chat.domain.ChatRole;
import com.fs.chat.param.ChatRoleAddEditCParam;
import com.fs.chat.service.IChatRoleService;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyConfig;
import com.fs.company.service.ICompanyConfigService;

import com.fs.fastGpt.domain.FastGptRole;
import com.fs.system.domain.SysConfig;
import com.fs.system.service.ISysConfigService;
import com.fs.wx.kf.dto.WeixinKfAddEditAccountDTO;
import com.fs.wx.kf.dto.WeixinKfDelAccountDTO;
import com.fs.wx.kf.dto.WeixinKfGetFileDTO;
import com.fs.wx.kf.dto.WeixinKuGetAccountUrlDTO;
import com.fs.wx.kf.service.IWeixinKfService;
import com.fs.wx.kf.vo.WeixinKfAddEditAccountVO;
import com.fs.wx.kf.vo.WeixinKfDelAccountVO;
import com.fs.wx.kf.vo.WeixinKfGetAccountUrlVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天角色Controller
 *
 * @author fs
 * @date 2024-04-19
 */
@RestController
@RequestMapping("/chat/chatRole")
public class ChatRoleController extends BaseController
{
    @Autowired
    private ICompanyConfigService companyConfigService;
    @Autowired
    private IChatRoleService chatRoleService;
    @Autowired
    private IWeixinKfService weixinKfService;
    @Autowired
    private ISysConfigService sysConfigService;
    /**
     * 查询聊天角色列表
     */
    @PreAuthorize("@ss.hasPermi('chat:chatRole:list')")
    @GetMapping("/list")
    public TableDataInfo list(ChatRole chatRole)
    {
        startPage();
        List<ChatRole> list = chatRoleService.selectChatRoleList(chatRole);
        return getDataTable(list);
    }

    /**
     * 导出聊天角色列表
     */
    @PreAuthorize("@ss.hasPermi('chat:chatRole:export')")
    @Log(title = "聊天角色", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ChatRole chatRole)
    {
        List<ChatRole> list = chatRoleService.selectChatRoleList(chatRole);
        ExcelUtil<ChatRole> util = new ExcelUtil<ChatRole>(ChatRole.class);
        return util.exportExcel(list, "聊天角色数据");
    }

    /**
     * 获取聊天角色详细信息
     */
    @PreAuthorize("@ss.hasPermi('chat:chatRole:query')")
    @GetMapping(value = "/{roleId}")
    public R getInfo(@PathVariable("roleId") Long roleId)
    {
//        SysConfig config = sysConfigService.selectConfigByConfigKey("qw:config");
////        CompanyConfig config=companyConfigService.selectCompanyConfigByKey(0L,"qw:config");
//        QwConfig qwConfig= JSONUtil.toBean(config.getConfigValue(), QwConfig.class);

        ChatRole chatRole=chatRoleService.selectChatRoleByRoleId(roleId);
        return R.ok().put("data",chatRole);
    }

    /**
     * 新增聊天角色
     */
    @PreAuthorize("@ss.hasPermi('chat:chatRole:add')")
    @Log(title = "聊天角色", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody ChatRoleAddEditCParam param)
    {
        WeixinKfAddEditAccountDTO dto=new WeixinKfAddEditAccountDTO();
        dto.setName(param.getRoleName());
        dto.setMedia_id(param.getKfMediaId());
        SysConfig config = sysConfigService.selectConfigByConfigKey("qw:config");
        QwConfig qwConfig= JSONUtil.toBean(config.getConfigValue(), QwConfig.class);



        WeixinKfAddEditAccountVO vo=weixinKfService.addAccount(qwConfig.getCorpId(),qwConfig.getSecret(),dto);
        if(vo.getErrcode().equals(0)){
            WeixinKuGetAccountUrlDTO urlDTO=new WeixinKuGetAccountUrlDTO();
            urlDTO.setOpen_kfid(vo.getOpen_kfid());
            WeixinKfGetAccountUrlVO urlVO=weixinKfService.getAccountUrl(qwConfig.getCorpId(),qwConfig.getSecret(),urlDTO);

            ChatRole chatRole=new ChatRole();
            BeanUtils.copyProperties(param,chatRole);
            chatRole.setCompanyId(0L);
            chatRole.setKfId(vo.getOpen_kfid());
            chatRole.setKfUrl(urlVO.getUrl());
            if(chatRoleService.insertChatRole(chatRole)>0){

                return R.ok();
            }
            else{
                return R.error();
            }
        }
        else{
            return R.error(vo.getErrmsg());
        }

    }

    /**
     * 修改聊天角色
     */
    @PreAuthorize("@ss.hasPermi('chat:chatRole:edit')")
    @Log(title = "聊天角色", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody ChatRoleAddEditCParam param)
    {
        SysConfig config = sysConfigService.selectConfigByConfigKey("qw:config");
        QwConfig qwConfig= JSONUtil.toBean(config.getConfigValue(), QwConfig.class);


        ChatRole chatRole=chatRoleService.selectChatRoleByRoleId(param.getRoleId());
        WeixinKfAddEditAccountDTO dto=new WeixinKfAddEditAccountDTO();
        dto.setOpen_kfid(chatRole.getKfId());
        dto.setName(param.getRoleName());
        dto.setMedia_id(param.getKfMediaId());
        WeixinKfAddEditAccountVO vo=weixinKfService.editAccount(qwConfig.getCorpId(),qwConfig.getSecret(),dto);
        if(vo.getErrcode().equals(0)){
            BeanUtils.copyProperties(param,chatRole);
            if(chatRoleService.updateChatRole(chatRole)>0){
                return R.ok();
            }
            else{
                return R.error();
            }
        }
        else{
            return R.error(vo.getErrmsg());
        }
    }

    /**
     * 删除聊天角色
     */
    @PreAuthorize("@ss.hasPermi('chat:chatRole:remove')")
    @Log(title = "聊天角色", businessType = BusinessType.DELETE)
	@DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds)
    {
        SysConfig config = sysConfigService.selectConfigByConfigKey("qw:config");
        QwConfig qwConfig= JSONUtil.toBean(config.getConfigValue(), QwConfig.class);

        for(Long id:roleIds){
            ChatRole chatRole=chatRoleService.selectChatRoleByRoleId(id);
            WeixinKfDelAccountDTO dto=new WeixinKfDelAccountDTO();
            dto.setOpen_kfid(chatRole.getKfId());
            WeixinKfDelAccountVO vo=weixinKfService.delAccount(qwConfig.getCorpId(),qwConfig.getSecret(),dto);
            if(vo.getErrcode().equals(0)){

            }
            chatRoleService.deleteChatRoleByRoleId(id);
        }
        return R.ok();
    }

    @GetMapping("/getAllRoleList")
    public R getAllRoleList()
    {
        ChatRole chatRole=new ChatRole();
        List<ChatRole> list = chatRoleService.selectChatRoleList(chatRole);
        return R.ok().put("data",list);
    }

}
