package com.ruoyi.cc.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.cc.domain.CcOutboundCdr;
import com.ruoyi.cc.service.ICcOutboundCdrService;
import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 外呼记录Controller
 *
 * @author ruoyi
 * @date 2024-12-22
 */
@Controller
@RequestMapping("/cc/outboundcdr")
public class CcOutboundCdrController extends BaseController
{
    private String prefix = "cc/outboundcdr";

    @Autowired
    private ICcOutboundCdrService ccOutboundCdrService;
    @Autowired
    private ICcParamsService ccParamsService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;


    @RequiresPermissions("cc:outboundcdr:view")
    @GetMapping()
    public String outboundcdr()
    {
        return prefix + "/outboundcdr";
    }

    /**
     * 查询外呼记录列表
     */
    @RequiresPermissions("cc:outboundcdr:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CcOutboundCdr ccOutboundCdr)
    {
        Map<String, Object> params = ccOutboundCdr.getParams();
        if (null == params) {
            params = new HashMap<>();
        }
        // 如果是班长坐席，根据权限查询有权限的坐席的通话记录，否则查询全部数据
        SysUser currentUser = getSysUser();
        List<String> manageOpnum = new ArrayList<>(); // 有权限的用户账号
        List<SysPost> postList = postService.selectPostsByUserId(currentUser.getUserId()).stream().filter(SysPost::isFlag).collect(Collectors.toList());
        for (SysPost sysPost: postList) {
            // 坐席可以查看本人数据
            if (UserConstants.SYSTEM_POST_AGENT.equals(sysPost.getPostCode())) {
                manageOpnum.add(currentUser.getLoginName());
            }
            // 班组长查看权限内坐席数据
            if (UserConstants.SYSTEM_POST_TEAM_LEADER.equals(sysPost.getPostCode())) {
                List<Long> deptIds = new ArrayList<>();
                deptIds.add(currentUser.getDeptId());
                deptIds.addAll(sysDeptService.selectChildrenDeptById(currentUser.getDeptId()).stream().map(SysDept::getDeptId).collect(Collectors.toList()));
                manageOpnum.addAll(sysUserService.selectUserByDeptIds(deptIds).stream().map(SysUser::getLoginName).collect(Collectors.toList()));
            }
        }
        params.put("manageOpnum", manageOpnum);

        ccOutboundCdr.setParams(params);
        startPage();
        List<CcOutboundCdr> list = ccOutboundCdrService.selectCcOutboundCdrList(ccOutboundCdr);
        for (CcOutboundCdr data: list) {
            data.setWavFileUrl("/recordings/files?filename=" + data.getRecordFilename());
            data.setCallee(CommonUtils.maskPhoneNumber(data.getCallee()));
            // 挂机原因处理
            if (StringUtils.isNotEmpty(data.getHangupCause())) {
                if (data.getHangupCause().startsWith("{") && data.getHangupCause().endsWith("}")) {
                    try {
                        JSONObject hangupCause = JSONObject.parseObject(data.getHangupCause());
                        String hangupCauseCode = hangupCause.getString("code");
                        String hangupCauseDetail = hangupCause.getString("details");
                        String hangupCauseCodeI18n = MessageUtils.message("_hangup_cause_code_" + hangupCauseCode);
                        if (StringUtils.isNotEmpty(hangupCauseCodeI18n)) {
                            hangupCauseCode = hangupCauseCodeI18n;
                        }
                        if (StringUtils.isNotEmpty(hangupCauseDetail)) {
                            data.setHangupCause(hangupCauseCode + ":" + hangupCauseDetail);
                        } else {
                            data.setHangupCause(hangupCauseCode);
                        }
                    } catch (Exception e) {
                        logger.error("解析挂断原因异常", e);
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出外呼记录列表
     */
    @RequiresPermissions("cc:outboundcdr:export")
    @Log(title = "外呼记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CcOutboundCdr ccOutboundCdr)
    {
        List<CcOutboundCdr> list = ccOutboundCdrService.selectCcOutboundCdrList(ccOutboundCdr);
        for (CcOutboundCdr data: list) {
            data.setCallee(CommonUtils.maskPhoneNumber(data.getCallee()));
            // 挂机原因处理
            if (StringUtils.isNotEmpty(data.getHangupCause())) {
                if (data.getHangupCause().startsWith("{") && data.getHangupCause().endsWith("}")) {
                    try {
                        JSONObject hangupCause = JSONObject.parseObject(data.getHangupCause());
                        String hangupCauseCode = hangupCause.getString("code");
                        String hangupCauseDetail = hangupCause.getString("details");
                        String hangupCauseCodeI18n = MessageUtils.message("_hangup_cause_code_" + hangupCauseCode);
                        if (StringUtils.isNotEmpty(hangupCauseCodeI18n)) {
                            hangupCauseCode = hangupCauseCodeI18n;
                        }
                        if (StringUtils.isNotEmpty(hangupCauseDetail)) {
                            data.setHangupCause(hangupCauseCode + ":" + hangupCauseDetail);
                        } else {
                            data.setHangupCause(hangupCauseCode);
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
        ExcelUtil<CcOutboundCdr> util = new ExcelUtil<CcOutboundCdr>(CcOutboundCdr.class);
        return util.exportExcel(list, "外呼记录数据");
    }

    /**
     * 新增外呼记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存外呼记录
     */
    @RequiresPermissions("cc:outboundcdr:add")
    @Log(title = "外呼记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CcOutboundCdr ccOutboundCdr)
    {
        return toAjax(ccOutboundCdrService.insertCcOutboundCdr(ccOutboundCdr));
    }

    /**
     * 修改外呼记录
     */
    @RequiresPermissions("cc:outboundcdr:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        CcOutboundCdr ccOutboundCdr = ccOutboundCdrService.selectCcOutboundCdrById(id);
        mmap.put("ccOutboundCdr", ccOutboundCdr);
        return prefix + "/edit";
    }

    /**
     * 修改保存外呼记录
     */
    @RequiresPermissions("cc:outboundcdr:edit")
    @Log(title = "外呼记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CcOutboundCdr ccOutboundCdr)
    {
        return toAjax(ccOutboundCdrService.updateCcOutboundCdr(ccOutboundCdr));
    }

    /**
     * 删除外呼记录
     */
    @RequiresPermissions("cc:outboundcdr:remove")
    @Log(title = "外呼记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ccOutboundCdrService.deleteCcOutboundCdrByIds(ids));
    }
}
