package com.ruoyi.cc.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aicall.domain.CcCallPhone;
import com.ruoyi.cc.domain.CcBizGroup;
import com.ruoyi.cc.domain.CcInboundCdr;
import com.ruoyi.cc.service.ICcBizGroupService;
import com.ruoyi.cc.service.ICcInboundCdrService;
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.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
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.Date;
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/inboundcdr")
public class CcInboundCdrController extends BaseController
{
    private String prefix = "cc/inboundcdr";

    @Autowired
    private ICcInboundCdrService ccInboundCdrService;
    @Autowired
    private ICcParamsService ccParamsService;
    @Autowired
    private ICcBizGroupService groupService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;


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

    /**
     * 查询呼入记录列表
     */
    @RequiresPermissions("cc:inboundcdr:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CcInboundCdr ccInboundCdr)
    {
        Map<String, Object> params = ccInboundCdr.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);
        ccInboundCdr.setParams(params);
        normalizeQueryTimeParams(ccInboundCdr);

        startPage();
        List<CcInboundCdr> list = ccInboundCdrService.selectCcInboundCdrList(ccInboundCdr);
        TableDataInfo tableDataInfo = getDataTable(list);
        List<CcInboundCdr> records = (List<CcInboundCdr>) tableDataInfo.getRows();
        if (records == null || records.isEmpty()) {
            return tableDataInfo;
        }

        Map<String, String> groupNames = new HashMap<>();
        for (CcBizGroup group : groupService.selectCcBizGroupList(new CcBizGroup())) {
            if (group.getGroupId() != null) {
                groupNames.put(String.valueOf(group.getGroupId()), group.getBizGroupName());
            }
        }
        for (CcInboundCdr data: records) {
            String wavFile = data.getWavFile();
            data.setWavFileUrl("/recordings/files?filename=" + (wavFile == null ? "" : wavFile));
            data.setCaller(CommonUtils.maskPhoneNumber(data.getCaller()));
            String groupName = groupNames.getOrDefault(data.getGroupId(), "-");
            if (StringUtils.isBlank(groupName)) {
                groupName = "-";
            }
            data.setGroupName(groupName);

            // 挂机原因处理
            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(ExceptionUtil.getExceptionMessage(e));
                    }

                }
            }

        }
        tableDataInfo.setRows(records);
        return tableDataInfo;
    }

    /**
     * 前端传入 yyyy-MM-dd HH:mm:ss，库字段为毫秒时间戳，统一转换以便命中索引
     */
    private void normalizeQueryTimeParams(CcInboundCdr ccInboundCdr) {
        Map<String, Object> params = ccInboundCdr.getParams();
        if (params == null || params.isEmpty()) {
            return;
        }
        convertDatetimeParamToMillis(params, "inboundTimeStart");
        convertDatetimeParamToMillis(params, "inboundTimeEnd");
        convertDatetimeParamToMillis(params, "answeredTimeStart");
        convertDatetimeParamToMillis(params, "answeredTimeEnd");
        convertDatetimeParamToMillis(params, "hangupTimeStart");
        convertDatetimeParamToMillis(params, "hangupTimeEnd");
    }

    private void convertDatetimeParamToMillis(Map<String, Object> params, String key) {
        Object value = params.get(key);
        if (value == null || StringUtils.isEmpty(value.toString())) {
            return;
        }
        String text = value.toString().trim();
        if (text.matches("^\\d+$")) {
            return;
        }
        Date date = DateUtils.parseDate(text);
        if (date != null) {
            params.put(key, date.getTime());
        }
    }

    /**
     * 导出呼入记录列表
     */
    @RequiresPermissions("cc:inboundcdr:export")
    @Log(title = "呼入记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CcInboundCdr ccInboundCdr)
    {
        List<CcInboundCdr> list = ccInboundCdrService.selectCcInboundCdrList(ccInboundCdr);
        for (CcInboundCdr data: list) {
            data.setCaller(CommonUtils.maskPhoneNumber(data.getCaller()));
        }
        ExcelUtil<CcInboundCdr> util = new ExcelUtil<CcInboundCdr>(CcInboundCdr.class);
        return util.exportExcel(list, "呼入记录数据");
    }

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

    /**
     * 新增保存呼入记录
     */
    @RequiresPermissions("cc:inboundcdr:add")
    @Log(title = "呼入记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CcInboundCdr ccInboundCdr)
    {
        return toAjax(ccInboundCdrService.insertCcInboundCdr(ccInboundCdr));
    }

    /**
     * 修改呼入记录
     */
    @RequiresPermissions("cc:inboundcdr:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        CcInboundCdr ccInboundCdr = ccInboundCdrService.selectCcInboundCdrById(id);
        mmap.put("ccInboundCdr", ccInboundCdr);
        return prefix + "/edit";
    }

    /**
     * 修改保存呼入记录
     */
    @RequiresPermissions("cc:inboundcdr:edit")
    @Log(title = "呼入记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CcInboundCdr ccInboundCdr)
    {
        return toAjax(ccInboundCdrService.updateCcInboundCdr(ccInboundCdr));
    }

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