package com.fs.watch.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.utils.DateUtils;
import com.fs.his.domain.FsHealthTongue;
import com.fs.his.domain.FsUser;
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.watch.domain.*;
import com.fs.watch.domain.vo.*;
import com.fs.watch.mapper.WatchUserMapper;
import com.fs.watch.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户腕表配置表(WatchUser)表服务实现类
 *
 * @author makejava
 * @since 2024-10-17 17:11:12
 */
@Service("watchUserService")
public class WatchUserServiceImpl implements WatchUserService {
    @Resource
    private WatchUserMapper watchUserMapper;

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private WatchDeviceInfoService deviceInfoService;

    @Autowired
    private WatchDeviceDataService watchDeviceDataService;

    @Autowired
    private WatchDeviceSetupService deviceSetupService;

    @Autowired
    private IFsUserWatchService fsUserWatchService;
    @Autowired
    private WatchDeviceInfoService watchDeviceInfoService;
    @Autowired
    private WatchFamilyUserService watchFamilyUserService;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public WatchFsUser selectWatchFsUserById(Long userId) {
        return this.watchUserMapper.selectWatchFsUserById(userId);
    }

    /**
     * 分页查询
     *
     * @param watchUser   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<WatchUser> queryByPage(WatchUser watchUser, PageRequest pageRequest) {
        long total = this.watchUserMapper.count(watchUser);
        return new PageImpl<>(this.watchUserMapper.queryAllByLimit(watchUser, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param watchUser 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(WatchUser watchUser) {
        watchUser.setCreateTime(new Date());
        return this.watchUserMapper.insert(watchUser);
    }

    /**
     * 修改用户
     *
     * @param watchUser 用户
     * @return 结果
     */
    @Override
    public int updateWatchUser(WatchUser watchUser) {
        watchUser.setUpdateTime(DateUtils.getNowDate());
        return watchUserMapper.updateWatchUser(watchUser);
    }

    @Override
    public Boolean editDevice(String userId, String imei, String model, String ble, String version,Long userWatchId) {
        //1.编辑绑定设备 ,更新用户表
        if (StringUtils.isNotBlank(imei)) {
            //1.1判断该设备是否已经绑定
            WatchFsUser user = selectWatchFsUserByDeviceId(imei);
            if (user != null) {
                return false;
            }
            //1.2 判断设备状态是否正常

            //1.3 绑定设备
            long userIdL = Long.parseLong(userId);
            WatchFsUser watchFsUser = selectWatchFsUserById(userIdL);
            //查询公司id
//            WatchDeviceInfoVo vo = deviceInfoService.getByNumber(imei);
//            if (vo != null && vo.getCompanyId() != null) {
//                watchFsUser.setCompanyId(vo.getCompanyId());
//            }
            if (watchFsUser == null) {
                WatchUser watchUser = new WatchUser();
                watchUser.setUserId(userIdL);
                watchUser.setDeviceId(imei);
                insert(watchUser);
            } else {
                String deviceId = watchFsUser.getDeviceId();
                if (deviceId == null || "".equals(deviceId)) {
                    watchFsUser.setDeviceId(imei);
                } else {
                    watchFsUser.setDeviceId(deviceId + "," + imei);
                }
                WatchUser watchUser = setWatchUser(watchFsUser);
                //查询是否含有腕表用户信息
                updateWatchUser(watchUser);
            }

            //2.编辑设备信息 , 更新设备信息表
            WatchDeviceData watchDeviceData = new WatchDeviceData();
            watchDeviceData.setDeviceId(imei);
            watchDeviceData.setModel(model);
            watchDeviceData.setVersion(version);
            watchDeviceData.setBle(ble);
//            watchDeviceData.setIsBind(1);
            watchDeviceData.setIsBind(true);
            if (watchDeviceDataService.existsByDeviceId(imei)) {
                //存在即更新
                watchDeviceDataService.updateByDeviceId(watchDeviceData);
            } else {
                //不存在则新增
                watchDeviceData.setCreateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getNowDate()));
//                watchDeviceData.setCreateTime(DateUtils.getNowDate());
//                watchDeviceData.setId(UUID.randomUUID().toString());
                watchDeviceDataService.insert(watchDeviceData);
            }
            //3.添加设备设置信息
            WatchDeviceSetup temp = deviceSetupService.selectDeviceSetupByDeviceId(imei);
            if (temp == null) {
                WatchDeviceSetup deviceSetup = new WatchDeviceSetup();
                deviceSetup.setDeviceId(imei);
                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");
                deviceSetupService.insertDeviceSetup(deviceSetup);
            }
            //4.更新用户腕表
            FsUserWatch fsUserWatch = fsUserWatchService.getLastByUserId(Long.valueOf(userId));
            fsUserWatch.setStatus(3);
            fsUserWatchService.updateFsUserWatch(fsUserWatch);
            //5.更新设备硬件信息表
            WatchDeviceInfo watchDeviceInfo = new WatchDeviceInfo();
            watchDeviceInfo.setDeviceNumber(imei);
            watchDeviceInfo.setCompanyId(fsUserWatch.getCompanyId());
            watchDeviceInfo.setCompanyUserId(fsUserWatch.getCompanyUserId());
            watchDeviceInfo.setDoctorId(fsUserWatch.getDoctorId());
            watchDeviceInfo.setLifeStatus(2);
            watchDeviceInfoService.updateByDeviceNumber(watchDeviceInfo);
            return true;
        }
        return false;
    }

    private WatchUser setWatchUser(WatchFsUser watchFsUser) {
        WatchUser watchUser = new WatchUser();
        watchUser.setUserId(watchFsUser.getUserId());
        watchUser.setDeviceId(watchFsUser.getDeviceId());
        watchUser.setSex(watchFsUser.getSex());
        watchUser.setBirthday(watchFsUser.getBirthday());
        watchUser.setWCompanyId(watchFsUser.getWCompanyId());
        watchUser.setHeight(watchFsUser.getHeight());
        watchUser.setWeight(watchFsUser.getWeight());
        watchUser.setTargetStep(watchFsUser.getTargetStep());
        watchUser.setTargetCalorie(watchFsUser.getTargetCalorie());
        watchUser.setDeviceId(watchFsUser.getDeviceId());
        watchUser.setOtherDevice(watchFsUser.getOtherDevice());
        watchUser.setMonitorDataTypeOrder(watchFsUser.getMonitorDataTypeOrder());
        watchUser.setCreateTime(watchFsUser.getCreateTime());
        watchUser.setUpdateTime(watchFsUser.getUpdateTime());
        watchUser.setIsDel(watchFsUser.getIsDel());
        return watchUser;

    }

    @Override
    public Boolean removeDevice(String userId, String deviceId) {
        //1.编辑绑定设备 ,更新用户表
        if (StringUtils.isNotBlank(deviceId)) {

            //1.1判断该设备是否已经绑定
            WatchFsUser user = selectWatchFsUserByDeviceId(deviceId);
            if (user == null) {
                return false;
            }
            if (!Objects.equals(user.getUserId(), Long.valueOf(userId))) {
                return false;
            }

            //1.2 解除绑定设备
            //查询是否有该设备
//            WatchDeviceInfoVo vo = deviceInfoService.getByNumber(deviceId);
//            if (vo != null) {
            String deviceIds = user.getDeviceId();

            List<String> list = Arrays.asList(deviceIds.split(","));
            if (!list.isEmpty()) {
                if (list.contains(deviceId)) {
                    list = list.stream().filter(s -> !(deviceId.equals(s))).collect(Collectors.toList());
                    String newDeviceIds = "";
                    for (int i = 0; i < list.size(); i++) {
                        if (i == 0) {
                            newDeviceIds = newDeviceIds + list.get(i);
                        } else {
                            newDeviceIds = newDeviceIds + "," + list.get(i);
                        }
                    }
                    user.setDeviceId(newDeviceIds);
                }
//                }
            }
            WatchUser watchUser = new WatchUser();
            BeanUtils.copyProperties(user, watchUser);
            updateWatchUser(watchUser);

            //2.编辑设备信息 , 更新设备信息表
            WatchDeviceData watchDeviceData = new WatchDeviceData();
            watchDeviceData.setDeviceId(deviceId);
//            watchDeviceData.setIsBind(0);
            watchDeviceData.setIsBind(false);
            if (watchDeviceDataService.existsByDeviceId(deviceId)) {
                //存在即更新
                watchDeviceDataService.updateByDeviceId(watchDeviceData);
            }
            //3.更新腕表用户日志表
            FsUserWatch fsUserWatch = fsUserWatchService.getLastByUserId(Long.valueOf(userId));
            fsUserWatch.setStatus(1);
            fsUserWatchService.updateFsUserWatch(fsUserWatch);
            //4.更新设备表绑定状态
            WatchDeviceInfo watchDeviceInfo = new WatchDeviceInfo();
            watchDeviceInfo.setDeviceNumber(deviceId);
            watchDeviceInfo.setLifeStatus(0);//空置
            watchDeviceInfoService.updateByDeviceNumber(watchDeviceInfo);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long userId) {
        return this.watchUserMapper.deleteById(userId) > 0;
    }

    @Override
    @Transactional
    public int updateFsUserByDeviceId(WatchFsUser user) {
        user.setUpdateTime(DateUtils.getNowDate());
        int flag = watchUserMapper.updateFsUserByDeviceId(user);
        if (flag > 0) {
            WatchFsUser temp = watchUserMapper.selectWatchFsUserByDeviceId(user.getDeviceId());
            FsUser fsUser = new FsUser();
            BeanUtils.copyProperties(user, fsUser);
            fsUser.setCreateTime(null);
            fsUser.setUserId(temp.getUserId());
            fsUserService.updateFsUser(fsUser);
        }
        return flag;
    }

    @Override
    public List<WatchInfoVo> getWatchInfo(long userId) {
        List<WatchInfoVo> res = new ArrayList<>();
        WatchFsUser user = selectWatchFsUserById(userId);
        if (user != null) {
            String otherDevice = user.getOtherDevice();
            List<DeviceFamily> deviceFamilies = JSON.parseArray(otherDevice, DeviceFamily.class);
            if (deviceFamilies != null && !deviceFamilies.isEmpty()) {
                for (DeviceFamily deviceFamily : deviceFamilies) {
                    WatchInfoVo vo = new WatchInfoVo();
                    BeanUtils.copyProperties(deviceFamily, vo);
                    //查询设备名字
                    WatchDeviceData deviceData = watchDeviceDataService.getByDeviceId(deviceFamily.getDeviceId());
                    if (deviceData != null) {
                        vo.setBle(deviceData.getBle());
                    }
                    //设备状态
                    Integer status = deviceInfoService.getStatus(deviceFamily.getDeviceId());
                    vo.setStatus(status!=null?status:-1);
                    res.add(vo);
                }
            }
            //自己
            String deviceId = user.getDeviceId();
            if (StringUtils.isNotBlank(deviceId)) {
                List<String> list = Arrays.asList(deviceId.split(","));
                if (!list.isEmpty()) {
                    for (String deId : list) {
                        WatchInfoVo vo = new WatchInfoVo();
                        vo.setName("自己");
                        vo.setRelationship("自己");

                        vo.setDeviceId(deviceId);
                        WatchDeviceData deviceData = watchDeviceDataService.getByDeviceId(deId);
                        if (deviceData != null) {
                            vo.setBle(deviceData.getBle());
                        }
                        //设备状态
                        Integer status = deviceInfoService.getStatus(deId);
                        vo.setStatus(status!=null?status:-1);
                        res.add(vo);
                    }
                }
            } else {
                WatchInfoVo vo = new WatchInfoVo();
                vo.setName("自己");
                vo.setRelationship("自己");
                //设备状态
                res.add(vo);
            }

        }
        return res;
    }

    @Override
    public List<WatchUserAndHealthVo> listByDeviceIdNotNull() {
        return watchUserMapper.listByDeviceIdNotNull();
    }

    @Override
    public FsHealthTongue getLastTongueByDeviceId(String deviceId) {
        return watchUserMapper.getLastTongueByDeviceId(deviceId);
    }

    @Override
    public WatchFsUser selectWatchFsUserByDeviceId(String deviceId) {
        return watchUserMapper.selectWatchFsUserByDeviceId(deviceId);
    }

    @Override
    public AppFsUserVo getUserInfoByDeviceId(String deviceId,Boolean isFamily,Long watchUserId) {
        AppFsUserVo appFsUserVo = new AppFsUserVo();
        if (isFamily){
            WatchFamilyUserVo familyUser = watchFamilyUserService.selectWatchFamilyUserByDeviceId(deviceId,watchUserId);
            if (familyUser != null) {
                BeanUtils.copyProperties(familyUser, appFsUserVo);
                if (familyUser.getBirthday() !=null){
                    appFsUserVo.setAge(getAge(familyUser.getBirthday()));
                }
            }
        } else {
            //根据设备id获取用户信息
            WatchFsUser user = selectWatchFsUserByDeviceId(deviceId);
            if (user != null ) {
                BeanUtils.copyProperties(user, appFsUserVo);
                if (user.getBirthday() !=null){
                    //计算年龄
                    appFsUserVo.setAge(getAge(user.getBirthday()));
                }
            }
        }

        return appFsUserVo;
    }

    private static int getAge(Date birthDate) {
        //计算年龄
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate birthday = LocalDate.parse(sdf.format(birthDate), formatter);
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(birthday, currentDate).getYears();
        return age;
    }
}
