package com.bonus.system.holiday.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.basic.dao.SysOrgDao;
import com.bonus.system.basic.dao.SysUserMapper;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.dept.entity.EightRoleBean;
import com.bonus.system.dept.entity.ProDeptRoleBean;
import com.bonus.system.dept.entity.ProDeptRoleDo;
import com.bonus.system.dept.entity.SubOrgBean;
import com.bonus.system.holiday.dao.WorkReportDao;
import com.bonus.system.holiday.entity.HolidayBean;
import com.bonus.system.holiday.service.HolidayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 轮休、临时外出、请假
 *
 * @author fly
 */
@RestController
@RequestMapping("/holiday")
@Slf4j
public class HolidayController extends BaseController {

    @Resource(name = "HolidayService")
    private HolidayService holidayService;

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

    @Resource
    private SysUserMapper userMapper;

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

    @Resource
    private SysOrgDao sysOrgDao;

    /**
     * 获取假期列表(表格)
     */
//    @RequiresPermissions("flow:holiday:list")
    @GetMapping("/list")
    @Log(title = "流程管理->假期管理->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo list(HolidayBean 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) {
                    //判断是否是普通人员
                    if (Collections.frequency(roleId, "15") == 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 {
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(holidayService.getHolidayList(bean));
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 新增假期
     */
//    @RequiresPermissions("flow:holiday:add")
    @PostMapping
    @Log(title = "流程管理->假期管理->新增假期", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated @RequestBody HolidayBean o) {
        try {
            int res = holidayService.insertHoliday(o);
            return toAjax(res);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("系统异常");
    }

    /**
     * 根据组织编号获取详细信息
     */
//    @RequiresPermissions("flow:holiday:query")
    @GetMapping(value = "/{id}")
    @Log(title = "流程管理->假期管理->查询单个请假单", businessType = BusinessType.QUERY)
    public AjaxResult getInfo(@PathVariable Long id) {
        try {
            return success(holidayService.selectHolidayById(id));
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("系统异常");
    }

    /**
     * 修改请假单
     */
//    @RequiresPermissions("flow:holiday:edit")
    @PutMapping
    @Log(title = "流程管理->假期管理->修改请假单", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated @RequestBody HolidayBean o) {
        try {
            int res = holidayService.updateHoliday(o);
            return toAjax(res);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("系统异常");
    }

    /**
     * 删除请假单
     */
//    @RequiresPermissions("flow:holiday:remove")
    @DeleteMapping("/{id}")
    @Log(title = "流程管理->假期管理->删除请假单", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable("id") Long id) {
        try {
            return toAjax(holidayService.deleteHolidayById(id));
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("系统异常");
    }

    /**
     * 获取假期列表(审核表格)
     */
//    @RequiresPermissions("flow:holiday:list")
    @GetMapping("/checkList")
    @Log(title = "流程管理->假期管理->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo checkList(HolidayBean 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) {
                    //判断是否是普通人员
                    if (Collections.frequency(roleId, "15") == 0) {
                        // 根据用户id查询是否是管理员
                        if (Collections.frequency(roleId, "14") == 0) {
                            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 {
                            //部门负责人
                            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<HolidayBean> holidayList = holidayService.getHolidayListCheck(bean);
            return endPage(holidayList);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 提交/撤回 审核
     */
//    @RequiresPermissions("flow:holiday:edit")
    @PutMapping("changeStatus")
    @Log(title = "流程管理->假期管理->修改状态", businessType = BusinessType.UPDATE)
    public AjaxResult changeStatus(@Validated @RequestBody HolidayBean o) {
        try {
            return toAjax(holidayService.changeStatus(o));
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return error("系统异常");
    }

    @PostMapping("batchLxCheckStatus")
    @Log(title = "流程相关->轮休审批->一键审批", businessType = BusinessType.UPDATE)
    public AjaxResult batchCheckStatus(@Validated @RequestBody HolidayBean o) {
       return holidayService.batchCheckStatus(o);
    }

    @PostMapping("batchLsCheckStatus")
    @Log(title = "流程相关->临时外出审核->一键审批", businessType = BusinessType.UPDATE)
    public AjaxResult batchLsCheckStatus(@Validated @RequestBody HolidayBean o) {
        return holidayService.batchCheckStatus(o);
    }



}
