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.fs.app.annotation.Login;
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.utils.sign.Md5Utils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyUserCard;
import com.fs.company.param.CompanyUserLoginParam;
import com.fs.company.service.ICompanyUserCardService;
import com.fs.company.service.ICompanyUserService;
import com.fs.core.security.SecurityUtils;
import com.fs.store.domain.FsUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;


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

    @Autowired
    private FSConfig fsConfig;
    @Autowired
    RedisCache redisCache;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private ICompanyUserCardService companyUserCardService;
    @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(),5, TimeUnit.DAYS);
            return R.ok().put("companyUserToken", Md5Utils.hash(companyUser.getUserId().toString()));
        } catch (Exception e){

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

    @ApiOperation("获取销售信息")
    @GetMapping("/getUserInfo")
    public R getUserInfo(@RequestParam("token")String token, HttpServletRequest request){
        Long userId=redisCache.getCacheObject("company-user-token:"+token);
        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);
    }

    @ApiOperation("获取销售名片")
    @GetMapping("/getCompanyUserCard")
    public R getCompanyUserCard(@RequestParam("cardId")Long cardId,HttpServletRequest request){
        //获取用户码
        CompanyUserCard companyUserCard=companyUserCardService.selectCompanyUserCardById(cardId);
        return R.ok().put("data",companyUserCard);
    }

    @Login
    @ApiOperation("获取支付宝收款码")
    @GetMapping("/getQrImg")
    public R getQrImg(@RequestParam("token")String token,HttpServletRequest request){
        Long userId=redisCache.getCacheObject("company-user-token:"+token);
        try {
            CompanyUser companyUser=companyUserService.selectCompanyUserById(userId);
            File newFile = new File("qr.jpg");
            File newFileT = new File("simsunb.ttf");
            try {
                InputStream stream =  getClass().getClassLoader().getResourceAsStream("qr.jpg");
                FileUtils.copyInputStreamToFile(stream, newFile);
                // if(!newFile.exists()){
                //     InputStream stream =  getClass().getClassLoader().getResourceAsStream("fx.jpg");
                //     FileUtils.copyInputStreamToFile(stream, newFile);
                // }
                if(!newFileT.exists()){
                    InputStream streamT =  getClass().getClassLoader()
                            .getResourceAsStream("simsunb.ttf");
                    FileUtils.copyInputStreamToFile(streamT, newFileT);
                }
            } catch (IOException e) {

                throw new CustomException(e.getMessage());
            }

            try {
                String url=fsConfig.getQrPath()+"/qr-"+userId+".jpg";
                File outputFile = new File(url);
                if(!outputFile.exists())
                {
                    try {
                        outputFile.createNewFile();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                Font font =  Font.createFont(Font.TRUETYPE_FONT, newFileT);
//                Font f= font.deriveFont(Font.PLAIN,20);
//                ImgUtil.pressText(//
//                        newFile,
//                        outputFile,
//                        companyUser.getNickName()+" 为您服务",
//                        Color.BLACK,
//                        f, //字体
//                        65, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
//                        100, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
//                        0.8f//透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
//                );
                File qr = new File(fsConfig.getQrPath()+"/qr-"+userId+".png");
                if(!qr.exists())
                {
                    try {
                        qr.createNewFile();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                QrCodeUtil.generate( "http://alipay.yjf.runtzh.com/#/?companyId="+companyUser.getCompanyId()+"&companyUserId="+companyUser.getUserId(), 200, 200,
                        FileUtil.file(fsConfig.getQrPath()+"/qr-"+userId+".png"));
                ImgUtil.pressImage(
                        newFile,
                        outputFile,
                        ImgUtil.read(qr), //QR图片
                        0, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        20, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        1f
                );
                return R.ok().put("url","profile/qr/qr-"+userId+".jpg");

            } catch (Exception e) {
                e.printStackTrace();
                return R.error("操作异常");
            }
        } catch (Exception e){

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



}
