package com.bonus.system.att.controller;

import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.Log;
import com.bonus.common.log.enums.BusinessType;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysRole;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.att.entity.AttDataDetailsBean;
import com.bonus.system.att.entity.AttDayReportBean;
import com.bonus.system.att.entity.AttMonthReportBean;
import com.bonus.system.att.service.AttendanceDetailsService;
import com.bonus.system.basic.dao.SysOrgDao;
import com.bonus.system.basic.dao.SysUserMapper;
import com.bonus.system.basic.domain.SysOrg;
import com.bonus.system.basic.service.SysOrgService;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.holiday.dao.WorkReportDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 考勤统计
 *
 * @author zys
 */
@RestController
@RequestMapping("/attDetails")
@Slf4j
public class AttendanceDetailsController extends BaseController {

    @Resource(name = "attendanceDetailsService")
    private AttendanceDetailsService attendanceDetailsService;

    @Resource(name = "sysOrgService")
    private SysOrgService sysOrgService;

    @Resource(name = "WorkReportDao")
    private WorkReportDao dao;

    @Resource(name = "ProDeptRoleDao")
    private ProDeptRoleDao proDeptRoleDao;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysOrgDao sysOrgDao;

    /**
     * 获取考勤原始明细列表
     */
    @RequiresPermissions("att:attOriginal:list")
    @GetMapping("/getOriginalList")
    @Log(title = "考勤报表->考勤明细->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getOriginalList(AttDataDetailsBean bean) {
        try{
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(attendanceDetailsService.selectAttOriginalList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 获取考勤统计列表
     */
    @RequiresPermissions("att:attDetails:list")
    @GetMapping("/getDetailsList")
    @Log(title = "考勤报表->考勤明细->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getDetailsList(AttDataDetailsBean bean) {
        try{
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    //判断是否是普通人员
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(attendanceDetailsService.selectAttDetailsList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 修改考勤
     */
    @RequiresPermissions("att:attDetails:edit")
    @PutMapping
    @Log(title = "考勤报表->考勤明细->考勤修改", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@RequestBody List<AttDataDetailsBean> list) {
        try{
            return toAjax(attendanceDetailsService.updateAttDetailsData(list));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 审核考勤
     */
    @RequiresPermissions("att:attDetailsUpdate:exam")
    @PutMapping("updateAttDetailsDataExamine")
    @Log(title = "考勤报表->考勤明细->考勤修改", businessType = BusinessType.UPDATE)
    public AjaxResult examine(@RequestBody List<AttDataDetailsBean> list) {
        try{
            return toAjax(attendanceDetailsService.updateAttDetailsDataExamine(list));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取考勤修改列表
     */
    @RequiresPermissions("att:attDetailsUpdate:list")
    @GetMapping("/getAttUpdateList")
    @Log(title = "考勤报表->考勤明细修改记录->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getAttUpdateList(AttDataDetailsBean bean) {
        try{
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是考勤员
                    if (Collections.frequency(roleId, "14") == 1) {
                        Long userId = SecurityUtils.getUserId();
                        List<MapVo> orgList = sysOrgDao.getOrgIdListAdministrators(userId);
                        if (!orgList.isEmpty()) {
                            // 使用 LinkedHashSet 来保证顺序并自动去重
                            Set<String> idsSet = new LinkedHashSet<>();
                            for (MapVo mapVo : orgList) {
                                String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                                if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                    // 将分割后的数组添加到 Set 中，自动去重
                                    Collections.addAll(idsSet, id.split(","));
                                }
                            }
                            // 如果需要转换回 List 类型
                            List<String> uniqueIds = new ArrayList<>(idsSet);
                            bean.setOrgList(uniqueIds);
                        }
                    } else if (Collections.frequency(roleId, "14") == 1) {
                        //部门负责人
                        Long userId = SecurityUtils.getUserId();
                        List<MapVo> orgList = sysOrgDao.getOrgIdListManager(userId);
                        if (!orgList.isEmpty()) {
                            // 使用 LinkedHashSet 来保证顺序并自动去重
                            Set<String> idsSet = new LinkedHashSet<>();
                            for (MapVo mapVo : orgList) {
                                String id = mapVo.getId() +"";
                                if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                    // 将分割后的数组添加到 Set 中，自动去重
                                    Collections.addAll(idsSet, id);
                                }
                            }
                            // 如果需要转换回 List 类型
                            List<String> uniqueIds = new ArrayList<>(idsSet);
                            bean.setOrgList(uniqueIds);
                        }
                    }else{
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            List<AttDataDetailsBean> attDataDetailsBeans = attendanceDetailsService.selectAttUpdateList(bean);
            return endPage(attDataDetailsBeans);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 获取组织列表
     */
    @GetMapping("/orgList")
    @Log(title = "系统管理->组织管理", businessType = BusinessType.QUERY)
    public AjaxResult list(SysOrg sysOrg) {
        try{
            List<SysOrg> org = sysOrgService.selectOrgList(sysOrg);
            return success(org);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取组织列表
     */
    @GetMapping("/orgListAll")
    @Log(title = "系统管理->组织管理", businessType = BusinessType.QUERY)
    public AjaxResult orgListAll(SysOrg sysOrg) {
        try{
            List<SysOrg> org = sysOrgService.selectOrgListAll(sysOrg);
            return success(org);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取日报表
     */
    @RequiresPermissions("att:attDayReport:list")
    @GetMapping("/getAttDayReportList")
    @Log(title = "考勤报表->日报表->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getAttDayReportList(AttDayReportBean bean) {
        try{
            List<AttDayReportBean> attDayReportList = attendanceDetailsService.getAttDayReportList(bean);
            attDayReportList.sort(Comparator.comparing(AttDayReportBean::getAttCurrentDay).reversed());
            return endPage(attDayReportList);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 获取日报表-详细记录
     */
    @RequiresPermissions("att:attDayReport:list")
    @GetMapping("/getAttDayReportDetailsList")
    @Log(title = "考勤报表->日报表->考勤记录查询", businessType = BusinessType.QUERY)
    public TableDataInfo getAttDayReportDetailsList(AttDataDetailsBean bean) {
        try{
            startPage();
            return getDataTable(attendanceDetailsService.getAttDayReportDetailsList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 日报表导出
     */
    @GetMapping("/exportAttDayReportData")
    @RequiresPermissions("att:attDayReport:export")
    @Log(title = "考勤报表->日报表->导出", businessType = BusinessType.EXPORT)
    public void exportAttDayReportData(HttpServletResponse response, AttDayReportBean o){
        attendanceDetailsService.exportAttDayReportData(response, o);
    }

    /**
     * 获取月报表
     */
    @RequiresPermissions("att:attMonthReport:list")
    @GetMapping("/getAttMonthReportList")
    @Log(title = "考勤报表->月报表->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getAttMonthReportList(AttMonthReportBean bean) {
        try{
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(attendanceDetailsService.getAttMonthReportList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    @GetMapping("/getClockingRecordListByUserId")
    @Log(title = "考勤报表->月报表->打卡记录", businessType = BusinessType.QUERY)
    public TableDataInfo getClockingRecordListByUserId(AttMonthReportBean bean) {
        startPage();
        return getDataTable(attendanceDetailsService.getClockingRecordListByUserId(bean));
    }

    /**
     * 月报表导出
     */
    @RequiresPermissions("att:attMonthReport:export")
    @GetMapping("/exportAttMonthReportData")
    @Log(title = "考勤报表->月报表->导出", businessType = BusinessType.EXPORT)
    public void exportAttMonthReportData(HttpServletResponse response, AttMonthReportBean o){
        attendanceDetailsService.exportAttMonthReportData(response, o);
    }

//    @RequiresPermissions("att:public:list")
    @GetMapping("/getOutCountList")
    @Log(title = "考勤报表->公用->外出次数查询", businessType = BusinessType.QUERY)
    public TableDataInfo getOutCountList(AttDataDetailsBean bean) {
        try{
            startPage();
            return getDataTable(attendanceDetailsService.getOutCountList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

//    @RequiresPermissions("att:public:list")
    @GetMapping("/getAttCountList")
    @Log(title = "考勤报表->考情明细->打卡次数记录", businessType = BusinessType.QUERY)
    public TableDataInfo getAttCountList(AttDataDetailsBean bean) {
        try{
            startPage();
            return getDataTable(attendanceDetailsService.getAttCountList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 用户新增
     */
    @PostMapping("/synchronous")
    @Log(title = "考勤报表-> 考勤明细->数据同步", businessType = BusinessType.INSERT)
    public AjaxResult synchronous(@Validated @RequestBody AttDataDetailsBean bean) {
        return attendanceDetailsService.synchronous(bean);
    }


    /**
     * 获取日报表-详细记录
     */
    @GetMapping("/getAttDayList")
    @Log(title = "考勤报表->日报表->今日出勤状态", businessType = BusinessType.QUERY)
    public TableDataInfo getAttDayList(AttDataDetailsBean bean) {
        try{
            startPage();
            return getDataTable(attendanceDetailsService.getAttDayList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }


    /**
     * 获取数据看板-详细记录
     */
    @GetMapping("/getAttDayReportDetailsListData")
    @Log(title = "数据看板->数据看板-> 今日异常统计", businessType = BusinessType.QUERY)
    public TableDataInfo getAttDayReportDetailsListData(AttDataDetailsBean bean) {
        try{
            startPage();
            return getDataTable(attendanceDetailsService.getAttDayReportDetailsListData(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }
}
