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.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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import static com.fs.app.constant.CommonConstant.REDIS_KEY_COMPANY_USER_TOKEN;


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

    @Autowired
    private FSConfig fsConfig;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private ICompanyUserCardService companyUserCardService;

    @PostMapping("/login")
    public R login(@RequestBody CompanyUserLoginParam param){
        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("用户已禁用");

            }
            if(!SecurityUtils.matchesPassword(param.getPassword(),companyUser.getPassword())){
                return R.error("密码不正确");
            }
            redisCache.setCacheObject(REDIS_KEY_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){
        Long userId=redisCache.getCacheObject(REDIS_KEY_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){
        //获取用户码
        CompanyUserCard companyUserCard=companyUserCardService.selectCompanyUserCardById(cardId);
        return R.ok().put("data",companyUserCard);
    }

    @Login
    @ApiOperation("获取支付宝收款码")
    @GetMapping("/getQrImg")
    public R getQrImg(@RequestParam("token")String token){
        Long userId=redisCache.getCacheObject(REDIS_KEY_COMPANY_USER_TOKEN + token);
        try {
            CompanyUser companyUser=companyUserService.selectCompanyUserById(userId);
            File newFile = new File("qr.jpg");
            File newFileT = new File("simsunb.ttf");
            InputStream stream =  getClass().getClassLoader().getResourceAsStream("qr.jpg");

            Asserts.notNull(stream,"收款码不存在!");

            FileUtils.copyInputStreamToFile(stream, newFile);
            if(!newFileT.exists()){
                InputStream streamT =  getClass().getClassLoader()
                        .getResourceAsStream("simsunb.ttf");
                Asserts.notNull(streamT,"字体文件不存在!");
                FileUtils.copyInputStreamToFile(streamT, newFileT);
            }

            String url=fsConfig.getQrPath()+"/qr-"+userId+".jpg";
            File outputFile = new File(url);
            if(!outputFile.exists()) {
                outputFile.createNewFile();
            }
            File qr = new File(fsConfig.getQrPath()+"/qr-"+userId+".png");
            if(!qr.exists()) {
                qr.createNewFile();
            }
            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){
            log.error("获取收款码异常", e);
            return R.error("操作异常");
        }
    }



}
