package com.yihu.wlyy.web.patient.device;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.device.PatientHealthTime;
import com.yihu.wlyy.repository.deviece.PatientHealthTimeDao;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者端：设备管理控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "patient/device")
@Api(value = "患者设备管理", description = "患者设备管理")
public class PatientDeviceController extends BaseController {

    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;

    private String url = SystemConf.getInstance().getYihuOpenPlatformUrl();
    private String appid = SystemConf.getInstance().getYihuOpenPlatformAppId();
    private String secret = SystemConf.getInstance().getYihuOpenPlatformSecret();
    private String registerDevice = "DeviceGateway/DeviceApi/registerDevice";//注册设备

    private ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 设置及修改血糖仪时间段
     * 默认时间段如下
     * fasting: 00:00-07:59
     * afterBreakfast: 08:00-09:59
     * beforeLunch: 10:00-11:59
     * afterLunch: 12:00-13:59
     * beforeDinner: 14:00-17:59
     * afterDinner: 18:00-19:59
     * beforeSleep: 20:00-23:59
     */
    @ApiOperation("设置修改血糖仪时间段")
    @RequestMapping(value = "/setBloodTime", method = RequestMethod.GET)
    @ResponseBody
    public String setBloodTime(@RequestParam(required = false) String fastingStart,
                               @RequestParam(required = false) String fastingEnd,
                               @RequestParam(required = false) String afterBreakfastStart,
                               @RequestParam(required = false) String afterBreakfastEnd,
                               @RequestParam(required = false) String beforeLunchStart,
                               @RequestParam(required = false) String beforeLunchEnd,
                               @RequestParam(required = false) String afterLunchStart,
                               @RequestParam(required = false) String afterLunchEnd,
                               @RequestParam(required = false) String beforeDinnerStart,
                               @RequestParam(required = false) String beforeDinnerEnd,
                               @RequestParam(required = false) String afterDinnerStart,
                               @RequestParam(required = false) String afterDinnerEnd,
                               @RequestParam(required = false) String beforeSleepStart,
                               @RequestParam(required = false) String beforeSleepEnd,
                               @RequestParam String deviceSN,
                               @RequestParam String categoryCode,
                               @RequestParam String userType,
                               @RequestParam(required = false) String newDeviceSN) {

        try {
//            String user = getUID();
            String user = getRepUID();

            if (StringUtils.isNotEmpty(newDeviceSN)) {
//                校验新的sn码 1.是否被占用 2.是否是真的设备码
                PatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(newDeviceSN, userType);
                if (device != null) {
                    throw new Exception("sn码" + newDeviceSN + "已被使用！");
                }

                //注册设备
                Map<String, String> params = new HashMap<>();
                params.put("deviceSn", newDeviceSN);

                //调用服务
                String response = HttpClientUtil.httpPost(url + registerDevice, HttpClientUtil.getSecretParams(params, appid, secret));
                System.out.println("注册设备=" + response);
                JSONObject json = new JSONObject(response);
                String code = json.get("Code").toString();
                //10000注册成功 10001已注册 -10000参数不通过(没传参数) -10001设备不存在 -10002设备未出库
                if ("10000".equals(code) || "10001".equals(code)) {
                    if ("1".equals(categoryCode)) {
//                        先修改患者设备绑定表
                        int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType);
                        if (rows != 0) {
                            //                只更换设备编码，不更改时间值
//                1.先查询是否自定义时间段，没有则新增，有则修改
                            PatientHealthTime healthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
                            if (healthTime == null) {
                                patientDeviceService.setBloodTime(user, newDeviceSN, "null", "null", "null", "null", "null", "null",
                                        "null", "null", "null", "null", "null", "null", "null", "null");
                            } else {
                                patientDeviceService.updateDeviceSN(user, deviceSN, newDeviceSN);
                            }
                        }
                    }else {
                        int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType);
                    }
                } else {
                    String message = json.get("Message").toString();
                    throw new Exception(message);
                }
                return write(200, "更改sv码成功！");
            }
            patientDeviceService.setBloodTime(user, deviceSN, fastingStart, fastingEnd, afterBreakfastStart, afterBreakfastEnd, beforeLunchStart, beforeLunchEnd,
                    afterLunchStart, afterLunchEnd, beforeDinnerStart, beforeDinnerEnd, afterDinnerStart, afterDinnerEnd, beforeSleepStart, beforeSleepEnd);
            return write(200, "设置成功！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, e.getMessage());
        }
    }

    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    @ResponseBody
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            PatientDevice device = objectMapper.readValue(json, PatientDevice.class);
            // 设置患者标识
            device.setUser(getRepUID());
//            device.setUser(getUID());
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
            }

            patientDeviceService.saveDevice(device);

            return success("设备保存成功！");
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceByPatient(@ApiParam(name = "id", value = "分页起始id", defaultValue = "0")
                                     @RequestParam(value = "id", required = true) long id,
                                     @ApiParam(name = "pagesize", value = "每页条数", defaultValue = "10")
                                     @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
//            Page<PatientDevice> list = patientDeviceService.findByPatient(getUID(), id, pagesize);
            Page<PatientDevice> list = patientDeviceService.findByPatient(getRepUID(), id, pagesize);

            return write(200, "查询成功", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

    //要增加时间段信息展示
    @ApiOperation("获取患者设备信息")
    @RequestMapping(value = "PatientDeviceInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getPatientDeviceInfo(@ApiParam(name = "id", value = "患者设备ID", defaultValue = "146")
                                       @RequestParam(value = "id", required = true) String id) {
        try {
            Map mapList = new HashMap();
            PatientDevice device = patientDeviceService.findById(id);
            String deviceSN = device.getDeviceSn();
            String user = device.getUser();
            Map map = patientDeviceService.getBloodSuggerTime(user, deviceSN);
            mapList.put("time", map);
            mapList.put("device", device);
            return write(200, "查询成功", "data", mapList);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

    /**
     * 通过sn码获取设备绑定情况
     */
    @ApiOperation("通过sn码获取设备绑定情况")
    @RequestMapping(value = "PatientDeviceIdcard", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceUser(@ApiParam(name = "type", value = "设备类型", defaultValue = "1")
                                @RequestParam(value = "type", required = true) String type,
                                @ApiParam(name = "device_sn", value = "设备SN码", defaultValue = "15L000002")
                                @RequestParam(value = "device_sn", required = true) String deviceSn) {
        try {
//            List<Map<String, String>> list = patientDeviceService.getDeviceUser(getUID(), deviceSn, type);
            List<Map<String, String>> list = patientDeviceService.getDeviceUser(getRepUID(), deviceSn, type);
            return write(200, "获取设备绑定信息成功！", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

    /**
     * 设备删除
     */
    @ApiOperation("设备删除")
    @RequestMapping(value = "DeletePatientDevice")
    @ResponseBody
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            PatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
//                if (!StringUtils.equals(pd.getUser(), getUID())) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备！");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getRepUID());
//                patientDeviceService.deleteDevice(id, getUID());
                return success("设备已删除！");
            } else {
                return error(-1, "不存在该设备！");
            }
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}
