package com.fs.app.controller;


import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.param.FsBindCompanyUserParam;
import com.fs.common.annotation.Log;
import com.fs.common.config.FSConfig;
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.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.file.OssException;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyUserCard;
import com.fs.company.domain.CompanyUserUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.param.CompanyUserLoginParam;
import com.fs.company.param.companyUserAddPrintParam;
import com.fs.company.service.ICompanyUserCardService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.service.ICompanyUserUserService;
import com.fs.config.ai.AiHostProper;
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.his.param.*;
import com.fs.his.service.IFsPrescribeService;
import com.fs.his.vo.FsPrescribeListDVO;
import com.fs.his.vo.FsPrescribeListUVO;
import com.fs.his.vo.FsPrescribeListVO;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Api("销售接口")
@RestController
@RequestMapping(value="/app/companyUser")
public class CompanyUserController extends  AppBaseController {


    @Autowired
    RedisCache redisCache;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private ICompanyUserUserService companyUserUserService;
    @Autowired
    private IFsPrescribeService fsPrescribeService;
    @Autowired
    private IQwSopTempVoiceService voiceService;
    @Autowired
    private FastgptChatVoiceHomoMapper fastgptChatVoiceHomoMapper;
    @Autowired
    AiHostProper aiHostProper;

    public static final String SOP_TEMP_VOICE_KEY = "sop:tempVoice";
    @PostMapping("/login")
    public R Login(@RequestBody CompanyUserLoginParam param, HttpServletRequest request){
        try {
            CompanyUser companyUser=companyUserService.selectUserByUserName(param.getUserName());
            if(companyUser==null||companyUser.getDelFlag().equals("1")){
                return R.error("用户不存在");
            }
            if(!companyUser.getStatus().equals("0")){
                return R.error("用户已禁用");

            }
            String pwd= SecurityUtils.encryptPassword(param.getPassword());
            if(!SecurityUtils.matchesPassword(param.getPassword(),companyUser.getPassword())){
                return R.error("密码不正确");
            }
            redisCache.setCacheObject("company-user-token:"+Md5Utils.hash(companyUser.getUserId().toString()),companyUser.getUserId(),100, TimeUnit.DAYS);
            return R.ok().put("companyUserToken", Md5Utils.hash(companyUser.getUserId().toString())).put("user",companyUser);
        } catch (Exception e){

            return R.error("操作异常");
        }
    }

    @ApiOperation("获取销售信息")
    @GetMapping("/getUserInfo")
    public R getUserInfo(HttpServletRequest request){

        Long userId=getCompanyUserId();
        if(userId==null){
            return R.error(403,"用户失效");
        }
        CompanyUser companyUser=companyUserService.selectCompanyUserById(userId);
        if(companyUser==null||companyUser.getDelFlag().equals("1")){
            return R.error("用户不存在");
        }
        if(!companyUser.getStatus().equals("0")){
            return R.error("用户已禁用");
        }
        return R.ok().put("data",companyUser);
    }

    @Login
    @ApiOperation("绑定销售")
    @PostMapping("/bindCompanyUser")
    public R bindCompanyUser(@Validated @RequestBody FsBindCompanyUserParam param, HttpServletRequest request){
        CompanyUserUser map=new CompanyUserUser();
        map.setCompanyUserId(param.getCompanyUserId());
        map.setUserId(Long.parseLong(getUserId()));
        List<CompanyUserUser> list= companyUserUserService.selectCompanyUserUserList(map);
        if(list==null||list.size()==0){
            CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
            if(companyUser!=null&&companyUser.getStatus().equals("0")){
                map.setCompanyId(companyUser.getCompanyId());
                companyUserUserService.insertCompanyUserUser(map);
            }
        }
        return R.ok();
    }


    @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();

    }
    @ApiOperation("小程序销售绑定医生")
    @Log(title = "小程序销售绑定医生", businessType = BusinessType.UPDATE)
    @PostMapping("/bindDoctorId")
    public R binDoctor(@RequestBody CompanyUser companyUser){
        return companyUserService.bindDoctor(companyUser);
    }
    @ApiOperation("小程序销售解除绑定医生")
    @Log(title = "小程序销售解除绑定医生", businessType = BusinessType.UPDATE)
    @GetMapping("/unBindDoctorId/{userId}")
    public R unBinDoctor(@PathVariable("userId") Long userId){
        return companyUserService.unBindDoctor(userId);
    }

    @ApiOperation("获取公司收款码")
    @GetMapping("/getCompanyWxaCodeByPayment")
    public R getCompanyWxaCodeByPayment(@RequestParam("companyId")Long companyId,@RequestParam("appId")String appId,HttpServletRequest request){
        //获取用户码
        String WxaCode = redisCache.getCacheObject("company-wxa-code:"+companyId+":"+appId);
        return R.ok().put("data",WxaCode);
    }

    /**
     * 生成绑定连接或者绑定码
     * @return
     */
    @Login
    @ApiOperation("获取绑定链接或者绑定码(唯一绑定)")
    @GetMapping("/getBindInfo")
    public R getBindInfo(){
        Long companyUserId = getCompanyUserId();
        if(companyUserId==null){
            return R.error("该销售不存在");
        }
        return companyUserService.getBindInfo(companyUserId);

    }

    /**
     * 当只有模板文字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);
    }

    /**
     * 当只有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("/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);
    }

    @GetMapping("/querySopVoiceList")
    public TableDataInfo querySopVoiceList(@RequestParam("recordType") Integer recordType){
        startPage();
        QwSopTempVoice sopTempVoice = new QwSopTempVoice();
        sopTempVoice.setRecordType(recordType);
        sopTempVoice.setCompanyUserId(getCompanyUserId());
        List<QwSopTempVoice> sopTempVoices = voiceService.selectQwSopTempVoiceNewList(sopTempVoice);
        return getDataTable(sopTempVoices);
    }

    /**
     * 一键转换
     * @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;
    }
    @Login
    @GetMapping("/getPrescribeList")
    public R getPrescribeList(FsPrescribeListDCompanyParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyUserId(getCompanyUserId());
        param.setStatus(1);
        List<FsPrescribeListDVO> list=fsPrescribeService.selectFsPrescribeListDVOByCompanyUser(param);
        PageInfo<FsPrescribeListDVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }


}
