package com.fs.app.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.app.annotation.Login;
import com.fs.app.param.*;
import com.fs.app.service.IAppService;
import com.fs.app.vo.CompanySubUserVO;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.constant.UserConstants;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.PatternUtils;
import com.fs.common.utils.bean.BeanUtils;
import com.fs.company.domain.*;
import com.fs.company.mapper.CompanyRoleMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.param.companyUserAddPrintParam;
import com.fs.company.service.*;
import com.fs.company.vo.CompanyTagUserVO;
import com.fs.company.vo.CompanyUserChangeApplyVO;
import com.fs.config.ai.AiHostProper;
import com.fs.core.security.SecurityUtils;
import com.fs.course.service.IFsCourseRedPacketLogService;
import com.fs.course.service.IFsCourseWatchLogService;
import com.fs.course.service.IFsUserCompanyUserService;
import com.fs.fastGpt.domain.FastgptChatVoiceHomo;
import com.fs.fastGpt.mapper.FastgptChatVoiceHomoMapper;
import com.fs.fastgptApi.util.AudioUtils;
import com.fs.fastgptApi.vo.AudioVO;
import com.fs.qw.dto.UserProjectDTO;
import com.fs.sop.domain.QwSopTempVoice;
import com.fs.sop.service.IQwSopTempVoiceService;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.service.ISysDictDataService;
import com.fs.system.vo.DictVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "企业用户接口")
@RestController
@RequestMapping("/app/companyUser")
@AllArgsConstructor
public class CompanyUserController extends AppBaseController {

    private final ICompanyUserService companyUserService;
    private final ICompanyService companyService;
    private final ICompanyDeptService companyDeptService;
    private final IFsCourseWatchLogService courseWatchLogService;
    private final IFsCourseRedPacketLogService courseRedPacketLogService;
    private final ICompanyUserChangeApplyService companyUserChangeApplyService;
    private final CompanyRoleMapper companyRoleMapper;
    private final IAppService appService;
    private final RedisCache redisCache;
    private final CompanyUserMapper companyUserMapper;
    private final IQwSopTempVoiceService voiceService;
    private final AiHostProper aiHostProper;
    private final ISysDictDataService dictDataService;
    private final IFsUserCompanyUserService fsUserCompanyUserService;
    private final ICompanyTagUserService companyTagUserService;
    private final FastgptChatVoiceHomoMapper fastgptChatVoiceHomoMapper;
    public static final String SOP_TEMP_VOICE_KEY = "sop:tempVoice";

    @Login
    @ApiOperation("查询用户列表")
    @GetMapping("/getCompanyUserList")
    public R getCompanyUserList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.debug("查询用户列表 pageNum: {}, pageSize: {}", pageNum, pageSize);

        Long userId = Long.parseLong(getUserId());
        CompanyUser companyUser = companyUserService.selectCompanyUserById(userId);
        List<CompanyRole> companyRoles = companyRoleMapper.selectRolePermissionByUserId(userId);
        List<CompanyUser> companyUsers;

        // 判断是否管理员 或者包含 1:全部数据权限
        if (companyUser.isAdmin() || companyRoles.stream().anyMatch(r -> "1".equals(r.getDataScope()))) {
            PageHelper.startPage(pageNum, pageSize);
            companyUsers = companyUserService.getCompanyUserListByCompanyIdAndDeptId(companyUser.getCompanyId(), null);
        }
        // 判断是否包含 3:本部门数据权限 4:本部门及以下数据权限
        else if (companyRoles.stream().anyMatch(r -> "3".equals(r.getDataScope()) || "4".equals(r.getDataScope()))) {
            PageHelper.startPage(pageNum, pageSize);
            companyUsers = companyUserService.getCompanyUserListByCompanyIdAndDeptId(companyUser.getCompanyId(), companyUser.getDeptId());
        }
        // 默认空 -- 判断是否包含 5:仅可查看本人
        else {
            companyUsers = new ArrayList<>();
        }
        PageInfo<CompanyUser> page = new PageInfo<>(companyUsers);

        // 转换对象
        List<CompanySubUserVO> users = page.getList().stream().map(u -> {
            CompanySubUserVO vo = new CompanySubUserVO();
            BeanUtils.copyProperties(u, vo);

            Map<String, Object> params = new HashMap<>();
            params.put("date", LocalDate.now());
            params.put("companyUserId", u.getUserId());
            params.put("logTypes", Arrays.asList(1,2,4));

            // 今日观看人数
            int count = courseWatchLogService.countByMap(params);
            vo.setTodayWatchCount(count);

            // 今日完播人数
            params.put("logTypes", Collections.singletonList(2));
            int finishCount = courseWatchLogService.countByMap(params);
            vo.setTodayFinishCount(finishCount);

            // 今日完播率
            BigDecimal rate = count > 0 ? BigDecimal.valueOf(finishCount)
                    .divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100)) : BigDecimal.ZERO;
            vo.setTodayFinishRate(rate);

            // 今日红包金额
            BigDecimal amount = courseRedPacketLogService.getSumByCompanyUserIdId(u.getUserId());
            vo.setTodayRedPacketAmount(amount);

            // 是否存在会员转移申请
            Wrapper<CompanyUserChangeApply> applyWrapper = Wrappers.<CompanyUserChangeApply>lambdaQuery()
                    .eq(CompanyUserChangeApply::getFrom, u.getUserId())
                    .orderByDesc(CompanyUserChangeApply::getApplyTime)
                    .last("limit 1");
            CompanyUserChangeApply apply = companyUserChangeApplyService.getOne(applyWrapper);
            int applyStatus = 3; // 不存在
            if (Objects.nonNull(apply)) {
                applyStatus = apply.getStatus();
            }
            vo.setApplyStatus(applyStatus);

            return vo;
        }).collect(Collectors.toList());

        PageInfo<CompanySubUserVO> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(page, pageInfo);
        pageInfo.setList(users);

        return R.ok().put("data", pageInfo);
    }

    @Login
    @ApiOperation("获取销售信息")
    @GetMapping("/getCompanyUserInfo")
    public R getCompanyUserInfo(@ApiParam(name = "companyUserId", value = "销售用户ID", required = true)
                                @RequestParam Long companyUserId) {
        return R.ok().put("data", companyUserService.selectCompanyUserById(companyUserId));
    }

    @Login
    @ApiOperation("修改用户信息")
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@Valid @RequestBody CompanyUserUpdateParam param) {
        CompanyUser companyUser = companyUserService.selectCompanyUserById(param.getUserId());
        if (Objects.isNull(companyUser)) {
            throw new ServiceException("用户不存在");
        }

        companyUser.setUserId(param.getUserId());
        companyUser.setNickName(param.getNickName());
        companyUser.setPhonenumber(param.getPhoneNumber());
        companyUser.setRemark(param.getRemark());
        companyUserService.updateCompanyUser(companyUser);
        return R.ok();
    }

    @ApiOperation("注册")
    @PostMapping("/resisterCompanyUser")
    public R resisterCompanyUser(@Valid @RequestBody CompanyUserParam param) {
        CompanyUser upCompanyUser = companyUserService.selectCompanyUserById(param.getCompanyUserId());
        if (Objects.isNull(upCompanyUser)) {
            return R.error("邀请销售不存在");
        }

        Company company = companyService.selectCompanyById(upCompanyUser.getCompanyId());
        if (Objects.isNull(company)) {
            return R.error("公司不存在");
        }

        // 判断用户数量是否已达到上线
        Integer count = companyUserService.selectCompanyUserCountByCompanyId(upCompanyUser.getCompanyId());
        if(count > company.getLimitUserCount()) {
            return R.error("用户数量已达到上限");
        }

        if (UserConstants.NOT_UNIQUE.equals(String.valueOf(companyUserService.checkUserName(param.getPhoneNumber())))) {
            return R.error("注册用户'" + param.getPhoneNumber() + "'失败，登录账号已存在");
        }

        // 密码校验
        if (!PatternUtils.checkPassword(param.getPassword())) {
            return R.error("密码格式不正确,需包含字母、数字和特殊字符,长度为 8-20位");
        }

        // 组装参数
        CompanyUser companyUser = new CompanyUser();
        BeanUtils.copyProperties(param, companyUser);

        companyUser.setUserName(param.getPhoneNumber());
        companyUser.setUserType("01");
        companyUser.setPhonenumber(param.getPhoneNumber());
        companyUser.setPassword(SecurityUtils.encryptPassword(companyUser.getPassword()));
        companyUser.setCreateTime(new Date());
        companyUser.setIsAudit(0);
        companyUser.setParentId(upCompanyUser.getUserId());
//        companyUser.setCompanyId(upCompanyUser.getCompanyId());
        companyUser.setCompanyId(company.getCompanyId());

        // 部门
        CompanyDept dept = companyDeptService.getDefaultCompanyDeptByCompanyId(upCompanyUser.getCompanyId());
        if (Objects.nonNull(dept)) {
            companyUser.setDeptId(dept.getDeptId());
        }

        companyUserService.insertUser(companyUser);
        return R.ok();
    }

    @Login
    @ApiOperation("接收群管列表")
    @GetMapping("/companyUserListByCompanyId")
    public R CompanyUserListByCompanyId(){
        // 查询公司下销售
        CompanyUser companyUser = new CompanyUser();
        companyUser.setCompanyId(getCompanyId());
        List<CompanyUser> companyUsers = companyUserService.selectCompanyUserList(companyUser);
        return R.ok().put("data",companyUsers);
    }

    @Login
    @RepeatSubmit
    @ApiOperation("更换会员归属申请")
    @PostMapping("/changeUserParentApply")
    public R changeVipUser(@RequestBody CompanyUserChangeApplyParam param) {
        // 参数校验
        CompanyUser fromUser = companyUserService.selectCompanyUserById(param.getFrom());
        if (Objects.isNull(fromUser)) {
            return R.error("原归属销售不存在");
        }

        CompanyUser toUser = companyUserService.selectCompanyUserById(param.getTo());
        if (Objects.isNull(toUser)) {
            throw new ServiceException("申请更换归属销售不存在");
        }

        if (Objects.equals(fromUser.getUserId(), toUser.getUserId())) {
            throw new ServiceException("申请更换归属销售不能与原归属销售相同");
        }

        if (param.getType() != 0 && param.getType() != 1) {
            throw new ServiceException("类型不正确");
        }

        if (param.getType() == 1 && (CollectionUtils.isEmpty(param.getIds()))
                &&(CollectionUtils.isEmpty(param.getProject()))
                &&(CollectionUtils.isEmpty(param.getTagList()))) {
            throw new ServiceException("请先选择会员！");
        }

        // 存在待审核的申请不能再次申请
        Wrapper<CompanyUserChangeApply> applyWrapper = Wrappers.<CompanyUserChangeApply>lambdaQuery()
                .eq(CompanyUserChangeApply::getFrom, fromUser.getUserId())
                .eq(CompanyUserChangeApply::getStatus, 0);
        if (companyUserChangeApplyService.count(applyWrapper) > 0) {
            throw new ServiceException("存在待审核申请");
        }
        CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
        List<UserProjectDTO> list = param.getIds();
        if(CollectionUtils.isEmpty(list)){
            List<UserProjectDTO> userProjectDTOS = addUserId(param.getProject(),param.getTagList(),param.getFrom());
            if (CollectionUtils.isNotEmpty(userProjectDTOS)){
                list.addAll(userProjectDTOS);
            }
        }
        // 添加申请
        companyUserChangeApplyService.apply(param.getFrom(), param.getTo(), param.getType(),list, companyUser.getCompanyId(), companyUser.getUserName());
        return R.ok();
    }

    /**
     * 查询标签和项目中的会员添加
     * @param tagList
     * @param companyUserId
     * @return
     */
    private List<UserProjectDTO> addUserId(List<Long> projects, List<Long> tagList, Long companyUserId) {
        // Prepare parameters map
        Map<String, Object> params = new HashMap<>();

        if (CollectionUtils.isNotEmpty(projects)) {
            params.put("projectIds", projects);
        } else {
            params.put("tagIds", tagList);
        }

        // Set company user ID
        Long effectiveCompanyUserId = ObjectUtil.isNotEmpty(companyUserId)
                ? companyUserId
                : getCompanyUserId();
        params.put("companyUserId", effectiveCompanyUserId);

        // Get data from service
        List<CompanyTagUserVO> voList = companyTagUserService.selectUserByMap(params);
        if (CollectionUtils.isEmpty(voList)) {
            return Collections.emptyList();
        }

        // Transform data
        return voList.stream()
                .map(vo -> {
                    UserProjectDTO dto = new UserProjectDTO();
                    dto.setUserId(vo.getUserId());
                    dto.setProjectId(vo.getProjectId());
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Login
    @ApiOperation("申请列表")
    @GetMapping("/applyList")
    public R applyList(@RequestParam(required = false) Integer status,
                       @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.debug("申请列表 status: {}, pageNum: {}, pageSize: {}", status, pageNum, pageSize);

        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("companyId", getCompanyId());

        PageHelper.startPage(pageNum, pageSize);
        List<CompanyUserChangeApplyVO> list = companyUserChangeApplyService.selectApplyListByMap(map);
        PageInfo<CompanyUserChangeApplyVO> page = new PageInfo<>(list);
        return R.ok().put("data", page);
    }

    @Login
    @ApiOperation("部门树列表")
    @GetMapping("/deptList")
    public R deptList() {
        return R.ok().put("data", appService.getDeptTreeSelect(getCompanyId()));
    }

    @Login
    @ApiOperation("岗位列表")
    @GetMapping("/postList")
    public R postList() {
        return R.ok().put("data", appService.postList(getCompanyId()));
    }

    @Login
    @ApiOperation("角色列表")
    @GetMapping("/roleList")
    public R roleList() {
        return R.ok().put("data", appService.roleList(getCompanyId()));
    }

    @Login
    @ApiOperation("修改用户部门和岗位")
    @PostMapping("/changeUserDeptAndPost")
    public R changeUserDeptAndPost(@Valid @RequestBody ChangeUserDeptAndPostParam param) {
        log.debug("changeUserDeptAndPost param: {}", JSON.toJSONString(param));

        CompanyUser companyUser = companyUserService.selectCompanyUserByUserId(Long.parseLong(getUserId()));
        if (!companyUser.isAdmin()) {
            return R.error("没有权限");
        }

        appService.changeUserDeptAndPost(param);
        return R.ok();
    }

    @ApiOperation("查询指定公司中存在会员的项目")
    @PostMapping("/getDictByKeyByProject")
    public R getDictByKey(
            @RequestBody TagProjectParam tagProjectParam){
        List<DictVO> dictVOS=dictDataService.selectDictDataListByType("sys_course_project");
        Map<String,Object> param = new HashMap<>();
        param.put("tagIds",tagProjectParam.getTagIds());
        param.put("companyUserId",tagProjectParam.getCompanyUserId());
        List<Long> projectIds =fsUserCompanyUserService.selectFsUserCompanyUserList(param);
        if (CollectionUtils.isEmpty(projectIds)){
            return R.ok().put("data",new ArrayList<DictVO>());
        }

        List<DictVO> filteredDictVOS = dictVOS.stream()
                .filter(dictVO -> projectIds.contains(Long.parseLong(dictVO.getDictValue())))
                .collect(Collectors.toList());
        return R.ok().put("data",filteredDictVOS);
    }

    @ApiOperation("查询所有项目")
    @GetMapping("/getDictProject")
    public R getDictProject(){
        List<DictVO> dictVOS = dictDataService.selectDictDataListByType("sys_course_project");
        return R.ok().put("data",dictVOS);
    }

    /**
     * 当只有模板文字text时，生成表中对应条的voice_url和user_voice_url
     * @param id            qw_sop_temp_voice的id
     * @return
     */
    @GetMapping("/companyUserVoice")
    public R companyUserVoice(@RequestParam("id") Long id){
        AudioVO audioVO = new AudioVO();
        Long companyUserId = getCompanyUserId();
        List<QwSopTempVoice> sopTempVoices = redisCache.getVoiceAllList(SOP_TEMP_VOICE_KEY + ":" + companyUserId);
        if(sopTempVoices != null && !sopTempVoices.isEmpty()){
            List<Long> collect = sopTempVoices.stream().map(QwSopTempVoice::getId).collect(Collectors.toList());
            if (collect.contains(id)){
                return R.ok().put("code",202).put("msg","该语音已进入转换,请完成后再试。");
            }
        }

        if(companyUserId != null){
            CompanyUser companyUser = companyUserMapper.selectCompanyUserByCompanyUserId(companyUserId);
            if(companyUser != null && companyUser.getVoicePrintUrl() == null){
                return R.ok().put("code",201).put("msg","账号未录制声纹，请录制后再试！");
            }
        }

        QwSopTempVoice qwSopTempVoice = voiceService.selectQwSopTempVoiceById(id);
        if(qwSopTempVoice != null && qwSopTempVoice.getCompanyUserId() != null){
            List<FastgptChatVoiceHomo> homos = fastgptChatVoiceHomoMapper.selectFastgptChatVoiceHomoList(new FastgptChatVoiceHomo());
            audioVO = AudioUtils.createUserUrlAndUrl(homos,qwSopTempVoice.getCompanyUserId(), qwSopTempVoice.getVoiceTxt().replace(" ",""));
            if(audioVO != null && audioVO.getWavUrl() != null &&  audioVO.getUrl() != null){
                qwSopTempVoice.setVoiceUrl(audioVO.getUrl());
                qwSopTempVoice.setUserVoiceUrl(audioVO.getWavUrl());
                qwSopTempVoice.setDuration(audioVO.getDuration());
                qwSopTempVoice.setRecordType(1);
                voiceService.updateQwSopTempVoice(qwSopTempVoice);
            }
        }
        return R.ok().put("data", audioVO);
    }
    @Login
    @ApiOperation("上传声纹")
    @PostMapping("/addVoicePrintUrl")
    public R addVoicePrintUrl(@RequestBody companyUserAddPrintParam param) throws Exception {
        Long userId=getCompanyUserId();
        if(userId==null){
            return R.error(403,"用户失效");
        }
        CompanyUser companyUser = new CompanyUser();
        companyUser.setUserId(userId);
        companyUser.setVoicePrintUrl(param.getVoicePrintUrl());

        //转换音频格式 mp3-wav
        String s = AudioUtils.audioWAVFromUrl(param.getVoicePrintUrl());

        //保存文件并且上传存储桶
        System.out.println(s);
        File file = new File(s);
        FileInputStream fileInputStream = new FileInputStream(file);
        CloudStorageService storage = OSSFactory.build();
        String wavUrl = storage.uploadSuffix(fileInputStream, ".wav");

        //更新销售员工声纹
        companyUser.setVoicePrintUrl(wavUrl);
        companyUserMapper.updateCompanyUser(companyUser);

        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(aiHostProper.getCommonApi()+"/app/common/addCompanyAudio");
            String json = "{\"url\":\""+wavUrl+"\",\"id\":\""+userId+"\"}";
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == 200) {
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(responseBody);
                Integer code = (Integer)jsonObject.get("code");
                if (code==200){
                    voiceService.insertQwSopTempVoiceModel(userId);
                    return R.ok();
                }
            } else {
                return R.error();
            }

            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.error();

    }

    /**
     * 当只有user_voice_url时，生成表中对应条的voice_url
     * @param userVoiceUrl  wav格式的语音文件
     * @param id            qw_sop_temp_voice的id
     * @return
     */
    @GetMapping("/companyUserVoiceNew")
    public R companyUserVoiceNew( @RequestParam("id") Long id,@RequestParam("userVoiceUrl") String userVoiceUrl){

        AudioVO audioVO = new AudioVO();
        Long companyUserId = getCompanyUserId();
        List<QwSopTempVoice> sopTempVoices = redisCache.getVoiceAllList(SOP_TEMP_VOICE_KEY + ":" + companyUserId);
        if(sopTempVoices != null && !sopTempVoices.isEmpty()){
            List<Long> collect = sopTempVoices.stream().map(QwSopTempVoice::getId).collect(Collectors.toList());
            if (collect.contains(id)){
                return R.ok().put("code",202).put("msg","该语音已进入转换,请完成后再试。");
            }
        }

        QwSopTempVoice qwSopTempVoice = voiceService.selectQwSopTempVoiceByIdAndUserVoiceUrl(id);
        if(qwSopTempVoice != null && qwSopTempVoice.getId() != null){
            audioVO = AudioUtils.createVoiceUrl(qwSopTempVoice.getCompanyUserId(), userVoiceUrl);
            if(audioVO != null && audioVO.getUrl() != null){
                qwSopTempVoice.setVoiceUrl(audioVO.getUrl());
                qwSopTempVoice.setUserVoiceUrl(userVoiceUrl);
                qwSopTempVoice.setDuration(audioVO.getDuration());
                qwSopTempVoice.setRecordType(1);
                voiceService.updateQwSopTempVoice(qwSopTempVoice);
            }
        }
        return R.ok().put("data", audioVO);
    }
    @GetMapping("/querySopVoiceList")
    public TableDataInfo querySopVoiceList(@Param("recordType") Integer recordType){
        startPage();
        QwSopTempVoice sopTempVoice = new QwSopTempVoice();
        sopTempVoice.setRecordType(recordType);
        sopTempVoice.setCompanyUserId(getCompanyUserId());
        List<QwSopTempVoice> sopTempVoices = voiceService.selectQwSopTempVoiceNewList(sopTempVoice);
        return getDataTable(sopTempVoices);
    }
    @GetMapping("/query/{id}")
    public R querySopVoiceById(@PathVariable("id") Long id){
        QwSopTempVoice tempVoice = voiceService.selectQwSopTempVoiceById(id);
        AudioVO audioVO = new AudioVO();
        if(tempVoice != null){
            audioVO.setId(tempVoice.getId());
            audioVO.setVoiceTxt(tempVoice.getVoiceTxt());
            audioVO.setUrl(tempVoice.getVoiceUrl());
            audioVO.setWavUrl(tempVoice.getUserVoiceUrl());
            audioVO.setDuration(tempVoice.getDuration());
            audioVO.setRecordType(tempVoice.getRecordType());
        }
        return R.ok().put("data", audioVO);
    }
    /**
     * 一键转换
     * @return
     */
    @GetMapping("/createUserAllVoice")
    public R createUserAllVoice(){
        QwSopTempVoice sopTempVoice = new QwSopTempVoice();
        sopTempVoice.setRecordType(0);
        Long companyUserId = getCompanyUserId();


        if(companyUserId != null){
            CompanyUser companyUser = companyUserMapper.selectCompanyUserByCompanyUserId(companyUserId);
            if(companyUser != null && companyUser.getVoicePrintUrl() == null){
                return R.ok().put("code",201).put("msg","账号未录制声纹，请录制后再试！");
            }
        }

        sopTempVoice.setCompanyUserId(companyUserId);
        List<QwSopTempVoice> sopTempVoices = voiceService.selectQwSopTempVoiceNewList(sopTempVoice);
        if(sopTempVoices != null && !sopTempVoices.isEmpty()){
            List<Long> newCompanyUserId = redisCache.getVoiceAllList(SOP_TEMP_VOICE_KEY);
            if(newCompanyUserId != null && newCompanyUserId.contains(companyUserId)){
                return R.error().put("code",202).put("msg","语音还未转换完成，请完成后再添加!");
            }else{
                redisCache.setVoice(SOP_TEMP_VOICE_KEY,companyUserId);
                sopTempVoices.forEach(m -> m.setVoiceTxt(m.getVoiceTxt().replace(" ","")));
                redisCache.setVoiceList(SOP_TEMP_VOICE_KEY + ":" + companyUserId, sopTempVoices);
                return R.ok().put("msg","语音已加入队列进行转换，请耐心等待!");
            }
        }
        return null;
    }
}
