package com.fs.company.controller.aiSipCall;

import com.alibaba.fastjson.JSONObject;
import com.fs.aiSipCall.domain.AiSipCallPhone;
import com.fs.aiSipCall.domain.AiSipCallTask;
import com.fs.aiSipCall.dto.CommonPhoneModel;
import com.fs.aiSipCall.service.IAiSipCallTaskService;
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.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * aiSIP外呼任务Controller
 *
 * @author fs
 * @date 2026-03-06
 */
@RestController
@RequestMapping("/company/aiSipCall/task")
public class AiSipCallTaskController extends BaseController
{
    @Autowired
    private IAiSipCallTaskService aiSipCallTaskService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询aiSIP外呼任务列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AiSipCallTask aiSipCallTask)
    {
        startPage();
        List<AiSipCallTask> list = aiSipCallTaskService.selectAiSipCallTaskList(aiSipCallTask);
        return getDataTable(list);
    }

    /**
     * 导出aiSIP外呼任务列表
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:export')")
    @Log(title = "aiSIP外呼任务", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AiSipCallTask aiSipCallTask)
    {
        List<AiSipCallTask> list = aiSipCallTaskService.selectAiSipCallTaskList(aiSipCallTask);
        ExcelUtil<AiSipCallTask> util = new ExcelUtil<>(AiSipCallTask.class);
        return util.exportExcel(list, "aiSIP销售端外呼任务数据");
    }

    /**
     * 获取aiSIP外呼任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:query')")
    @GetMapping(value = "/{batchId}")
    public AjaxResult getInfo(@PathVariable("batchId") Long batchId)
    {
        return AjaxResult.success(aiSipCallTaskService.selectAiSipCallTaskByBatchId(batchId));
    }

    /**
     * 新增aiSIP外呼任务
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:add')")
    @Log(title = "aiSIP外呼任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AiSipCallTask aiSipCallTask)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        aiSipCallTask.setCompanyId(loginUser.getUser().getCompanyId());
        aiSipCallTask.setCompanyUserId(loginUser.getUser().getUserId());
        aiSipCallTask.setCreateBy(loginUser.getUser().getUserName());
        aiSipCallTask.setCreateTime(new Date());
        // 外呼速率=1/接通率
        if (null != aiSipCallTask.getConntectRate() && aiSipCallTask.getConntectRate() > 0) {
            aiSipCallTask.setRate(aiSipCallTask.getConntectRate()/100.0);
        }
        return toAjax(aiSipCallTaskService.insertAiSipCallTask(aiSipCallTask));
    }

    /**
     * 修改aiSIP外呼任务
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:edit')")
    @Log(title = "aiSIP外呼任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AiSipCallTask aiSipCallTask)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        aiSipCallTask.setUpdateBy(loginUser.getUser().getUserName());
        aiSipCallTask.setUpdateTime(new Date());
        return toAjax(aiSipCallTaskService.updateAiSipCallTask(aiSipCallTask));
    }

    /**
     * 删除aiSIP外呼任务
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:remove')")
    @Log(title = "aiSIP外呼任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{batchIds}")
    public AjaxResult remove(@PathVariable Long[] batchIds)
    {
        return toAjax(aiSipCallTaskService.deleteAiSipCallTaskByBatchIds(batchIds));
    }

    /**
     * 启动aiSIP外呼任务
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:startTask')")
    @Log(title = "启动aiSIP外呼任务", businessType = BusinessType.UPDATE)
    @PostMapping("/startTask/{batchId}")
    public AjaxResult startTask(@PathVariable Long batchId)
    {
        return toAjax(aiSipCallTaskService.startTask(batchId));
    }

    /**
     * 暂停aiSIP外呼任务
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:stopTask')")
    @Log(title = "暂停aiSIP外呼任务", businessType = BusinessType.UPDATE)
    @PostMapping("/stopTask/{batchId}")
    public AjaxResult stopTask(@PathVariable Long batchId)
    {
        return toAjax(aiSipCallTaskService.stopTask(batchId));
    }

    /**
     * 导入外呼号码模板
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:commonImportExcel')")
    @Log(title = "导入外呼号码", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/common/importExcel")
    public AjaxResult commonImportExcel(
            @RequestParam("batchId") Long batchId,
            @RequestParam("file") MultipartFile file) throws Exception {
        List<CommonPhoneModel> phoneList = parseExcelFile(file);
        return toAjax(aiSipCallTaskService.commonImportExcel(batchId, phoneList,buildCallPhone()));
    }

    /**
     * 导入外呼号码数据
     */
    @PostMapping(value = "/common/importData/{batchId}")
    public AjaxResult commonImportData(
            @PathVariable("batchId") Long batchId,
            @RequestBody List<CommonPhoneModel> phoneList){

        return toAjax(aiSipCallTaskService.commonImportExcel(batchId, phoneList,buildCallPhone()));
    }

    /**
     * 构建页面导入通话基础数据
     */
    private AiSipCallPhone buildCallPhone() {
        AiSipCallPhone callPhone = new AiSipCallPhone();
        callPhone.setCallType("0");
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        callPhone.setCompanyId(loginUser.getUser().getCompanyId());
        callPhone.setCompanyUserId(loginUser.getUser().getUserId());
        callPhone.setCompanyUserName(loginUser.getUser().getUserName());
        return callPhone;
    }
    /**
     * 解析 Excel 文件为电话号码列表
     */
    private List<CommonPhoneModel> parseExcelFile(MultipartFile file) throws Exception {
        List<CommonPhoneModel> phoneList = new ArrayList<>();
        DataFormatter formatter = new DataFormatter();

        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {

            Sheet sheet = workbook.getSheetAt(0);

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                CommonPhoneModel phone = new CommonPhoneModel();

                // 读取客户姓名（第 1 列）
                Cell nameCell = row.getCell(0);
                if (nameCell != null) {
                    String name = formatter.formatCellValue(nameCell);
                    phone.setNoticeContent(name);
                    JSONObject bizJson = new JSONObject();
                    bizJson.put("custName", name);
                    phone.setBizJson(bizJson);
                }

                // 读取电话号码（第 2 列）
                Cell phoneCell = row.getCell(1);
                if (phoneCell != null) {
                    phone.setPhoneNum(formatter.formatCellValue(phoneCell));
                }

                phoneList.add(phone);
            }
        }
        return phoneList;
    }

    /**
     * 下载指定类型的模板文件
     * @param taskType 1 为 ai 外呼
     */
    @PreAuthorize("@ss.hasPermi('company:aiSipCall:task:download:template')")
    @GetMapping("/download/template/{taskType}")
    public ResponseEntity<Resource> downloadTemplateByType(@PathVariable("taskType") Integer taskType) {
        if (taskType == null || taskType != 1) {
            throw new RuntimeException("不支持的模板类型：" + taskType);
        }

        String templateName = "AICallList.xlsx";
        String filePath = "C:\\fs\\AiSipCallTemplate\\" + templateName;
        Resource resource = new FileSystemResource(filePath);

        if (!resource.exists()) {
            throw new RuntimeException("模板文件不存在：" + filePath);
        }

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + templateName)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

}
