package com.yanzhu.jh.publics;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.PublicStateEnum;
import com.ruoyi.common.enums.SysRoleEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.FlowTaskEntity;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.yanzhu.jh.project.domain.*;
import com.yanzhu.jh.project.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 公共服务Controller
 *
 * @author JiangYuQi
 * @date 2023-07-29
 */
@RestController
@RequestMapping("/publics")
public class
PublicsController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISurProjectService surProjectService;

    @Autowired
    private ISurProjectUnitInfoService surProjectUnitInfoService;

    @Autowired
    private ISurProjectUserinfoService surProjectUserinfoService;

    @Autowired
    private ISurProjectAuditinfoService surProjectAuditinfoService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取部门列表
     */
    @GetMapping("/deptList")
    public AjaxResult list(SysDept dept)
    {
        dept.setStatus(PublicStateEnum.OK.getCode());
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 获取子公司部门列表
     */
    @GetMapping("/queryZgsDeptList")
    public AjaxResult queryZgsDeptList(SysDept dept)
    {
        String key="publics_queryZgsDeptList";
        Object obj=redisCache.getCacheObject(key);
        if(obj!=null){
            return success(obj);
        }
        dept.setStatus(PublicStateEnum.OK.getCode());
        dept.setComFlag(PublicStateEnum.COMZGS.getCode());
        List<SysDept> list = deptService.selectAllDeptList(dept);
        redisCache.setCacheObject(key, list, Constants.BIGSCREEN_QUERY_CACHE, TimeUnit.MINUTES);
        return success(list);
    }

    /**
     * 查询项目列表
     */
    @GetMapping("/projectList")
    public TableDataInfo projectList(SurProject surProject)
    {
        List<SurProject> list = surProjectService.selectSurProjectList(surProject);
        return getDataTable(list);
    }

    /**
     * 查询我的项目列表
     */
    @GetMapping("/findMyProjectList")
    public TableDataInfo findMyProjectList(SurProject surProject)
    {
        surProject.setNowRole(Convert.toStr(getUserFirstRole()));
        if(SysRoleEnum.ZGS.getCode().equals(surProject.getNowRole())){
            surProject.setNowDept(Convert.toStr(deptService.getZGSDeptId(getDeptId())));
        }else{
            surProject.setNowDept(Convert.toStr(getDeptId()));
        }
        surProject.setNowUser(Convert.toStr(getUserId()));
        List<SurProject> list = surProjectService.selectSurProjectList(surProject);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/userList")
    public TableDataInfo list(SysUser user)
    {
        user.setDelFlag(PublicStateEnum.OK.getCode());
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 查询项目部门列表
     */
    @GetMapping("/queryUnitList")
    public TableDataInfo queryUnitList(SurProjectUnitInfo surProjectUnitInfo)
    {
        surProjectUnitInfo.setNowRole(Convert.toStr(getUserFirstRole()));
        // 如果查询当前监理单位 && 当前角色是监理单位则只能查询自己单位
        if(surProjectUnitInfo.getUnitTypes()!=null && surProjectUnitInfo.getUnitTypes().contains(4) && (surProjectUnitInfo.getNowRole().equals(SysRoleEnum.JLDW.getCode()) || surProjectUnitInfo.getNowRole().equals(SysRoleEnum.JLDWGR.getCode()))){
            surProjectUnitInfo.setUnitId(getDeptId());
        }
        if(surProjectUnitInfo.getUnitType()!=null && surProjectUnitInfo.getUnitType().equals("4") && (surProjectUnitInfo.getNowRole().equals(SysRoleEnum.JLDW.getCode()) || surProjectUnitInfo.getNowRole().equals(SysRoleEnum.JLDWGR.getCode()))){
            surProjectUnitInfo.setUnitId(getDeptId());
        }
        // 如果查询当前总包单位 && 当前角色是监理单位则只能查询自己单位
        if(surProjectUnitInfo.getUnitTypes()!=null && surProjectUnitInfo.getUnitTypes().contains(2) && (surProjectUnitInfo.getNowRole().equals(SysRoleEnum.ZBDW.getCode()) || surProjectUnitInfo.getNowRole().equals(SysRoleEnum.ZBDWGR.getCode()))){
            surProjectUnitInfo.setUnitId(getDeptId());
        }
        if(surProjectUnitInfo.getUnitType()!=null && surProjectUnitInfo.getUnitType().equals("2") && (surProjectUnitInfo.getNowRole().equals(SysRoleEnum.ZBDW.getCode()) || surProjectUnitInfo.getNowRole().equals(SysRoleEnum.ZBDWGR.getCode()))){
            surProjectUnitInfo.setUnitId(getDeptId());
        }
        return getDataTable(surProjectUnitInfoService.selectSurProjectUnitInfoList(surProjectUnitInfo));
    }

    /**
     * 选择项目所有部门人员
     */
    @GetMapping("/selectProjectAllUnitUser")
    public AjaxResult selectProjectAllUnitUser(SurProjectUserinfo surProjectUserinfo)
    {
        String key="publics_selectProjectAllUnitUser_"+surProjectUserinfo.getProjectId();
        Object obj=redisCache.getCacheObject(key);
        if(obj!=null){
            return success(obj);
        }
        List<SurProjectUnitInfo> list = surProjectUserinfoService.selectProjectUnitUser(surProjectUserinfo);
        redisCache.setCacheObject(key, list, Constants.BIGSCREEN_QUERY_CACHE, TimeUnit.MINUTES);
        return success(list);
    }

    /**
     * 选择项目部门人员
     */
    @GetMapping("/selectProjectUnitUser")
    public AjaxResult selectProjectUnitUser(SurProjectUnitInfo surProjectUnitInfo)
    {
        String key="publics_selectProjectUnitUser_"+surProjectUnitInfo.getProjectId();
        Object obj=redisCache.getCacheObject(key);
        if(obj!=null){
            return success(obj);
        }
        List<SurProjectUnitInfo> list = surProjectUserinfoService.selectProjectUnitUser(surProjectUnitInfo);
        redisCache.setCacheObject(key, list, Constants.BIGSCREEN_QUERY_CACHE, TimeUnit.MINUTES);
        return success(list);
    }

    /**
     * 查询项目审核信息列表
     */
    @GetMapping("/selectProjectAuditinfo")
    public AjaxResult selectProjectAuditinfo(SurProjectAuditinfo surProjectAuditinfo)
    {
        return success(surProjectAuditinfoService.selectProjectAuditinfoList(surProjectAuditinfo));
    }

    /**
     * 查询代办任务
     */
    @GetMapping("/findTask")
    public AjaxResult findTask()
    {
        FlowTaskEntity flowTaskEntity = new FlowTaskEntity();
        flowTaskEntity.setNowRole(Convert.toStr(getUserFirstRole()));
        if(SysRoleEnum.ZGS.getCode().equals(flowTaskEntity.getNowRole())){
            flowTaskEntity.setNowDept(Convert.toStr(deptService.getZGSDeptId(getDeptId())));
        }else{
            flowTaskEntity.setNowDept(Convert.toStr(getDeptId()));
        }
        flowTaskEntity.setNowUser(Convert.toStr(SecurityUtils.getUserId()));
        flowTaskEntity.setRoleIds(SecurityUtils.getLoginUser().getUser().getRoles().stream().map(role -> role.getRoleId()).collect(Collectors.toList()));
        flowTaskEntity.setNowUserName(getUsername());
        flowTaskEntity.setActiveName("await");
        return success(surProjectAuditinfoService.findMyTask(flowTaskEntity));
    }

    @Autowired
    private ISurProjectAttendanceCfgService surProjectAttendanceCfgService;

    @Autowired
    private ISurProjectAttendanceDataService surProjectAttendanceDataService;

    /**
     * 查询代办任务
     */
    @GetMapping("/v1/initAttendanceData")
    public AjaxResult initAttendanceData()
    {
        //开始时间
        Calendar calendar = Calendar.getInstance();
        /***
         * 查询所有项目考勤配置
         */
        List<SurProjectAttendanceCfg> cfgList = surProjectAttendanceCfgService.selectSurProjectAttendanceCfgList(new SurProjectAttendanceCfg());
        Map<String, Object> data = new HashMap<>();
        for(SurProjectAttendanceCfg cfg:cfgList){
            calendar.setTime(DateUtils.parseDate("2023-07-16"));
            data.put("cfgid",cfg.getId());
            for(int i=0;i<365;i++){
                if(calendar.getTimeInMillis()>System.currentTimeMillis()){
                    /** 跳出本次循环 **/
                    break;
                }
                calendar.add(Calendar.DATE, 1);
                data.put("date",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,calendar.getTime()));
                List<Map<String,Object>> list;
                if(cfg.getVendorsCode().equals("huazhu")){
                    list = surProjectAttendanceDataService.initHuaZhuData(data);
                }else{
                    list = surProjectAttendanceDataService.initOtherData(data);
                }
                List<SurProjectAttendanceData> dataList = new ArrayList<>();
                for(Map<String,Object> map:list){
                    SurProjectAttendanceData attendanceData = new SurProjectAttendanceData();
                    attendanceData.setCfgid(cfg.getId());
                    attendanceData.setAppId(map.get("app_id").toString());
                    attendanceData.setProjectId(cfg.getProjectId());
                    attendanceData.setProjectName(cfg.getProjectName());
                    attendanceData.setDeptId(cfg.getSubDeptId());
                    attendanceData.setDeptName(cfg.getUnitName());
                    attendanceData.setVendorsCode(cfg.getVendorsCode());
                    attendanceData.setServerid(map.get("serverid").toString());
                    attendanceData.setWorkerId(map.get("workerId").toString());
                    attendanceData.setWorkerName(map.get("name").toString());
                    attendanceData.setIdentification(map.get("identification").toString());
                    attendanceData.setWorkerPhoto(Convert.toStr(map.get("recentPhoto")));
                    attendanceData.setWorkerGender(Convert.toLong(map.get("gender")));
                    attendanceData.setBirthDate(Convert.toLong(map.get("birthDate")));
                    attendanceData.setEthnic(map.get("ethnic").toString());
                    attendanceData.setNativePlace(map.get("nativePlace").toString());
                    attendanceData.setPhone(map.get("phone").toString());
                    attendanceData.setWorkTypeName(map.get("workTypeName").toString());
                    attendanceData.setSpecWorkType(Convert.toInt(map.get("specWorkType")));
                    attendanceData.setGroupName(map.get("groupName").toString());
                    attendanceData.setCompanyTypeId(Convert.toStr(map.get("companyTypeId"),"0"));
                    attendanceData.setCompanyName(map.get("companyName").toString());
                    attendanceData.setAttendanceTime(Convert.toStr(map.get("inTime")));
                    attendanceData.setAttendanceOutTime(Convert.toStr(map.get("outTime")));
                    attendanceData.setScanPhoto(Convert.toStr(map.get("scanPhoto")));
                    attendanceData.setTeamId(Convert.toLong(map.get("teamId")));
                    attendanceData.setWorkTypeCode(Convert.toStr(map.get("workTypeCode")));
                    attendanceData.setCompanyId(Convert.toStr(map.get("companyId")));
                    attendanceData.setVendorId(Convert.toLong(map.get("vendorId")));
                    attendanceData.setDeviceCode(Convert.toStr(map.get("device_code")));
                    attendanceData.setIsDel(Convert.toLong(map.get("is_del")));
                    attendanceData.setCreateBy("数据迁移格式化");
                    attendanceData.setCreateTime(new Date());
                    dataList.add(attendanceData);
                }
                if(StringUtils.isNotEmpty(dataList)){
                    surProjectAttendanceDataService.batchSurProjectAttendanceData(dataList);
                }
            }
        }
        return success();
    }
}
