package com.rongwei.savecheck.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rongwe.scentity.domian.*;
import com.rongwe.scentity.vo.*;
import com.rongwei.commonservice.serial.service.SysSerialNumberService;
import com.rongwei.commonservice.service.RedisService;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.domain.SysRoleDo;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwcommonconfig.fegin.CommonFeginApi;
import com.rongwei.rwadmincommon.system.service.*;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.QueryPar;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.PinyinComparator;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.rwcommonconfig.fegin.CommonFeginApi;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import com.rongwei.sfcommon.sys.service.*;
import com.rongwei.sfcommon.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("mobileApi")
@Slf4j
public class MobileApiController {

    private static final Logger logger = LoggerFactory.getLogger(MobileApiController.class);

    @Autowired
    private CommonFeginApi commonFeginApi;
    @Autowired
    private CheckItemsService checkItemsService;
    @Autowired
    private CheckItemsDutyuserService checkItemsDutyuserService;
    @Autowired
    private PointCheckService pointCheckService;
    @Autowired
    private PointCheckItemService pointCheckItemService;
    @Autowired
    private ThemeCheckItemService themeCheckItemService;
    @Autowired
    private HiddenDangerTrackService hiddenDangerTrackService;
    @Autowired
    private SafetyObservationService safetyObservationService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrganizationService sysOrgService;
    @Autowired
    private SysUserOrgService sysUserOrgService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysSerialNumberService sysSerialNumberService;
    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private RedisService redisService;

    /**
     * 查询是否登录
     *
     * @param params
     * @return
     */
    @PostMapping("/wxLogin")
    public R wxLogin(@RequestBody Map<String, Object> params) {
        R r = commonFeginApi.apiExcuteByPar(params, "rw-common-server/wxsv/cmWxLogin");
        if (r.getData() != null) {
            Map<String, Object> dataMap = (Map<String, Object>) r.getData();
            String loginStatus = dataMap.get("loginStatus").toString();
            // 已登录，添加当前用户的关联设备列表
            if ("isLogin".equals(loginStatus)) {
                Map<String, Object> map = (Map<String, Object>) dataMap.get("userInfo");
                List<CheckItemsVo> checkItemsDos = checkItemsDutyuserService.getCheckItemsByUserId(map.get("userid").toString());
                checkItemsDos.forEach(v -> {
                    v.setChecked(false);
                });
                dataMap.put("hasCheckItems", checkItemsDos);
                List<CheckItemsDo> checkItems = checkItemsService.list();
                checkItems.sort(Comparator.comparing(CheckItemsDo::getModifydate).reversed());
                List<CheckItemsVo> checkItemsVos = new ArrayList<>();
                checkItems.forEach(v -> {
                    CheckItemsVo checkItemsVo = new CheckItemsVo();
                    BeanUtil.copyProperties(v, checkItemsVo);
                    checkItemsVo.setChecked(false);
                    checkItemsVos.add(checkItemsVo);
                });
                dataMap.put("allCheckItems", checkItemsVos);
                // 数据字典初始化
                if (params.get("dictTypes") != null) {
                    dataMap.put("dicts", sysDictService.getDictsByTypes((List<String>) params.get("dictTypes")));
                }
                // 员工列表
                dataMap.put("users", sysUserService.list());
                // 员工列表
                dataMap.put("userOrg", sysUserOrgService.list());
                // 组织机构列表
                dataMap.put("orgs", sysOrgService.list());
            } else {
                // 未登录则查询所有设备
                List<CheckItemsDo> checkItemsDos = checkItemsService.list();
                checkItemsDos.sort(Comparator.comparing(CheckItemsDo::getModifydate).reversed());
                List<CheckItemsVo> checkItemsVos = new ArrayList<>();
                checkItemsDos.forEach(v -> {
                    CheckItemsVo checkItemsVo = new CheckItemsVo();
                    BeanUtil.copyProperties(v, checkItemsVo);
                    checkItemsVo.setChecked(false);
                    checkItemsVos.add(checkItemsVo);
                });
                dataMap.put("allCheckItems", checkItemsVos);
                // 数据字典初始化
                if (params.get("dictTypes") != null) {
                    dataMap.put("dicts", sysDictService.getDictsByTypes((List<String>) params.get("dictTypes")));
                }
            }
            r.setData(dataMap);
        }
        return r;
    }

    /**
     * 小程序用户未绑定登录
     *
     * @param map
     * @return
     */
    @PostMapping("/wxLoginIn")
    public R wxLoginIn(@RequestBody Map<String, Object> map) {
        R r = commonFeginApi.apiExcuteByPar(map, "rw-common-server/wxsv/cmWxLoginIn");
        if (r.getData() != null) {
            Map<String, Object> dataMap = (Map<String, Object>) r.getData();
            Map<String, Object> userMap = (Map<String, Object>) dataMap.get("userInfo");
            SysUserVo sysUserVo = BeanUtil.mapToBean(userMap, SysUserVo.class, false);
            // 有绑定设备时登录时绑定
            if (map.get("checkItemsIds") != null) {
                String checkItemsIds = map.get("checkItemsIds").toString();
                String[] cids = checkItemsIds.split(",");
                if (cids != null && cids.length > 0) {
                    List<CheckItemsDutyuserDo> checkItemsDutyuserDos = new ArrayList<>();
                    for (String cid : cids) {
                        CheckItemsDutyuserDo checkItemsDutyuserDo = new CheckItemsDutyuserDo();
                        checkItemsDutyuserDo.setId(SecurityUtil.getUUID());
                        checkItemsDutyuserDo.setDutyuserid(sysUserVo.getId());
                        checkItemsDutyuserDo.setDutyusername(sysUserVo.getName());
                        checkItemsDutyuserDo.setDutyuserattribute(sysUserVo.getUserattribute());
                        checkItemsDutyuserDo.setCheckitemid(cid);
                        checkItemsDutyuserDo.setDutyuserattribute(sysUserVo.getUserattribute());
                        checkItemsDutyuserDos.add(checkItemsDutyuserDo);
                    }
                    checkItemsDutyuserService.saveBatch(checkItemsDutyuserDos);
                    Map<String, Object> bindMap = new HashMap<>();
                    bindMap.put("hasCheckItems", checkItemsDutyuserDos);
                    Map<String, Object> rDatas = (Map<String, Object>) r.getData();
                    rDatas.put("hasCheckItems", checkItemsDutyuserDos);
                }
            }
        }
        return r;
    }

    /**
     * 解除用户设备绑定
     *
     * @param map
     * @return
     */
    @PostMapping("/relieveCheckItems")
    public R relieveCheckItems(@RequestBody Map<String, Object> map) {
        try {
            if (map != null && map.size() > 0) {
                String userid = map.get("userid").toString();
                String checkItemsIds = map.get("checkItemsIds").toString();
                checkItemsDutyuserService.unbindCheckItemsByUseridAndCheckItemsIds(userid, checkItemsIds);
                // 用户已绑定设备列表
                Map<String, Object> dataMap = new HashMap<>();
                List<CheckItemsVo> checkItemsDos = checkItemsDutyuserService.getCheckItemsByUserId(userid);
                checkItemsDos.forEach(v -> {
                    v.setChecked(false);
                });
                dataMap.put("hasCheckItems", checkItemsDos);
                // 所有设备列表
                List<CheckItemsDo> allcheckItemsDos = checkItemsService.list();
                allcheckItemsDos.sort(Comparator.comparing(CheckItemsDo::getModifydate).reversed());
                dataMap.put("allCheckItems", allcheckItemsDos);
                return R.ok(dataMap);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return R.error();
        }
    }

    /**
     * 重新绑定
     *
     * @param map
     * @return
     */
    @PostMapping("/reBind")
    public R reBind(@RequestBody Map<String, Object> map) {
        try {
            // username
            if (map == null || map.get("userid") == null || map.get("username") == null || map.get("password") == null
                    || map.get("openid") == null || map.get("checkItemsIds") == null) {
                return R.errorWithMsg("缺少必要信息");
            }
            String userid = map.get("userid").toString();
            String checkItemsIds = map.get("checkItemsIds").toString();
            String openid = map.get("openid").toString();
            // 解除老userid绑定的微信号
            R r1 = commonFeginApi.apiExcuteByPar(map, "rw-common-server/wxsv/unbindWxUser");

            // 解除老userid绑定的设备
            /*if (org.apache.commons.lang3.StringUtils.isNotEmpty(checkItemsIds)) {
                checkItemsDutyuserService.unbindCheckItemsByUseridAndCheckItemsIds(userid, checkItemsIds);
            }*/

            // 新ID绑定
            R r = commonFeginApi.apiExcuteByPar(map, "rw-common-server/wxsv/cmWxLoginIn");
            Map<String, Object> dataMap = (Map<String, Object>) r.getData();
            Map<String, Object> userMap = (Map<String, Object>) dataMap.get("userInfo");
            SysUserVo sysUserVo = BeanUtil.mapToBean(userMap, SysUserVo.class, false);
            // 新用户绑定的设备
            List<CheckItemsVo> checkItemsDos = checkItemsDutyuserService.getCheckItemsByUserId(sysUserVo.getId());
            checkItemsDos.forEach(v -> {
                v.setChecked(false);
            });
            dataMap.put("hasCheckItems", checkItemsDos);

            // 新ID绑定设备
           /* if (org.apache.commons.lang3.StringUtils.isNotEmpty(checkItemsIds)) {
                List<CheckItemsDutyuserDo> list = checkItemsDutyuserService.bindCheckItemsByUserAndCheckItemsIds(sysUserVo, checkItemsIds);
            }*/
            dataMap.put("username", sysUserVo.getName());
            return R.ok(dataMap);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.error();
        }
    }

    /**
     * 设备绑定
     *
     * @param map
     * @return
     */
    @PostMapping("/addUserCheckItems")
    public R addUserCheckItems(@RequestBody Map<String, Object> map) {
        try {
            if (map.get("userid") != null && map.get("checkitemsid") != null) {
                String userid = map.get("userid").toString();
                SysUserDo sysUserDo = sysUserService.getById(userid);
                String checkitemsid = map.get("checkitemsid").toString();
                String[] checkitemsids = checkitemsid.split(",");
                for (String itemid : checkitemsids) {
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("checkitemid", itemid);
                    map2.put("deleted", "0");
                    map2.put("dutyuserid", userid);
                    List<CheckItemsDutyuserDo> tempList = (List<CheckItemsDutyuserDo>) checkItemsDutyuserService.listByMap(map2);
                    if (tempList.size() == 0) {
                        CheckItemsDutyuserDo checkItemsDutyuserDo = new CheckItemsDutyuserDo();
                        checkItemsDutyuserDo.setId(SecurityUtil.getUUID());
                        checkItemsDutyuserDo.setDutyuserid(userid);
                        checkItemsDutyuserDo.setDutyusername(sysUserDo.getName());
                        checkItemsDutyuserDo.setCheckitemid(itemid);
                        checkItemsDutyuserDo.setDutyuserattribute(sysUserDo.getUserattribute());
                        checkItemsDutyuserService.save(checkItemsDutyuserDo);
                    }
                }
                // 用户已绑定设备列表
                Map<String, Object> dataMap = new HashMap<>();
                List<CheckItemsVo> checkItemsDos = checkItemsDutyuserService.getCheckItemsByUserId(userid);
                checkItemsDos.forEach(v -> {
                    v.setChecked(false);
                });
                dataMap.put("hasCheckItems", checkItemsDos);
                // 所有设备列表
                List<CheckItemsDo> allcheckItemsDos = checkItemsService.list();
                allcheckItemsDos.sort(Comparator.comparing(CheckItemsDo::getModifydate).reversed());
                dataMap.put("allCheckItems", allcheckItemsDos);
                return R.ok(dataMap);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/checkItemList")
    public R checkItemList(@RequestParam QueryPar<CheckItemsPartsDo> params) {
        try {
            Wrapper<CheckItemsDo> entity = new QueryWrapper(params.getParameter());
            List<CheckItemsDo> list = checkItemsService.list(entity);
            return R.ok(list);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 备用设备列表
     *
     * @return
     * @para
     */

    @PostMapping("/spareList")
    public R spareList(@RequestBody QueryPar<CheckItemsDo> checkItemsDo) {
        try {
            IPage<CheckItemsDo> spareList = checkItemsService.spareList(checkItemsDo.getPage());
            return R.ok(spareList);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }


    /**
     * 移动端备用设备待点检、已点检、未点检列表查询
     *
     * @param pointCheckVo
     * @return
     */
    @PostMapping("/sparePointCheckList")
    public R sparePointCheckList(@RequestBody QueryPar<PointCheckVo> pointCheckVo) {
        try {
            IPage<PointCheckVo> list = pointCheckService.sparePointCheckList(pointCheckVo);
            return R.ok(list);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 移动端待点检、已点检列表查询
     *
     * @param pointCheckVo
     * @return
     */
    @PostMapping("/pointCheckList")
    public R pointCheckList(@RequestBody QueryPar<PointCheckVo> pointCheckVo) {
        try {
            // 查询当前人绑定的设备是否有点检任务
            // 查询当前人所在工段是否有没有绑定的设备有分配任务
            IPage<PointCheckVo> list = pointCheckService.pointCheckList(pointCheckVo);
            return R.ok(list);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 移动端未点检查询
     *
     * @param pointCheckVo
     * @return
     */
    @PostMapping("/notPointCheckList")
    public R notPointCheckList(@RequestBody QueryPar<PointCheckVo> pointCheckVo) {
        try {
            // 查询未点检
            IPage<PointCheckVo> list = pointCheckService.notPointCheckList(pointCheckVo);
            return R.ok(list);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 点检详情信息
     *
     * @param pointCheckDo
     * @return
     */
    @PostMapping("/pointCheckInfo")
    public R pointCheckInfo(@RequestBody PointCheckDo pointCheckDo) {
        try {
            PointCheckVo pointCheckVo = pointCheckService.ydPointCheckInfo(pointCheckDo);
            PointCheckVo lastpointCheckVo = pointCheckService.queryLastCheckInfo(pointCheckVo.getId());
            pointCheckVo.setLastPointCheck(lastpointCheckVo);
            return R.ok(pointCheckVo);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 点检信息保存
     *
     * @param pointCheckVo
     * @return
     */
    @PostMapping("/pointCheckSave")
    public R pointCheckSave(@RequestBody PointCheckVo pointCheckVo) {
        try {
            pointCheckService.pointCheckSave(pointCheckVo);
            Map<String, Object> map = new HashMap<>();
            map.put("ID", pointCheckVo.getId());
            pointCheckService.createHiddenDangerTask(map);
            return R.ok();
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.error();
        }
    }

    /**
     * 日常检查，待检查、已检查列表
     *
     * @param themeCheckItemVo
     * @return
     */
    @PostMapping("/themeCheckList")
    public R themeCheckList(@RequestBody QueryPar<ThemeCheckItemVo> themeCheckItemVo) {
        try {
            IPage<ThemeCheckItemVo> retList = themeCheckItemService.themeCheckList(themeCheckItemVo);
            return R.ok(retList);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 日常检查详情信息
     *
     * @param themeCheckItemVo
     * @return
     */
    @PostMapping("/themeCheckInfo")
    public R themeCheckInfo(@RequestBody ThemeCheckItemVo themeCheckItemVo) {
        try {
            ThemeCheckItemVo themeCheckItem = themeCheckItemService.themeCheckInfo(themeCheckItemVo);
            return R.ok(themeCheckItem);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 日常检查保存
     *
     * @param themeCheckItemVo
     * @return
     */
    @PostMapping("/themeCheckSave")
    public R themeCheckSave(@RequestBody ThemeCheckItemVo themeCheckItemVo) {
        try {
            themeCheckItemService.themeCheckSave(themeCheckItemVo);
            Map<String, Object> map = new HashMap<>();
            map.put("ID", themeCheckItemVo.getId());
            themeCheckItemService.createHiddenDangerTask(map);
            return R.ok();
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 隐患跟踪任务列表
     *
     * @param queryMap
     * @return
     */
    @PostMapping("/checkTaskList")
    public R checkTaskList(@RequestBody QueryPar<Map<String, Object>> queryMap) {
        try {
            IPage<HiddenDangerTrackVo> hiddenDangerTracks = hiddenDangerTrackService.checkTaskList(queryMap);
            return R.ok(hiddenDangerTracks);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 隐患跟踪任务详情信息
     *
     * @param hiddenDangerTrack
     * @return
     */
    @PostMapping("/checkTaskInfo")
    public R checkTaskInfo(@RequestBody HiddenDangerTrackDo hiddenDangerTrack) {
        try {
            HiddenDangerTrackVo hiddenDangerTrackVo = new HiddenDangerTrackVo();
            HiddenDangerTrackDo hiddenDangerTrackDo = hiddenDangerTrackService.getById(hiddenDangerTrack.getId());
            BeanUtil.copyProperties(hiddenDangerTrackDo, hiddenDangerTrackVo);
            /*if(StringUtils.isNotEmpty(hiddenDangerTrackDo.getTrackuserid())){
                Map<String,Object> maps = hiddenDangerTrackService.getTrackUserRoles(Arrays.asList(hiddenDangerTrackDo.getTrackuserid().split(",")));
                if(maps != null && maps.size()>0){
                    hiddenDangerTrackVo.setTrackUserRoles(maps);
                }
            }*/
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNotEmpty(token)) {
                SysUserVo sysUserVo = redisService.getLoginUser(token);
                Boolean hasSafeRole = false;
                Boolean hasGdzg = false;
                Boolean noPer = false;
                List<String> idList = new ArrayList<>();

                System.out.println("SysUserVo.ID:" + sysUserVo.getId());
                System.out.println(sysUserVo.getRoleDos());

                if (sysUserVo != null && sysUserVo.getRoleDos() != null && sysUserVo.getRoleDos().size() > 0) {
                    for (SysRoleDo sysRoleDo : sysUserVo.getRoleDos()) {
                        if ("code-safe".equals(sysRoleDo.getCode()) || "safety-engineer".equals(sysRoleDo.getCode())) {
                            hasSafeRole = true;
                        }
                        if ("gdzg".equals(sysRoleDo.getCode())) {
                            hasGdzg = true;
                        }
                    }

                    if (hasGdzg) {
                        idList.add(sysUserVo.getOrganizationDoList().get(0).getId());
                    } else if (hasSafeRole) {
                        idList = null;
                    } else {
                        noPer = true;
                    }
                } else {
                    noPer = true;
                }

                if (!noPer) {
                    List<SysUserVo> list1 = sysUserRoleService.getRoleUsersByRoleCode("spa");
                    if (idList != null && idList.size() > 0) {
                        List<SysUserVo> list = sysUserOrgService.getDeptUsersByDeptIds(idList);
                        if (list != null && list.size() > 0) {
                            list1.addAll(list);
                        }
                    }
                    //按照名称拼音排序
                    PinyinComparator<SysUserVo> pc = new PinyinComparator<>();
                    pc.setMethodName("getName");
                    Collections.sort(list1, pc);
                    hiddenDangerTrackVo.setTrackUserSelects(list1);
                }
            }

            return R.ok(hiddenDangerTrackVo);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 隐患跟踪任务保存更新
     *
     * @param hiddenDangerTrack
     * @return
     */
    @PostMapping("/saveOrUpdateTask")
    public R saveOrUpdateTask(@RequestBody HiddenDangerTrackDo hiddenDangerTrack) {
        try {
            if (!StringUtils.isNotEmpty(hiddenDangerTrack.getId())) {
                hiddenDangerTrack.setId(SecurityUtil.getUUID());
            }
            SysSerialVo sysSerialVo = new SysSerialVo();
            if (!StringUtils.isNotEmpty(hiddenDangerTrack.getCode())) {
                sysSerialVo.setRuleTemplateStr("@{date:yyyyMMdd}@{serialNumber:#000000}");
                sysSerialVo.setModulecode("asp_hidden_danger_track_CODE");
                hiddenDangerTrack.setCode(sysSerialNumberService.getCodeByTemplate(sysSerialVo));
            }
            hiddenDangerTrackService.saveOrUpdate(hiddenDangerTrack);
            return R.ok();
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 安全观察列表
     *
     * @param queryMap
     * @return
     */
    @PostMapping("/safetyObservationList")
    public R safetyObservationList(@RequestBody QueryPar<SafetyObservationDo> queryMap) {
        try {
            Wrapper<SafetyObservationDo> entity = new QueryWrapper(queryMap.getParameter());
            IPage<SafetyObservationDo> safetyObservationDos = safetyObservationService.page(queryMap.getPage(), entity);
            return R.ok(safetyObservationDos);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.queryError();
        }
    }

    /**
     * 安全观察详情信息
     *
     * @param safetyObservation
     * @return
     */
    @PostMapping("/safetyObservationInfo")
    public R safetyObservationInfo(@RequestBody SafetyObservationDo safetyObservation) {
        try {
            SafetyObservationDo safetyObservationDo = safetyObservationService.getById(safetyObservation.getId());
            SafetyObservationVo safetyObservationVo = new SafetyObservationVo();
            BeanUtil.copyProperties(safetyObservationDo, safetyObservationVo);
            if (safetyObservationVo.getObservationdate() != null) {
                safetyObservationVo.setObservationdatestr(DateUtil.format(safetyObservationVo.getObservationdate(), "yyyy-MM-dd"));
            }
            return R.ok(safetyObservationVo);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.error();
        }
    }

    /**
     * 安全观察保存或更新
     *
     * @param safetyObservation
     * @return
     */
    @PostMapping("/safetyObservationSaveOrUpdate")
    public R safetyObservationSaveOrUpdate(@RequestBody SafetyObservationDo safetyObservation) {
        log.info("begin save or update asp_safety_observation by safetyObservationDo:{}", safetyObservation);
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            boolean hasSetValue = false;
            if (StringUtils.isNotEmpty(safetyObservation.getObservationuserid())) {
                R r = sysUserService.get(safetyObservation.getObservationuserid());
                if (r.getData() != null) {
                    SysUserVo sysUserVo = (SysUserVo) r.getData();
                    if (sysUserVo.getSysuserorgids() != null && sysUserVo.getSysuserorgids().size() > 0) {
                        safetyObservation.setDeptid(sysUserVo.getSysuserorgids().get(0));
                        SysOrganizationDo sysOrganizationDo = sysOrganizationService.getById(sysUserVo.getSysuserorgids().get(0));
                        if (sysOrganizationDo != null) {
                            safetyObservation.setDeptname(sysOrganizationDo.getShortname());
                        }
                    }
                }
                // 判断是否有null
                if (StringUtils.isNotEmpty(safetyObservation.getObservationuserid()) && StringUtils.isNotEmpty(safetyObservation.getObservationuser())
                        && StringUtils.isNotEmpty(safetyObservation.getDeptid()) && StringUtils.isNotEmpty(safetyObservation.getDeptname())) {
                    hasSetValue = true;
                }
            }
            if (!hasSetValue) {
                if (StringUtils.isNotEmpty(token)) {
                    SysUserVo sysUserVo = redisService.getLoginUser(token);
                    if (sysUserVo != null) {
                        safetyObservation.setObservationuserid(sysUserVo.getId());
                        safetyObservation.setObservationuser(sysUserVo.getName());
                        if (sysUserVo.getOrganizationDoList() != null && sysUserVo.getOrganizationDoList().size() > 0) {
                            safetyObservation.setDeptid(sysUserVo.getOrganizationDoList().get(0).getId());
                            safetyObservation.setDeptname(sysUserVo.getOrganizationDoList().get(0).getShortname());
                        }
                    }
                }
            }
            // 当周数为空且安全观察日期不为空时 特殊处理weekIndex
            if (safetyObservation.getObservationdate() != null) {
                log.info("开始处理周数信息");
                // 和前端计算周数的逻辑保持一致
                Date observationDate = safetyObservation.getObservationdate();
                try {
                    String s = CommonUtil.getWeekForYear(observationDate, false);
                    safetyObservation.setWeekindex(Integer.parseInt(s.split(";")[1]));
                    safetyObservation.setYearindex(Integer.parseInt(s.split(";")[0]));
                } catch (Exception e) {
                    log.error("计算周数信息异常");
                }
            }
            if (StringUtils.isNotEmpty(safetyObservation.getId())) {
                safetyObservationService.saveOrUpdate(safetyObservation);
            } else {
                safetyObservation.setId(SecurityUtil.getUUID());
                safetyObservationService.save(safetyObservation);
            }
            return R.ok();
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.error();
        }
    }

    /**
     * 隐患上报初始化所有部门工段主管和spa人员信息
     */
    @GetMapping("/taskInitInfo")
    public R taskInitInfo() {
        try {
            List<Map<String, Object>> list = hiddenDangerTrackService.getAllDeptZGSPA();
            return R.ok(list);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.error();
        }
    }

    /**
     * 根据部门ID查询部门员工和spa角色人员
     *
     * @param idList
     * @return
     */
    @PostMapping("/getUserByDeptIds")
    public R getUserByDeptIds(@RequestBody List<String> idList) {
        try {
            List<SysUserVo> list1 = sysUserRoleService.getRoleUsersByRoleCode("spa");
            if (idList != null && idList.size() > 0) {
                List<SysUserVo> list = sysUserOrgService.getDeptUsersByDeptIds(idList);
                if (list != null && list.size() > 0) {
                    list1.addAll(list);
                }
            }
            //按照名称拼音排序
            PinyinComparator<SysUserVo> pc = new PinyinComparator<>();
            pc.setMethodName("getName");
            Collections.sort(list1, pc);
            return R.ok(list1);
        } catch (Exception e) {
            log.error(StringUtils.spliceErrorMsg(e), e.fillInStackTrace());
            return R.error();
        }
    }
}
