package com.bonus.system.evection.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.evection.entity.EvectionBean;
import com.bonus.system.evection.service.EvectionService;
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 java.util.*;

/**
 * 出差报备
 *
 * @author lsun
 */
@RestController
@RequestMapping("/evection")
@Slf4j
public class EvectionController extends BaseController {

    @Resource(name = "EvectionService")
    private EvectionService evectionService;

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

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

    /**
     * 获取出差报备列表(表格)
     */
    @RequiresPermissions("flow:evection:list")
    @GetMapping("/list")
    @Log(title = "流程管理->出差报备->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo list(EvectionBean bean) {
        try{

//            //不是管理员，只能查自己
//            Long userId = SecurityUtils.getUserId();
//            List<SysRole> sysRoleList = dao.getRoleListByUserId(userId);
//            int roleCount = 0;
//            if(!sysRoleList.isEmpty()){
//                for (SysRole sysRole : sysRoleList) {
//                    if(sysRole.getRoleName().contains("管理员")){
//                        roleCount = 1;
//                        break;
//                    }
//                }
//            }
//            if(roleCount==1){
//
//            }else{
//                bean.setUserId(userId);
//            }
            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);
                        }
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }else{
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(evectionService.getEvectionList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }


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

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


    /**
     * 删除出差报备
     */
    @RequiresPermissions("flow:evection:remove")
    @DeleteMapping("/{id}")
    @Log(title = "流程管理->出差报备->删除出差报备", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable("id") String id) {
        try{
            AjaxResult result = isCheck(id,2);
            if(result!=null){
                return result;
            }
            return toAjax(evectionService.deleteEvectionById(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(String id,int type) {
        // 判断休假报备数据是否被核对
        Integer checkStatus = evectionService.isCheck(id,type);
        if(!Objects.equals(checkStatus,0)){
            return AjaxResult.error("出差报备数据已被核对，无法操作");
        }else {
            return null;
        }
    }

    /**
     * 根据id获取详细信息
     */
    @RequiresPermissions("flow:evection:query")
    @GetMapping(value = "/{id}")
    @Log(title = "流程管理->出差报备->查询单个出差报备", businessType = BusinessType.QUERY)
    public AjaxResult getInfo(@PathVariable String id) {
        try{
            return success(evectionService.selectEvectionById(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(evectionService.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(evectionService.getUserList(id));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

}