package com.fs.company.controller.company;

import com.alibaba.fastjson.JSONObject;
import com.fs.aicall.domain.BaseDomain;
import com.fs.aicall.domain.TaskInfo;
import com.fs.aicall.domain.apiresult.PushIIntentionResult;
import com.fs.aicall.domain.result.CIDGroupListResult;
import com.fs.aicall.domain.result.EditDialogResult;
import com.fs.aicall.domain.result.GetairobotResult;
import com.fs.aicall.domain.result.QueryCallTaskInfoResult;
import com.fs.aicall.service.AiCallService;
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.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyVoiceRobotic;
import com.fs.company.domain.CompanyVoiceRoboticCallees;
import com.fs.company.domain.CompanyVoiceRoboticWx;
import com.fs.company.service.ICompanyVoiceRoboticCalleesService;
import com.fs.company.service.ICompanyVoiceRoboticService;
import com.fs.company.service.ICompanyVoiceRoboticWxService;
import com.fs.company.vo.CdrBodyVo;
import com.fs.company.vo.CdrDetailVo;
import com.fs.company.vo.WorkflowExecRecordVo;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 机器人外呼任务Controller
 *
 * @author fs
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/company/companyVoiceRobotic")
@Slf4j
public class CompanyVoiceRoboticController extends BaseController
{
    @Autowired
    private ICompanyVoiceRoboticService companyVoiceRoboticService;
    @Autowired
    private ICompanyVoiceRoboticCalleesService companyVoiceRoboticCalleesService;
    @Autowired
    private AiCallService aiCallService;
    @Autowired
    private ICompanyVoiceRoboticWxService companyVoiceRoboticWxService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询机器人外呼任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:list')")
    @GetMapping("/list")
    public TableDataInfo list(CompanyVoiceRobotic companyVoiceRobotic){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyVoiceRobotic.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        List<CompanyVoiceRobotic> list = companyVoiceRoboticService.selectCompanyVoiceRoboticListCompany(companyVoiceRobotic);
        return getDataTable(list);
    }
    /**
     * 查询机器人外呼任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:list')")
    @GetMapping("/listAll")
    public R listAll(CompanyVoiceRobotic companyVoiceRobotic){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyVoiceRobotic.setCompanyId(loginUser.getCompany().getCompanyId());
        return R.ok().put("data", companyVoiceRoboticService.selectCompanyVoiceRoboticListCompany(companyVoiceRobotic));
    }
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:list')")
    @GetMapping("/calleesList")
    public TableDataInfo calleesList(Long id){
        startPage();
        List<CompanyVoiceRoboticCallees> list = companyVoiceRoboticCalleesService.selectCompanyVoiceRoboticCalleesListByRoboticId(id);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:list')")
    @GetMapping("/wxList")
    public TableDataInfo wxList(Long id){
        startPage();
        List<CompanyVoiceRoboticWx> list = companyVoiceRoboticWxService.selectWxList(id);
        return getDataTable(list);
    }

//    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:wxListQw')")
    @GetMapping("/wxListQw")
    public TableDataInfo wxListQw(Long id){
        startPage();
        List<CompanyVoiceRoboticWx> list = companyVoiceRoboticWxService.selectWxListQw(id);
        return getDataTable(list);
    }

    /**
     * 导出机器人外呼任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:export')")
    @Log(title = "机器人外呼任务", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CompanyVoiceRobotic companyVoiceRobotic)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyVoiceRobotic.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CompanyVoiceRobotic> list = companyVoiceRoboticService.selectCompanyVoiceRoboticListCompany(companyVoiceRobotic);
        ExcelUtil<CompanyVoiceRobotic> util = new ExcelUtil<CompanyVoiceRobotic>(CompanyVoiceRobotic.class);
        return util.exportExcel(list, "robotic");
    }

    /**
     * 获取机器人外呼任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(companyVoiceRoboticService.selectCompanyVoiceRoboticById(id));
    }

    /**
     * 新增机器人外呼任务
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:add')")
    @Log(title = "机器人外呼任务", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody CompanyVoiceRobotic companyVoiceRobotic){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        companyVoiceRobotic.setCreateUser(loginUser.getUser().getUserId());
        companyVoiceRobotic.setCompanyUserId(loginUser.getUser().getUserId());
        companyVoiceRobotic.setCompanyId(loginUser.getCompany().getCompanyId());
        return toAjax(companyVoiceRoboticService.insertCompanyVoiceRobotic(companyVoiceRobotic));
    }

    /**
     * 修改机器人外呼任务
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:edit')")
    @Log(title = "机器人外呼任务", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody CompanyVoiceRobotic companyVoiceRobotic)
    {
        return toAjax(companyVoiceRoboticService.updateCompanyVoiceRobotic(companyVoiceRobotic));
    }

    /**
     * 删除机器人外呼任务
     */
    @PreAuthorize("@ss.hasPermi('system:companyVoiceRobotic:remove')")
    @Log(title = "机器人外呼任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            companyVoiceRoboticService.updateDelFlag(id, 1);
        }
        return AjaxResult.success();
    }
    /**
     * 删除机器人外呼任务
     */
	@GetMapping("/getTypes")
    public R getTypes(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        List<GetairobotResult> getairobotlist = aiCallService.getairobotlist(companyId);
        List<EditDialogResult> editDialogResults = aiCallService.queryDialog(companyId);
        return R.ok().put("robot", getairobotlist).put("dialog", editDialogResults);
    }
    /**
     * 查询状态
     */
    @GetMapping("/statusList")
    public R statusList(String ids){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        List<String> list = Arrays.stream(ids.split(",")).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        return R.ok().put("data", list.stream().map(e -> aiCallService.queryCallTaskInfo(TaskInfo.builder().taskID(e).build(), companyId)).collect(Collectors.toMap(QueryCallTaskInfoResult::getTaskID, e -> e)));
    }
    /**
     * 启动任务
     */
	@GetMapping("/startRobotic")
    public R startRobotic(String taskId){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        aiCallService.startCallTask(TaskInfo.builder().taskID(taskId).build(), companyId);
        return R.ok();
    }
    /**
     * 停止任务
     */
	@GetMapping("/stopRobotic")
    public R stopRobotic(String taskId){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        aiCallService.stopCallTask(TaskInfo.builder().taskID(taskId).build(), companyId);
        return R.ok();
    }
    /**
     * 员工列表
     */
	@GetMapping("/companyUserList")
    public R qwUserList(){
        return R.ok().put("data", companyVoiceRoboticService.qwUserListCompany(new CompanyVoiceRobotic()));
    }

    /**
     * 外呼回调
     */
	@PostMapping("/callerResult")
    public R callerResult(@RequestBody PushIIntentionResult result){
        companyVoiceRoboticService.callerResult(result);
        return R.ok();
    }

    @PostMapping("/callerResult4EasyCall")
    public String callerResult4EasyCall(@RequestBody String cdrStr) {
        log.info("callerResult4EasyCall：回调结果：{}",cdrStr);
        CdrDetailVo cdrDetailVo = JSONObject.parseObject(cdrStr, CdrDetailVo.class);
        companyVoiceRoboticService.callerResult4EasyCall(cdrDetailVo);
        return "success";
    }
    /**
     * 外呼回调
     */
	@GetMapping("/test")
    public R test(Long id){
        companyVoiceRoboticService.dispenseWx(id);
        return R.ok();
    }
    /**
     * 获取主叫
     */
    @GetMapping("/cidList")
    public R cidList(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        companyVoiceRoboticService.cidList(companyId);
        return R.ok();
    }
    /**
     * 启动任务
     */
    @GetMapping("/taskRun")
    public R taskRun(Long id){
        companyVoiceRoboticService.taskRun(id);
        return R.ok();
    }

    @GetMapping("/getCIDGroupList")
    public R getCIDGroupList(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<CIDGroupListResult> cidGroupList = aiCallService.getCIDGroupList(null, loginUser.getCompany().getCompanyId());
        return R.ok().put("data", cidGroupList);
    }

    /**
     * 查询任务执行记录
     * 获取每个人的工作流执行状态和节点日志
     */
//    @GetMapping("/execRecords")
//    public R getExecRecords(Long roboticId) {
//        if (roboticId == null) {
//            return R.error("任务ID不能为空");
//        }
//        List<WorkflowExecRecordVo> records = companyVoiceRoboticService.getExecRecords(roboticId);
//        return R.ok().put("data", records);
//    }

    @GetMapping("/execRecords")
    public R getExecRecords(@RequestParam Long roboticId,
                            @RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "10") Integer pageSize,
                            @RequestParam(required = false) String customerName,
                            @RequestParam(required = false) String customerPhone,
                            @RequestParam Boolean onlyCallNode) {
        if (roboticId == null) {
            return R.error("任务ID不能为空");
        }
        return R.ok(companyVoiceRoboticService.getExecRecords(roboticId, pageNum, pageSize, customerName,
                 customerPhone,onlyCallNode));
    }

    @GetMapping("/getCurrentCompanyId")
    public R getCurrentCompanyId(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        return R.ok().put("companyId", loginUser.getCompany().getCompanyId());
    }
}
