package com.bonus.system.leaveReporting.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.dept.dao.ProDeptRoleDao;
import com.bonus.system.holiday.dao.WorkReportDao;
import com.bonus.system.holiday.entity.HolidayBean;
import com.bonus.system.leaveReporting.entity.LeaveReportingBean;
import com.bonus.system.leaveReporting.service.LeaveReportingService;
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 lsun
 */
@RestController
@RequestMapping("/leaveReporting")
@Slf4j
public class LeaveReportingController extends BaseController {

    @Resource(name = "LeaveReportingService")
    private LeaveReportingService leaveReportingService;

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

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

    /**
     * 获取休假报备列表(表格)
     */
    @RequiresPermissions("flow:leaveReporting:list")
    @GetMapping("/list")
    @Log(title = "流程管理->休假报备->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo list(LeaveReportingBean 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){
                        List<MapVo> orgList = sysUser.getOrgList();
                        if (!orgList.isEmpty()) {
                            ArrayList<String> ids = new ArrayList<>();
                            for (MapVo mapVo : orgList) {
                                String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                                // 使用 Arrays.asList() 将数组转换为 ArrayList
                                ArrayList<String> idList = new ArrayList<>(Arrays.asList(id.split(",")));
                                ids.addAll(idList);
//                        ids.add(String.valueOf(mapVo.getId()));
                            }
                            bean.setOrgList(ids);
                        }
                    }else{
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(leaveReportingService.getLeaveReportingList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }


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

    /**
     * 修改休假报备
     */
    @RequiresPermissions("flow:leaveReporting:edit")
    @PutMapping
    @Log(title = "流程管理->休假报备->修改休假报备", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated @RequestBody LeaveReportingBean o) {
        try{
            AjaxResult result = isCheck(o.getId());
            if(result!=null){
                return result;
            }
            int res = leaveReportingService.updateLeaveReporting(o);
            return toAjax(res);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }


    /**
     * 删除休假报备
     */
    @RequiresPermissions("flow:leaveReporting:remove")
    @DeleteMapping("/{id}")
    @Log(title = "流程管理->休假报备->删除休假报备", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable("id") Long id) {
        try{
            AjaxResult result = isCheck(id);
            if(result!=null){
                return result;
            }
            return toAjax(leaveReportingService.deleteLeaveReportingById(id));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 判断休假报备数据是否被核对
     * @param id
     * @return AjaxResult
     * @author cwchen
     * @date 2025/2/12 14:32
     */
    public AjaxResult isCheck(Long id) {
        // 判断休假报备数据是否被核对
        Integer checkStatus = leaveReportingService.isCheck(id);
        if(!Objects.equals(checkStatus,0)){
            return AjaxResult.error("休假报备数据已被核对，无法操作");
        }else {
            return null;
        }
    }

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


    /**
     * 根据用户id获取职位信息
     */
    @GetMapping(value = "/getPostName/{id}")
    @Log(title = "流程管理->休假报备->查询职位信息", businessType = BusinessType.QUERY)
    public AjaxResult getPostName(@PathVariable Long id) {
        try{
            return success(leaveReportingService.getPostName(id));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 根据用户id获取同部门人员
     */
    @GetMapping(value = "/getUserList/{id}")
    @Log(title = "流程管理->休假报备->查询同部门人员", businessType = BusinessType.QUERY)
    public AjaxResult getUserList(@PathVariable Long id) {
        try{
            return success(leaveReportingService.getUserList(id));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 根据用户id 临时外出审核 代理主持工作人员
     */
    @GetMapping(value = "/getUserListCheck/{id}")
    @Log(title = "流程管理->临时外出审核->查询同部门人员", businessType = BusinessType.QUERY)
    public AjaxResult getUserListCheck(@PathVariable Long id) {
        try{
            return success(leaveReportingService.getUserListCheck(id));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 休假时间去除周末以及法定节假日
     * 1、查询出所有周末以及节假日的日期
     * 2、传入开始日期和结束日期，判断是否含有周末或者节假日
     * 3、计算去除周末或节假日后剩余天数
     */
    @PostMapping("/getDays")
    @Log(title = "流程管理->休假报备->计算时间", businessType = BusinessType.QUERY)
    public AjaxResult getDays(@Validated @RequestBody LeaveReportingBean bean){
        try {
            return success(leaveReportingService.getDays(bean));
        } catch (Exception e) {
            log.error(e.toString(),e);
        }
        return error("操作失败");

    }


}