package com.fs.app.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.app.param.DeviceEditParam;
import com.fs.app.param.WatchUserEditParam;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.his.domain.FsUserWatch;
import com.fs.his.dto.FsStoreCartDTO;
import com.fs.his.service.IFsUserService;
import com.fs.his.service.IFsUserWatchService;
import com.fs.his.utils.PhoneUtil;
import com.fs.watch.domain.*;
import com.fs.watch.domain.vo.AppFsUserVo;
import com.fs.watch.domain.vo.WatchFamilyUserVo;
import com.fs.watch.param.WatchFamilyUserEditParam;
import com.fs.watch.service.*;
import com.fs.watch.service.impl.WatchDeviceDataServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 用户腕表配置表(WatchUser)表控制层
 *
 * @author makejava
 * @since 2024-10-17 17:11:06
 */
@RestController
@RequestMapping("/app/watchUser")
public class WatchUserController extends AppBaseController {
    @Autowired
    private WatchUserService userService;

    @Autowired
    private DeviceSetUpService deviceSetUpService;


    @Autowired
    private WatchDeviceSetupService IDeviceSetupService;

    @Autowired
    private IFsUserWatchService fsUserWatchService;

    @Autowired
    private WatchFamilyUserService watchFamilyUserService;
    @Autowired
    private WatchDeviceDataServiceImpl watchDeviceDataServiceImpl;
    @Autowired
    private WatchDeviceDataService watchDeviceDataService;

    /**
     * 获取用户信息
     *
     * @param isFamily 是否是家人
     * @return
     */
    @Login
    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    public R getUserInfo(@RequestParam("isFamily") Boolean isFamily,
                         @RequestParam(value = "deviceId", required = false) String deviceId) {
        try {
            if (isFamily) {
                WatchFamilyUser familyUser = watchFamilyUserService.selectWatchFamilyUserByDeviceId(deviceId,Long.valueOf(getUserId()));
                return R.ok().put("user", familyUser);
            } else {
                WatchFsUser user = userService.selectWatchFsUserById(Long.parseLong(getUserId()));
                if (user == null) {
                    WatchUser watchUser = new WatchUser();
                    watchUser.setUserId(Long.parseLong(getUserId()));
                    userService.insert(watchUser);
                    user = userService.selectWatchFsUserById(Long.parseLong(getUserId()));
                }
                user.setPassword("***********");//隐藏密码
                //处理电话
                String phone = user.getPhone();
                if (StringUtils.isNotBlank(phone)) {
                    if (phone.length() != 11 && !phone.startsWith("1")) {
                        user.setPhone(PhoneUtil.decryptPhone(phone));
                    }
                }
                //处理deviceId
                String userDeviceId = user.getDeviceId();
                if (userDeviceId != null && !userDeviceId.isEmpty()) {
                    List<String> deviceIds = Arrays.asList(userDeviceId.split(","));
                    AppFsUserVo appFsUserVo = new AppFsUserVo();
                    BeanUtils.copyProperties(user, appFsUserVo);
                    appFsUserVo.setDeviceId(deviceIds);
                    return R.ok().put("user", appFsUserVo);
                } else {
                    return R.ok().put("user", user);

                }
            }
        } catch (Exception e) {

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


    /**
     * 获取腕表信息
     *
     * @param request
     * @return
     */
    @Login
    @ApiOperation("获取腕表信息")
    @GetMapping("/getWatchInfo")
    public R getWatchInfo(HttpServletRequest request) {
        return R.ok().put("data", userService.getWatchInfo(Long.parseLong(getUserId())));
    }

    /**
     * 修改用户腕表信息 (只能修改身高,体重,生日,目标,家人,编辑卡片,其余用户信息在个人中心修改)
     *
     * @param param
     * @param request
     * @return
     */
    @Login
    @ApiOperation("修改用户腕表信息")
    @PostMapping("/editUser")
    @Transactional
    public R editUser(@RequestBody WatchUserEditParam param, HttpServletRequest request) {
        WatchUser user = new WatchUser();
        UserInfo userInfo = new UserInfo();
        //昵称
        if (StringUtils.isNotBlank(param.getNickName())){
            user.setNickName(param.getNickName());
        }
        //身高
        if (param.getHeight() != null) {
            user.setHeight(param.getHeight());
            userInfo.setHeight(param.getHeight());
        }
        //体重
        if (param.getWeight() != null) {
            user.setWeight(param.getWeight());
            userInfo.setWeight(param.getWeight());
        }
        //生日
        if (param.getBirthday() != null) {
            user.setBirthday(param.getBirthday());
            userInfo.setBirthday(param.getBirthday());
        }
        //目标步数
        if (StringUtils.isNoneBlank(param.getTargetStep())) {
            user.setTargetStep(param.getTargetStep());
        }
        //目标卡路里
        if (StringUtils.isNoneBlank(param.getTargetCalorie())) {
            user.setTargetCalorie(param.getTargetCalorie());
        }

        //目标运动
        if (StringUtils.isNoneBlank(param.getTargetSport())) {
            user.setTargetSport(param.getTargetSport());
        }
        //目标活动
        if (StringUtils.isNoneBlank(param.getTargetActivity())) {
            user.setTargetActivity(param.getTargetActivity());
        }
        //家人
        String otherDevice = param.getOtherDevice();
        if (StringUtils.isNoneBlank(otherDevice)) {
            user.setOtherDevice(otherDevice);
            JSONArray jsonArray = JSONUtil.parseArray(otherDevice);

            // 将 JSONArray 转换为 List<Person>
            List<DeviceFamily> list = jsonArray.toList(DeviceFamily.class);
            if (list != null && !list.isEmpty()) {
                for (DeviceFamily deviceFamily : list) {
                    String deviceId = deviceFamily.getDeviceId();
                    if (StringUtils.isNotBlank(deviceId)) {
                        //添加设备设置信息
                        if (IDeviceSetupService.selectDeviceSetupByDeviceId(deviceId) == null) {
                            WatchDeviceSetup deviceSetup = new WatchDeviceSetup();
                            deviceSetup.setDeviceId(deviceId);
                            deviceSetup.setSmartDoctor(0);
                            deviceSetup.setSedentary(JSONUtil.toJsonStr(new DeviceSedentary()));
                            deviceSetup.setFallcheck(0);
                            deviceSetup.setHeartHealth(0);
                            deviceSetup.setHralarm(JSONUtil.toJsonStr(new DeviceHralarm()));
                            deviceSetup.setSpo2alarm(JSONUtil.toJsonStr(new DeviceSpo2alarm()));
                            deviceSetup.setAlarmClock(JSONUtil.toJsonStr(new DeviceAlarmClock()));
                            deviceSetup.setPower(JSONUtil.toJsonStr(new DevicePower()));
                            deviceSetup.setPhonebook(JSONUtil.toJsonStr(new DevicePhonebooks()));
                            deviceSetup.setTime(JSONUtil.toJsonStr(new DeviceTime()));
                            deviceSetup.setLcdgesture(JSONUtil.toJsonStr(new DeviceLcdgesture()));
                            deviceSetup.setUnit(JSONUtil.toJsonStr(new DeviceUnit()));
                            deviceSetup.setMode(JSONUtil.toJsonStr(new DeviceMode()));
                            deviceSetup.setVersion("1.0.0");
                            IDeviceSetupService.insertDeviceSetup(deviceSetup);
                        }
                        //添加家人信息
                        //查询该设备是否已存在家人信息
                        WatchFamilyUser familyUser = watchFamilyUserService.selectWatchFamilyUserByDeviceId(deviceId,null);
                        if (familyUser == null) {
                            WatchFamilyUser watchFamilyUser = new WatchFamilyUser();
                            watchFamilyUser.setDeviceId(deviceId);
                            watchFamilyUserService.insertWatchFamilyUser(watchFamilyUser);
                        }
                    }
                }
            }

        }
        //编辑卡片
        if (StringUtils.isNoneBlank(param.getMonitorDataTypeOrder())) {
            user.setMonitorDataTypeOrder(param.getMonitorDataTypeOrder());
        }

        long userId = Long.parseLong(getUserId());
        WatchFsUser userById = userService.selectWatchFsUserById(userId);
        String deviceIdsStr = userById.getDeviceId();
        if (StringUtils.isNoneBlank(deviceIdsStr)) {
            List<String> deviceIds = Arrays.asList(deviceIdsStr.split(","));
            for (String deviceId : deviceIds) {
                //补全用户信息
                userInfo.setDeviceid(deviceId);
                Integer sex = userById.getSex();
                if (sex != null) {
                    userInfo.setgender(sex);
                }
                //下发设置到设备
                deviceSetUpService.setDeviceUserInfo(userInfo);
            }
        }

        //更新腕表用户表
        user.setUserId(userId);
        int i = userService.updateWatchUser(user);
        if (i > 0) {
            return R.ok("修改成功");
        } else {
            user.setCreateTime(DateUtils.getNowDate());
            if (userService.insert(user) > 0) {
                return R.ok("修改成功");
            }
            return R.error("修改失败");
        }
    }

    /**
     * 修改家人腕表信息
     *
     * @param param
     * @return
     */
    @Login
    @ApiOperation("修改家人腕表信息")
    @PostMapping("/editFamilyUser")
    public R editFamilyUser(@RequestBody WatchFamilyUserEditParam param) {
        String deviceIdStr = param.getDeviceId();
        if (StringUtils.isNotBlank(deviceIdStr)) {
            List<String> ids = Arrays.asList(deviceIdStr.split(","));
            if (!ids.isEmpty()) {
                for (String deviceId : ids) {
                    //1.基本信息
                    WatchFamilyUserVo familyUser = new WatchFamilyUserVo();
                    BeanUtils.copyProperties(param, familyUser);
                    int flag = watchFamilyUserService.updateWatchFamilyUserByDeviceId(familyUser,Long.valueOf(getUserId()));
                    //昵称
                    //2.更新腕表sim
                    if (StringUtils.isNotBlank(param.getPhone())) {
                        WatchDeviceData deviceData = new WatchDeviceData();
                        deviceData.setDeviceId(deviceId);
                        deviceData.setSIM(param.getPhone());
                        watchDeviceDataService.updateByDeviceId(deviceData);
                    }
                    //3.下发设置到设备
                    UserInfo userInfo = new UserInfo();
                    if (param.getHeight() != null) {
                        userInfo.setHeight(param.getHeight());
                    }
                    if (param.getWeight() != null) {
                        userInfo.setWeight(param.getWeight());
                    }
                    if (param.getSex() != null) {
                        userInfo.setgender(param.getSex());
                    }
                    if (param.getBirthday() != null) {
                        userInfo.setBirthday(param.getBirthday());
                    }
                    if (param.getTargetStep() != null) {
                        userInfo.setTargetStep(param.getTargetStep());
                    }
                    if (param.getTargetCalorie() != null) {
                        userInfo.setTargetCalorie(param.getTargetCalorie());
                    }
                    userInfo.setDeviceid(deviceId);
                    deviceSetUpService.setDeviceUserInfo(userInfo);
                    return flag > 0 ? R.ok("修改成功") : R.error("修改失败");
                }
            }

        }
        return R.error("未绑定设备!");
    }

    @Login
    @ApiOperation("绑定设备")
    @PostMapping("/editDevice")
    public R editDevice(@RequestBody DeviceEditParam param, HttpServletRequest request) {
        //1.获取当前登录用户信息
        String userId = getUserId();
        //判断是否是购买者本人绑定
        FsUserWatch fsUserWatch = fsUserWatchService.getLastByUserId(Long.valueOf(userId));
        if (fsUserWatch == null) {
            return R.error("该设备非购买者本人绑定!");
        }
        if (fsUserWatch.getStatus() == 3) {
            return R.error("该设备已绑定!");
        }
        if (fsUserWatch.getStatus() == -1) {
            return R.error("该设备已退货,不可绑定!");
        }
        Boolean flag = userService.editDevice(userId, param.getImei(), param.getModel(), param.getBle(), param.getVersion(), fsUserWatch.getId());
        if (flag) {
            return R.ok("绑定成功");
        } else {
            return R.ok("设备号已绑定或已存在");
        }
    }

    @Login
    @ApiOperation("解除绑定设备")
    @GetMapping("/removeDevice")
    public R removeDevice(@RequestParam("deviceId") String deviceId, HttpServletRequest request) {
        //1.获取当前登录用户信息
        String userId = getUserId();
        Boolean flag = userService.removeDevice(userId, deviceId);
        if (flag) {
            return R.ok("解绑成功");
        } else {
            return R.ok("设备号已绑定或已存在");
        }
    }

    /**
     * 健康报告-个人信息
     */
    @GetMapping("/getUserByDeviceId")
    @Login
    @ApiOperation("健康报告-个人信息")
    public AjaxResult getUserByDeviceId(@RequestParam("deviceId") String deviceId,
                                        @RequestParam("isFamily") Boolean isFamily) {
        if (com.fs.common.utils.StringUtils.isBlank(deviceId)) {
            return null;
        }
        return AjaxResult.success(userService.getUserInfoByDeviceId(deviceId, isFamily,Long.valueOf(getUserId())));
    }

}

