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.config.FSConfig;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
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.fastgptApi.util.AudioUtils;
import com.fs.his.param.FsCouponReceiveParam;
import com.fs.his.param.FsHealthTongueUParam;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
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;


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

        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("http://118.24.209.192:7771/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){
                    return R.ok();
                }
            } else {
                return R.error();
            }

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

        return R.error();

    }

}
