package com.fs.app.controller;


import cn.hutool.core.lang.Validator;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.app.annotation.Login;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.app.param.FsDoctorRegisterParam;
import com.fs.app.param.FsUserEditParam;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.his.domain.FsDoctor;
import com.fs.his.domain.FsUser;
import com.fs.his.dto.FindUsersByDTO;
import com.fs.his.param.FindUserByParam;
import com.fs.his.param.FsUserCouponUParam;
import com.fs.his.param.FsUserEditPushParam;
import com.fs.his.config.IntegralConfig;
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.PhoneUtil;
import com.fs.his.vo.FsUserCouponCountUVO;
import com.fs.his.vo.FsUserCouponListUVO;
import com.fs.his.vo.UserVo;
import com.fs.live.service.ILiveCommentWsUserTypeService;
import com.fs.qw.service.IQwAppContactWayService;
import com.fs.system.service.ISysConfigService;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
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 javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fs.his.utils.PhoneUtil.decryptPhoneMk;
import static com.fs.his.utils.PhoneUtil.encryptPhone;


@Api("个人中心")
@RestController
@Slf4j
@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;
    @Autowired
    private IFsUserCourseVideoService courseVideoService;

    @Autowired
    private ILiveCommentWsUserTypeService liveCommentWsUserTypeService;

    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    private ISysConfigService configService;
    @Login
    @ApiOperation("获取用户信息")
    @PostMapping("/friendsSearch")
    public R friendsSearch(@RequestBody FindUserByParam param){
        if(param.getPageNum() == null) {
            throw new IllegalArgumentException("分页参数 pageNum 不能为空!");
        }
        if(param.getPageSize() == null) {
            throw new IllegalArgumentException("分页参数 pageSize 不能为空！");
        }

        if(StringUtils.isBlank(param.getKeywords())) {
            return R.ok().put("data",new ArrayList<>());
        }
        PageHelper.startPage(param.getPageNum(), param.getPageSize());

        if(StringUtils.isNotBlank(param.getKeywords())){
            if(Validator.isMobile(param.getKeywords())) {
                param.setKeywords(PhoneUtil.encryptPhone(param.getKeywords()));
            }
        }
        List<FindUsersByDTO> list = fsUserService.findUserByParam(param);
        PageInfo<FindUsersByDTO> listPageInfo=new PageInfo<>(list);

        return R.ok().put("data", listPageInfo);
    }
    /**
     * 获取用户信息
     * @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()));
            }
            applyLiveCommentUserType(user);
            Map<String,Object> map=new HashMap<>();
            map.put("user",user);
            map.put("needFillFirstLoginRewardAddress", needFillFirstLoginRewardAddress(user));
            return R.ok(map);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }
    @Login
    @ApiOperation("获取用户信息ByUserId")
    @GetMapping("/getUserInfoByUserId")
    public R getUserInfoByUserId(
            @ApiParam(required = true, name = "userId", value = "用户ID") @RequestParam(value = "userId", required = false) Long userId,
            HttpServletRequest request){
        try {
            FsUser user=userService.selectFsUserByUserId(userId);
            if (user.getPhone()!=null&&user.getPhone().length()>11&&!user.getPhone().matches("\\d+")){
                user.setPhone(decryptPhoneMk(user.getPhone()));
            }
            applyLiveCommentUserType(user);
            Map<String,Object> map=new HashMap<>();
            map.put("user",user);
            map.put("needFillFirstLoginRewardAddress", needFillFirstLoginRewardAddress(user));
            return R.ok(map);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }
    @Login
    @ApiOperation("判断用户是否存在头像昵称")
    @GetMapping("/checkUserInfo")
    public R checkUserInfo(){
        log.info("【判断判断用户是否存在头像昵称】：{}",getUserId());
        return courseVideoService.checkUserInfo(Long.parseLong(getUserId()));
    }

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

    @ApiOperation("获取首次登录App奖励返回")
    @GetMapping("/getIntegralFirstLoginApp")
    public R getIntegralFirstLoginApp() {
        String json = configService.selectConfigByKey("his.integral");
        if (StringUtils.isBlank(json)) {
            return R.ok()
                    .put("integralFirstLoginApp", 0)
                    .put("giftName", "")
                    .put("giftPrice", "")
                    .put("giftImage", "");
        }
        JSONObject cfgObj = JSONUtil.parseObj(json);
        IntegralConfig config = JSONUtil.toBean(cfgObj, IntegralConfig.class);
        Integer integralFirstLoginApp = config.getIntegralFirstLoginApp();
        return R.ok()
                .put("integralFirstLoginApp", integralFirstLoginApp == null ? 0 : integralFirstLoginApp)
                .put("giftName", pickFirstNonBlank(cfgObj,
                        "firstLoginGiftName", "integralFirstLoginGiftName", "newcomerGiftName", "giftName"))
                .put("giftPrice", pickFirstNonBlank(cfgObj,
                        "firstLoginGiftPrice", "integralFirstLoginGiftPrice", "newcomerGiftPrice", "giftPrice"))
                .put("giftImage", pickFirstNonBlank(cfgObj,
                        "firstLoginGiftImage", "integralFirstLoginGiftImage", "newcomerGiftImage", "giftImage"));
    }

    @Login
    @ApiOperation("修改用户信息")
    @PostMapping("/editUser")
    public R editUser(@RequestBody @Valid FsUserEditParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        log.info("【修改用户头像昵称】：{}",param);
        if (param.getNickname() != null && param.getNickname().length()>50){
            return R.error("请授权正确的昵称！");
        }
        if (StringUtils.isEmpty(param.getAvatar())){
            param.setAvatar("https://zkzh-2025.oss-cn-beijing.aliyuncs.com/fs/20250715/533c6f87cc2e4ba4a9504374bb58416d.png");
        }
        FsUser user=new FsUser();
        user.setUserId(Long.parseLong(getUserId()));
        user.setAvatar(param.getAvatar());
        // 前端传了nickname 和 nickName 但是只有nickName是正确的
        user.setNickName(StringUtils.isNotEmpty(param.getNickName())?param.getNickName():param.getNickname());
        if (ObjectUtils.isNotEmpty(param.getIsWeixinAuth())){
            user.setIsWeixinAuth(param.getIsWeixinAuth());
        }
        if(userService.updateFsUser(user)>0){
            return R.ok("修改成功");
        }
        else{
            return R.error("修改失败");
        }
    }

    @Login
    @ApiOperation("填写首次登录奖励地址")
    @PostMapping("/setFirstLoginRewardAddress")
    public R setFirstLoginRewardAddress(@RequestBody Map<String, String> body, HttpServletRequest request) {
        String address = body.get("address");
        if (StringUtils.isBlank(address)) {
            return R.error("地址不能为空");
        }
        FsUser user = new FsUser();
        user.setUserId(Long.parseLong(getUserId()));
        user.setFirstLoginRewardAddress(address.trim());
        if (userService.updateFsUser(user) > 0) {
            return R.ok("操作成功");
        }
        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(String.format("您已提交申请: %s,等待审核...",doctor.getDoctorName()));
            }
            else if(doctor.getIsAudit().equals(1)){
                return R.error(String.format("您已提交过申请 提交信息: %s",doctor.getDoctorName()));
            }
        }
        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);
    }

    @Login
    @ApiOperation("删除用户（逻辑删除）")
    @PostMapping("/deleteUser/{id}")
    public R deleteUser(@PathVariable("id") Long id ){
        // 仅允许删除当前登录用户自身，防止越权删除他人账号
        Long currentUserId = Long.parseLong(getUserId());
        if (id == null || !id.equals(currentUserId)) {
            return R.error("无权删除该用户");
        }
        return userService.updateStatus(id);
    }

    /**
     * 查询用户
     */
    @GetMapping("/user/list/{name}")
    public TableDataInfo userlist(@PathVariable("name")String name)
    {
        List<UserVo> list = userService.selectUserVOList(name);
        if (list==null|| list.isEmpty()){
            String s = encryptPhone(name);
            list = userService.selectUserVOList(s);
        }
        return getDataTable(list);
    }

    /**
     * 更新historyApp
     */
    @Login
    @GetMapping("/updateHistoryApp")
    public R updateHistoryApp(@Param("historyApp") String historyApp) {
        String userId = getUserId();
        FsUser fsUser = new FsUser();
        fsUser.setUserId(Long.parseLong(userId));
//        fsUser.setHistoryApp(historyApp);
        if (userService.updateFsUser(fsUser)>0) {
            return R.ok();
        } else {
            return R.error("用户不存在！");
        }
    }

    @Login
    @ApiOperation("注销用户")
    @PostMapping("/removeUser")
    public R removeUser(){
        return userService.removeUser(Long.parseLong(getUserId()));
    }

    /** 与登录接口一致：已记首次登录 app 时间且奖励地址为空时需弹窗填写 */
    private boolean needFillFirstLoginRewardAddress(FsUser user) {
        return user != null
                && user.getFirstLoginAppTime() != null
                && StringUtils.isBlank(user.getFirstLoginRewardAddress());
    }

    /** 直播评论飘屏/置顶：与 WS userType 对齐 */
    private void applyLiveCommentUserType(FsUser user) {
        if (user == null) {
            return;
        }
        Long companyUserId = user.getBindCompanyUserId();
        int liveUt = liveCommentWsUserTypeService.resolveLiveCommentUserType(
                companyUserId != null && companyUserId > 0 ? companyUserId : null);
        user.setLiveUserType(liveUt);
        user.setUserType(Integer.toString(liveUt));
    }

    private String pickFirstNonBlank(JSONObject jsonObject, String... keys) {
        if (jsonObject == null || keys == null) {
            return "";
        }
        for (String key : keys) {
            String value = jsonObject.getStr(key);
            if (StringUtils.isNotBlank(value)) {
                return value;
            }
        }
        return "";
    }
}
