package com.fs.app.controller;


import com.fs.app.annotation.Login;
import com.fs.app.param.FsDoctorRegisterParam;
import com.fs.app.param.FsUserEditParam;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.his.domain.FsDoctor;
import com.fs.his.domain.FsPackage;
import com.fs.his.domain.FsUser;
import com.fs.his.param.FsUserCouponUParam;
import com.fs.his.param.FsUserEditPushParam;
import com.fs.his.service.IFsDoctorService;
import com.fs.his.service.IFsPackageService;
import com.fs.his.service.IFsUserCouponService;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.qrcode.QRCodeUtils;
import com.fs.his.vo.FsDoctorListUVO;
import com.fs.his.vo.FsUserCouponCountUVO;
import com.fs.his.vo.FsUserCouponListUVO;
import com.fs.qw.service.IQwAppContactWayService;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fs.common.utils.SecurityUtils.getUserId;
import static com.fs.his.utils.PhoneUtil.decryptPhoneMk;
import static com.fs.his.utils.PhoneUtil.encryptPhone;


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


    @Autowired
    private IFsUserService userService;
    @Autowired
    private IFsDoctorService doctorService;
    @Autowired
    private IFsPackageService packageService;
    @Autowired
    private IFsUserCouponService couponService;
    @Autowired
    private IQwAppContactWayService qwAppContactWayService;

    /**
     * 获取用户信息
     * @param request
     * @return     */
    @Login
    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public R getUserInfo(HttpServletRequest request){
        try {
            FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));
            if (user.getPhone()!=null&&user.getPhone().length()>11&&!user.getPhone().matches("\\d+")){
                user.setPhone(decryptPhoneMk(user.getPhone()));
            }
            Map<String,Object> map=new HashMap<>();
            map.put("user",user);
            return R.ok(map);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }

    @Login
    @ApiOperation("查看推送设置")
    @GetMapping("/getUserPushSetting")
    public R getUserPushSetting(HttpServletRequest request){
        FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));
        Map<String,Object> map=new HashMap<>();
        map.put("isPush",user.getIsPush());
        map.put("isIndividuationPush",user.getIsIndividuationPush());
        return R.ok().put("data",map);
    }

    @Login
    @ApiOperation("保存推送设置")
    @PostMapping("/editUserPushSetting")
    public R editUserPushSetting(@RequestBody FsUserEditPushParam param, HttpServletRequest request){
        FsUser map=new FsUser();
        BeanUtils.copyProperties(param,map);
        map.setUserId(Long.parseLong(getUserId()));
        if(userService.updateFsUser(map)>0){
            return R.ok("保存成功");
        }
        else{
            return R.error("保存失败");
        }
    }

    @ApiOperation("检测是否登录")
    @GetMapping("/checkLogin")
    public R checkLogin(HttpServletRequest request){
        if(StringUtils.isEmpty(getUserId())){
            //未登录
            return R.error("未登录");
        }
        else{
            //登录
            String token = jwtUtils.generateToken(Long.parseLong(getUserId()));
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            return R.ok("认证成功").put("userId",getUserId()).put("token",token);
        }
    }




    @Login
    @ApiOperation("修改用户信息")
    @PostMapping("/editUser")
    public R editUser(@RequestBody FsUserEditParam param, HttpServletRequest request){
        FsUser map=new FsUser();
        BeanUtils.copyProperties(param,map);
        map.setUserId(Long.parseLong(getUserId()));
        if(userService.updateFsUser(map)>0){
            return R.ok("修改成功");
        }
        else{
            return R.error("修改失败");
        }
    }


    @Login
    @ApiOperation("注册医生")
    @PostMapping("/registerDoctor")
    public R registerDoctor(@Validated  @RequestBody FsDoctorRegisterParam param, HttpServletRequest request){
        FsDoctor doctor= doctorService.selectFsDoctorByUserId(Long.parseLong(getUserId()));
        if(doctor!=null){
            if(doctor.getIsAudit().equals(0)){
                return R.error("您已提交申请,等待审核...");
            }
            else if(doctor.getIsAudit().equals(1)){
                return R.error("您已提交申请");
            }
        }
        doctor=new FsDoctor();
        BeanUtils.copyProperties(param,doctor);
        doctor.setUserId(Long.parseLong(getUserId()));
        doctor.setIsAudit(0);
        doctor.setPassword(Md5Utils.hash(param.getPassword()));
        doctor.setStatus(0);
        doctor.setBalance(new BigDecimal(0));
        doctor.setPriceJson("[{\"price\":1.00,\"type\":1},{\"price\":1.00,\"type\":2}]");
        if(doctorService.insertFsDoctor(doctor)>0){
            return R.ok("注册成功");
        }
        else{
            return R.error("注册失败");
        }
    }
    @Login
    @ApiOperation("获取用户优惠券")
    @GetMapping("/getMyCouponList")
    public R getMyCouponList(FsUserCouponUParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsUserCouponListUVO> list=couponService.selectFsUserCouponListUVO(param);
        PageInfo<FsUserCouponListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取用户可用优惠券")
    @GetMapping("/getMyEnableCouponList")
    public R getMyEnableCouponList(FsUserCouponUParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        List<FsUserCouponListUVO> list=couponService.getMyEnableCouponList(param);
        return R.ok().put("data",list);
    }
    @Login
    @ApiOperation("获取用户优惠券数量")
    @GetMapping("/getMyCouponCount")
    public R getMyCouponCount(FsUserCouponUParam param, HttpServletRequest request){
        if (StringUtils.isNotEmpty(getUserId())) {
            param.setUserId(Long.parseLong(getUserId()));
        }
        FsUserCouponCountUVO count =couponService.selectFsUserCouponCountUVO(param);
        return R.ok().put("data",count);
    }

    @ApiOperation("获取APP客服活码")
    @GetMapping("/getAppContactWay/{userId}")
    public R getAppContactWay(@PathVariable("userId") Long userId)
    {
        if (userId==null||userId==0){
            return R.error("UserId不能为空");
        }
        String appContactWayImgCode = qwAppContactWayService.getAppContactWayImgCode(userId);
       // String appContactWayImgCode ="https://wework.qpic.cn/wwpic3az/769765_uPSW3IV5QP6-bsM_1733303905/0";
        File mb = new File("C:\\fs\\qwCode.png");
        if (!mb.exists()) {
            // 创建目录
            throw  new CustomException("模板文件不存在");
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(mb);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Graphics2D pen = image.createGraphics();
        try {
            URL imageUrl = new URL(appContactWayImgCode);
            BufferedImage img = ImageIO.read(imageUrl);
            pen.drawImage(img, 1550, 3270, 500, 500, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(inputStream, ".jpg");
        return R.ok().put("data",url);
    }

}
