package com.fs.watch.controller;

import com.fs.app.annotation.Login;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyRoleService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.service.ICompanyUserUserService;
import com.fs.system.service.ISysRoleService;
import com.fs.watch.domain.WatchDeviceInfo;
import com.fs.watch.domain.vo.WatchDeviceInfoVo;
import com.fs.watch.param.WatchDeviceInfoQueryParam;
import com.fs.watch.service.WatchDataService;
import com.fs.watch.service.WatchDeviceInfoService;
import com.fs.watch.service.WatchUserService;
import com.fs.watch.service.impl.WatchUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/device")
public class WatchDeviceInfoController extends BaseController {
    @Autowired
    private WatchDeviceInfoService deviceInfoService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ICompanyRoleService companyRoleService;

    @Autowired
    private WatchDataService watchDataService;

    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private WatchUserService watchUserService;


    /**
     * 获取设备信息
     *
     * @param deviceNumber 设备编号
     * @return 结果 添加设备返回null则设备不存在,无法添加
     */
    @GetMapping("/info")
    public AjaxResult getInfo(@RequestParam("deviceNumber") String deviceNumber) {
        return AjaxResult.success(deviceInfoService.getInfo(deviceNumber));
    }

    /**
     * 根据设备编号获取设备信息
     *
     * @param deviceNumber 设备编号
     * @return 结果 添加设备返回null则设备不存在,无法添加
     */
    @GetMapping("/getByNumber")
    public AjaxResult getByNumber(@RequestParam("deviceNumber") String deviceNumber) {
        return AjaxResult.success(deviceInfoService.getByNumber(deviceNumber));
    }


    /**
     * 查询设备信息列表
     */
    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(WatchDeviceInfoQueryParam param, HttpServletRequest request) {
        //判断前端请求
        String type = request.getHeader("x-frontend-type");
        if ("admin".equals(type)) {
            //判断登录用户是角色

            Long userId = getSysUserId();
            if (userId == null) {
                throw new ServiceException("请先登录!");
            }

        } else if ("company".equals(type)) {
            //判断登录用户是角色
            CompanyUser companyUser = getLoginUser().getUser();
            Long userId = companyUser.getUserId();
            if (userId == null) {
                throw new ServiceException("请先登录!");
            }
            //按公司查询
            if (companyUser.getCompanyId() == null){
                throw new ServiceException("没有权限查看");
            } else {
                Long companyId = companyUser.getCompanyId();
                param.setCompanyId(companyId);
            }
        } else if ("doctor".equals(type)) {
            String doctorId = getDoctorId();
            if (doctorId == null) {
                throw new ServiceException("请先登录!");
            }
            param.setDoctorId(Long.valueOf(doctorId));
        }
        startPage();
        List<WatchDeviceInfoVo> list = deviceInfoService.selectDeviceInfoList(param);
        return getDataTable(list);
    }

    /**
     * 导出设备信息列表
     */
    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:export')")
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(WatchDeviceInfoQueryParam param) {
        List<WatchDeviceInfoVo> list = deviceInfoService.selectDeviceInfoList(param);
        ExcelUtil<WatchDeviceInfoVo> util = new ExcelUtil<WatchDeviceInfoVo>(WatchDeviceInfoVo.class);
        return util.exportExcel(list, "设备信息数据");
    }

//    /**
//     * 查询当月新增设备
//     */
//    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:query')")
//    @GetMapping(value = "/getAddCountByMonth")
//    public AjaxResult getAddCountByMonth()
//    {
//        //判断登录用户是角色
//        Long userId = getUserId();
//        if (userId == null){
//            return AjaxResult.error("请先登录!");
//        }
//        List<Integer> roleIds = sysRoleService.selectRoleListByUserId(userId);
//        if (roleIds == null || roleIds.size() == 0){
//            return AjaxResult.error("该用户没有分配角色");
//        }
//        Long companyId = 0L;
////        if (!(roleIds.contains(1) || roleIds.contains(2))) {
////            //按公司查询
////            Company company = companyService.selectCompanyByUserId(userId);
////            if (company == null){
////                return AjaxResult.error("没有权限查看");
////            } else {
////                companyId = company.getCompanyId();
////            }
////        }
//        return AjaxResult.success(deviceInfoService.getAddCountByMonth(companyId));
//    }

    /**
     * 获取设备信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return AjaxResult.success(deviceInfoService.selectDeviceInfoByDeviceId(deviceId));
    }

    /**
     * 新增设备信息
     */
    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:add')")
//    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WatchDeviceInfo deviceInfo) {
        //判断所属员工和所属公司是否对应
        if (deviceInfo.getCompanyUserId() != null) {
            CompanyUser companyUser = companyUserService.selectCompanyUserById(deviceInfo.getCompanyUserId());
            if (deviceInfo.getCompanyId() == null) {
                deviceInfo.setCompanyId(companyUser.getUserId());
            } else {
                if (deviceInfo.getCompanyId() != companyUser.getCompanyId()) {
                    return AjaxResult.error("所属员工不属于该公司!");
                }
            }
        }
        deviceInfo.setCreateBy(getUsername());
        return toAjax(deviceInfoService.insertDeviceInfo(deviceInfo));
    }

    /**
     * 修改设备信息
     */
    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:edit')")
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WatchDeviceInfo deviceInfo, HttpServletRequest request) {

        //判断前端请求
        String type = request.getHeader("x-frontend-type");
        String userName = "";
        if ("admin".equals(type)) {
            //判断登录用户是角色
            userName = getSysLoginUser().getUsername();

        } else if ("company".equals(type)) {
            userName = getUsername();
        }
        deviceInfo.setUpdateBy(userName);

        //判断所属员工和所属公司是否对应
        if (deviceInfo.getCompanyUserId() != null) {
            CompanyUser companyUser = companyUserService.selectCompanyUserById(deviceInfo.getCompanyUserId());
            if (deviceInfo.getCompanyId() == null) {
                deviceInfo.setCompanyId(companyUser.getUserId());
            } else {
                if (!Objects.equals(deviceInfo.getCompanyId(), companyUser.getCompanyId())) {
                    return AjaxResult.error("所属员工不属于该公司!");
                }
            }
        }
        return toAjax(deviceInfoService.updateDeviceInfo(deviceInfo));
    }

    /**
     * 删除设备信息
     */
    @PreAuthorize("@ss.hasPermi('watchApi:deviceInfo:remove')")
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        return toAjax(deviceInfoService.deleteDeviceInfoByDeviceIds(deviceIds));
    }

    /**
     * 最新数据
     *
     * @param deviceId
     * @return 健康数据
     */
    @GetMapping("/queryLastWatchData")
    public AjaxResult queryLastWatchData(String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        return AjaxResult.success(watchDataService.queryLastWatchData(deviceId));
    }

    /**
     * 紧急联系人
     *
     * @param deviceId
     * @return 健康数据
     */
    @GetMapping("/querySos")
    public AjaxResult querySos(String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        return AjaxResult.success(watchDataService.querySos(deviceId));
    }

    /**
     * 根据设备id获取用户信息
     *
     * @param deviceId
     * @return 健康数据
     */
    @GetMapping("/queryWatchUserByDeviceId")
    public AjaxResult queryWatchUserByDeviceId(String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        return AjaxResult.success(watchUserService.selectWatchFsUserByDeviceId(deviceId));
    }


}
