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.exception.CustomException;
import com.fs.common.param.BaseQueryParam;
import com.fs.common.utils.OrderUtils;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsUser;
import com.fs.store.domain.FsUserBill;
import com.fs.store.domain.FsUserPromoterApply;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.FsStoreOrderTuiVO;
import com.fs.store.vo.FsStoreProductRelationQueryVO;
import com.fs.store.vo.FsUserExtractVO;
import com.fs.store.vo.FsUserTuiVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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.math.BigDecimal;
import java.util.List;


@Api("个人中心")
@RestController
@RequestMapping(value="/app/user")
public class UserController extends  AppBaseController {

    @Autowired
    private FSConfig fsConfig;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private IFsUserBillService userBillService;
    @Autowired
    private IFsStoreProductRelationService productRelationService;

    @Autowired
    private IFsUserExtractService userExtractService;
    @Autowired
    private IFsUserPromoterApplyService userPromoterApplyService;
    /**
     * 获取用户信息
     * @param request
     * @return     */
    @Login
    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public R getUserInfo(HttpServletRequest request){
        try {
            FsUser user=userService.selectFsUserById(Long.parseLong(getUserId()));
            if (user.getIsShow()==0){
                FsStoreOrder order = orderService.selectOrderByUserIdLimit1(user.getUserId());
                if (order!=null){
                    user.setIsShow(1);
                }
            }
            return R.ok().put("user",user);
        } catch (Exception e){

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

    @Login
    @ApiOperation("检测是否登录")
    @GetMapping("/checkLogin")
    public R checkLogin(HttpServletRequest request){
        return R.ok("认证成功");
    }

    @Login
    @ApiOperation("获取推荐海报")
    @GetMapping("/getTuiImg")
    public R getTuiImg(HttpServletRequest request){
        try {
            FsUser user=userService.selectFsUserById(Long.parseLong(getUserId()));
            if(StringUtils.isEmpty(user.getUserCode())){
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setUserCode(OrderUtils.genUserCode());
                userService.updateFsUser(userMap);
                user.setUserCode(userMap.getUserCode());
            }
            File newFile = new File("fx.jpg");
            File newFileT = new File("simsunb.ttf");
            try {
                InputStream stream =  getClass().getClassLoader().getResourceAsStream("fx.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.getTuiImgPath()+"/tui-"+getUserId()+".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,50);
                ImgUtil.pressText(//
                        newFile,
                        outputFile,
                        user.getNickname()+"邀您加入",
                        Color.BLACK,
                        f, //字体
                        -60, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        900, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        0.8f//透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
                );
                ImgUtil.pressText(//
                        outputFile,
                        outputFile,
                         "邀请码:"+user.getUserCode(),
                        Color.BLACK,
                        f, //字体
                        -40, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        1000, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        0.8f//透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
                );
                File qr = new File(fsConfig.getTuiImgPath()+"/qr-"+getUserId()+".png");
                if(!qr.exists())
                {
                    try {
                        qr.createNewFile();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                QrCodeUtil.generate(fsConfig.getUrl()+"/distribution?userCode="+user.getUserCode(), 300, 300,
                        FileUtil.file(fsConfig.getTuiImgPath()+"/qr-"+getUserId()+".png"));
                ImgUtil.pressImage(
                        outputFile,
                        outputFile,
                        ImgUtil.read(qr), //QR图片
                        -400, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                        900, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                        1f
                );
                return R.ok().put("url","profile/tui/tui-"+getUserId()+".jpg");
            } catch (Exception e) {
                e.printStackTrace();
                return R.error("操作异常");
            }
        } catch (Exception e){

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

    @Login
    @ApiOperation("获取我的推荐人")
    @GetMapping("/getMyTuiList")
    public R getMyTuiList(BaseQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<FsUserTuiVO> list= userService.selectFsUserTuiList(getUserId());
        PageInfo<FsUserTuiVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取用户金额")
    @GetMapping("/getTuiMoney")
    public R getMemberTuiMoney(HttpServletRequest request){
        try {
            FsUser user=userService.selectFsUserById(Long.parseLong(getUserId()));
            BigDecimal yesterdayMoney=userBillService.selectFsUserBillTotalByUserId(getUserId(),"brokerage_price");
            return R.ok().put("nowMoney",user.getNowMoney()).put("brokeragePrice",user.getBrokeragePrice()).put("yesterdayMoney",yesterdayMoney);
        } catch (Exception e){

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

    @Login
    @ApiOperation("获取我的推荐订单")
    @GetMapping("/getMyTuiOrderList")
    public R getMyTuiOrderList(BaseQueryParam param,  HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<FsStoreOrderTuiVO> list= orderService.selectFsStoreOrderTuiListVO(getUserId());
        PageInfo<FsStoreOrderTuiVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取用户佣金记录")
    @GetMapping("/getTuiMoneyLogs")
    public R getTuiMoneyLogs(BaseQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        FsUserBill map=new FsUserBill();
        map.setUserId(Long.parseLong(getUserId()));
        map.setCategory("brokerage_price");
        List<FsUserBill> list=userBillService.selectFsUserBillList(map);
        PageInfo<FsUserBill> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }


    @Login
    @ApiOperation("获取商品足迹")
    @GetMapping("/getProductFoots")
    public R getProductFoots(FsStoreProductRelationQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsStoreProductRelationQueryVO> list=productRelationService.selectFsStoreProductRelationListVOQuery(param);
        PageInfo<FsStoreProductRelationQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("删除足迹")
    @PostMapping("/delProductFoots")
    public R delProductFoots(@RequestBody FsStoreProductFootDelParam param, HttpServletRequest request){
        productRelationService.deleteFsStoreProductRelationById(param.getId());
        return R.ok("操作成功");
    }


    @Login
    @ApiOperation("申请提现")
    @PostMapping("/doExtract")
    public R doExtract(@Validated  @RequestBody FsUseDoExtractParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        return userExtractService.doExtract(param);
    }

    @Login
    @ApiOperation("获取提现记录")
    @GetMapping("/getExtractList")
    public R getExtractList(FsUseExtractQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsUserExtractVO> list=userExtractService.selectFsUserExtractListVOQuery(param);
        PageInfo<FsUserExtractVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("修改用户信息")
    @PostMapping("/editUser")
    public R editUser(@RequestBody FsUserEditParam param, HttpServletRequest request){
        FsUser user=new FsUser();
        user.setUserId(Long.parseLong(getUserId()));
        user.setAvatar(param.getAvatar());
        user.setNickname(param.getNickname());
        if(userService.updateFsUser(user)>0){
            return R.ok("修改成功");
        }
        else{
            return R.error("修改失败");
        }
    }
    @Login
    @ApiOperation("申请推广员")
    @PostMapping("/applyPromoter")
    public R applyPromoter(@RequestBody FsUserPromoterApply param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));

        FsUserPromoterApply promoterApply=userPromoterApplyService.selectFsUserPromoterApplyByUserId(Long.parseLong(getUserId()));
        if(promoterApply!=null){
            return R.error("已提交申请,等待后台审核");
        }
        if(userPromoterApplyService.insertFsUserPromoterApply(param)>0){
            return R.ok("提交成功,等待后台审核");
        }
        else{
            return R.error("提交失败");
        }
    }

    @Login
    @ApiOperation("绑定推广员")
    @PostMapping("/bindPromoter")
    public R bindPromoter(@RequestBody FsUserBindPromoterParam param, HttpServletRequest request){

        FsUser user=userService.selectFsUserById(Long.parseLong(getUserId()));
        if(user.getIsPromoter()==null||user.getIsPromoter()==0){
            FsUser tuiUser=userService.selectFsUserByUserCode(param.getUserCode());
            if(tuiUser!=null){
                FsUser userMap=new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setIsPromoter(1);
                userMap.setSpreadUserId(tuiUser.getUserId());
                userService.updateFsUser(userMap);
                return R.ok("绑定成功");

            }
            else{
                return R.error("邀请码不存在");
            }
        }
        else{
            return R.error("您已是推广员,不能重复绑定");
        }
    }
}
