package com.supervision.web.controller.peopleChuRu;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.supervision.common.core.domain.entity.SysDept;
import com.supervision.common.core.domain.entity.SysUser;
import com.supervision.common.core.domain.model.LoginUser;
import com.supervision.common.utils.DateUtils;
import com.supervision.peopleChuRu.domain.BdglLeaveFu;
import com.supervision.peopleChuRu.service.IBdglLeaveFuService;
import com.supervision.peopleManage.domain.BdglPeople;
import com.supervision.peopleManage.service.IBdglPeopleService;
import com.supervision.system.service.ISysDeptService;
import com.supervision.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.supervision.common.annotation.Log;
import com.supervision.common.core.controller.BaseController;
import com.supervision.common.core.domain.AjaxResult;
import com.supervision.common.enums.BusinessType;
import com.supervision.peopleChuRu.domain.BdglLeave;
import com.supervision.peopleChuRu.service.IBdglLeaveService;
import com.supervision.common.utils.poi.ExcelUtil;
import com.supervision.common.core.page.TableDataInfo;

/**
 * 人员请假Controller
 *
 * @author supervision
 * @date 2022-03-02
 */
@RestController
@RequestMapping("/peopleChuRu/bdglLeave")
public class BdglLeaveController extends BaseController {
    @Autowired
    private IBdglLeaveService bdglLeaveService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IBdglPeopleService bdglPeopleService;
    @Autowired
    private IBdglLeaveFuService leaveFuService;
    @Autowired
    ISysDeptService deptService;

    /**
     * 查询人员请假列表
     * <p>
     * 备注  common=1  普通审批
     * common=2  特殊审批
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:list')")
    @GetMapping("/list")
    public TableDataInfo list(BdglLeave bdglLeave) {
        if(bdglLeave.getName()!= null && bdglLeave.getName() != "") {
            List<String> list = bdglPeopleService.selectPowerPeoleListes(bdglLeave.getName());
            String str = list.stream().collect(Collectors.joining(","));
            String[] split = str.split(",");
            bdglLeave.setNames(split);
        }
        startPage();
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        startPage();
        List<BdglLeave> list = bdglLeaveService.selectBdglLeaveList(bdglLeave);
        int a = 0;
        c:
        for (BdglLeave leave : list) {
            //如果当前登录用户有特殊审批权限  显示归队按钮

            a++;
            if (leave.getStatus1().equals(2) || leave.getStatus2().equals(2) || leave.getStatus3().equals(2) || leave.getStatus4().equals(2) || leave.getRejoin().equals(1)
            ) {
                continue c;
            }
            boolean falg=false;
            if(sysUser.getPermissions()!=null){

                 falg = isFalg(sysUser,"3");
            }
            Integer status4 = leave.getStatus4();
            if (sysUser.getPermissions() != null) {
                if (leave.getStatus4().equals(1) || leave.getStatus4().equals(3) && falg) {
                    leave.setCommon("3");
                    continue c;
                }
                if (falg && leave.getPeopleId4() == null && (leave.getStatus3().equals(1) || leave.getStatus3().equals(3))) {
                    leave.setCommon("3");
                    continue c;
                }
                if (falg && leave.getPeopleId3() == null && leave.getPeopleId4() == null && (leave.getStatus2().equals(1) || leave.getStatus2().equals(3))) {
                    leave.setCommon("3");
                    continue c;
                }
                if (falg && leave.getPeopleId2() == null && leave.getPeopleId3() == null && leave.getPeopleId4() == null && (leave.getStatus1().equals(1) || leave.getStatus1().equals(3))) {
                    leave.setCommon("3");
                    continue c;
                }
            }
            if (leave.getStatus4() == 3 || leave.getStatus4() == 1) {
                continue c;
            }
            if (sysUser.getPermissions() != null) {
                //是否有特殊审批权限
                boolean falg2=false;
                if(sysUser.getPermissions()!=null){

                     falg2 = isFalg(sysUser,"0");
                }
                if (falg2) {

                    leave.setUnitId(loginUser.getUserId());
                    //如果特殊审批人和某级审批人相同   返回普通审批;
//                    if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId1())) || loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId2())) || loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId3())) || loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId4()))) {
//                        leave.setCommon("1");
//                    }
                    if (leave.getPeopleId1() != null) {
                        if (leave.getStatus1() == 0 && (leave.getStatus1() != 1 || leave.getStatus1() != 3)) {
                            leave.setShenPiJiBie("一级");
                            leave.setCommon("2");
                            if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId1()))) {
                                leave.setCommon("1");
                            }
                            continue c;
                        }
                    }
                    if (leave.getPeopleId2() != null) {
                        if ((leave.getStatus2() == 0 && (leave.getStatus1() == 1 || leave.getStatus1() == 3)) || (leave.getPeopleId1() == null && leave.getStatus2() == 0)) {
                            leave.setShenPiJiBie("二级");
                            leave.setCommon("2");
                            if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId2()))) {
                                leave.setCommon("1");
                            }
                            continue c;
                        }
                    }
                    if (leave.getPeopleId3() != null) {
                        if ((leave.getStatus3() == 0 && leave.getStatus3() != 1 && (leave.getStatus2() == 1 || leave.getStatus2() == 3)) || (leave.getPeopleId2() == null && leave.getStatus3() == 0)) {
                            leave.setShenPiJiBie("三级");
                            leave.setCommon("2");
                            if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId3()))) {
                                leave.setCommon("1");
                            }
                            continue c;
                        }
                    }
                    if (leave.getPeopleId4() != null) {

                        if ((leave.getStatus4() == 0 && leave.getStatus4() != 1 && (leave.getStatus3() == 1 || leave.getStatus3() == 3)) || (leave.getPeopleId3() == null && leave.getStatus4() == 0)) {

                            leave.setCommon("2");
                            leave.setShenPiJiBie("四级");
                            if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId4()))) {
                                leave.setCommon("1");
                            }
                            continue c;

                        }
                    }


                }
            }
            Long userId1 = loginUser.getUserId();
            Integer peopleId1 = leave.getPeopleId1();
            if (leave.getPeopleId1() != null) {
                if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId1()))) {
                    if (leave.getStatus1() == 0) {
                        leave.setCommon("1");
                        leave.setShenPiJiBie("一级");
                        continue c;
                    }
                }
            }
            if (leave.getPeopleId2() != null) {
                if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId2()))) {
                    if(leave.getPeopleId1()==null&&leave.getStatus2() == 0){
                        leave.setCommon("1");
                        leave.setShenPiJiBie("二级");
                        continue c;
                    }
                    if (leave.getStatus2() == 0 && leave.getStatus1() == 1 || leave.getStatus1() == 3) {
                        leave.setCommon("1");
                        leave.setShenPiJiBie("二级");
                        continue c;
                    }
                }
            }
            if (leave.getPeopleId3() != null) {
                if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId3()))) {
                    if(leave.getStatus3() == 0 && leave.getPeopleId2()==null && leave.getPeopleId1()==null){
                        leave.setCommon("1");
                        leave.setShenPiJiBie("三级");
                        continue c;
                    }
                    if (leave.getStatus3() == 0 && leave.getStatus2() == 1 || leave.getStatus2() == 3) {
                        leave.setCommon("1");
                        leave.setShenPiJiBie("三级");
                        continue c;

                    }
                }
            }
            if (leave.getPeopleId4() != null) {
                if (loginUser.getUserId().equals(Long.valueOf(leave.getPeopleId4()))) {
                    boolean b = leave.getStatus4() == 0;
                    boolean b1 = leave.getStatus3() == 1;
                    if (leave.getStatus4() == 0 && leave.getStatus3() == 1 || leave.getStatus3() == 3 || leave.getPeopleId3() == null) {
                        leave.setCommon("1");
                        leave.setShenPiJiBie("四级");
                        continue c;
                    }
                }
            }

        }
        return getDataTable(list);
    }

    public static boolean isFalg(SysUser sysUser, String aa) {
        boolean falg=false;
        String[] split = sysUser.getPermissions().split(",");
        for (String s : split) {
            if(s.equals(aa)){
                falg=true;
                break;
            }
        }
        return falg;
    }



    /**
     * 导出人员请假列表
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:export')")
    @Log(title = "人员请假", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BdglLeave bdglLeave) {
        List<BdglLeave> list = bdglLeaveService.selectBdglLeaveList(bdglLeave);
        ExcelUtil<BdglLeave> util = new ExcelUtil<BdglLeave>(BdglLeave.class);
        return util.exportExcel(list, "人员请假数据");
    }

    /**
     * 获取人员请假详细信息
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(bdglLeaveService.selectBdglLeaveById(id));
    }

    /**
     * 新增人员请假
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:add')")
    @Log(title = "人员请假", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BdglLeave bdglLeave) {
        BdglPeople bdglPeople = new BdglPeople();
        bdglPeople.setReign(Integer.parseInt(bdglLeave.getLeaveType()));
        bdglLeave.setCreatetime(DateUtils.getNowDate());
        return toAjax(bdglLeaveService.insertBdglLeave(bdglLeave));
    }

    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:guidui')")
    //@Log(title = "人员请假", businessType = BusinessType.INSERT)
    @PutMapping(value = "guidui")
    public AjaxResult guidui(@RequestBody BdglLeave bdglLeave) {
        BdglLeave bdglLeave1 = bdglLeaveService.selectBdglLeaveById(bdglLeave.getId());
        String[] split = bdglLeave.getPeopleId().split(",");
        String name = "";
        for (String s : split) {
            BdglPeople bdglPeople1 = bdglPeopleService.selectBdglPeopleById(Long.valueOf(s));
            bdglPeople1.setReign(0);
            name += bdglPeople1.getName() + ",";
            if (bdglLeave.getRejoin() != 0) {
                bdglPeopleService.updateBdglPeople(bdglPeople1);
                bdglLeave.setActualreturntime(new Date());
            }

        }
        BdglLeaveFu bdglLeaveFu = new BdglLeaveFu();
        if (bdglLeave.getCommon() != null) {
            if (bdglLeave.getCommon().equals("1") || bdglLeave.getCommon().equals("2") || bdglLeave.getCommon().equals("3") || bdglLeave.getCommon().equals("4")) {
                bdglLeaveFu.setPeople(bdglLeave.getCommon());
                bdglLeaveFu.setLeaveId(bdglLeave.getId());
                bdglLeaveFu.setSpecialApproval(bdglLeave.getSpecialApproval());
                leaveFuService.insertBdglLeaveFu(bdglLeaveFu);
            }
        }
        bdglLeave.setPeopleName(name.substring(0, name.length() - 1));

        return toAjax(bdglLeaveService.updateBdglLeave(bdglLeave));
    }
    /**
     * 修改人员请假
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:edit')")
    @Log(title = "人员请假", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BdglLeave bdglLeave) {   //判断人员是否归位  归位修改人员在位状态
        BdglLeave bdglLeave1 = bdglLeaveService.selectBdglLeaveById(bdglLeave.getId());
        updateBdglLeave(bdglLeave);
        return toAjax(bdglLeaveService.updateBdglLeave(bdglLeave));
    }
    
    private void updateBdglLeave(BdglLeave bdglLeave) {
        String[] split = bdglLeave.getPeopleId().split(",");
        StringBuilder name = new StringBuilder();
        for (String s : split) {
            BdglPeople bdglPeople1 = bdglPeopleService.selectBdglPeopleById(Long.valueOf(s));
            bdglPeople1.setReign(0);
            name.append(bdglPeople1.getName()).append(",");
            if (bdglLeave.getRejoin() != 0) {
                bdglPeopleService.updateBdglPeople(bdglPeople1);
                bdglLeave.setActualreturntime(new Date());
            }
        
        }
        BdglLeaveFu bdglLeaveFu = new BdglLeaveFu();
        if (bdglLeave.getCommon() != null) {
            if (bdglLeave.getCommon().equals("1") || bdglLeave.getCommon().equals("2") || bdglLeave.getCommon().equals("3") || bdglLeave.getCommon().equals("4")) {
                bdglLeaveFu.setPeople(bdglLeave.getCommon());
                bdglLeaveFu.setLeaveId(bdglLeave.getId());
                bdglLeaveFu.setSpecialApproval(bdglLeave.getSpecialApproval());
                leaveFuService.insertBdglLeaveFu(bdglLeaveFu);
            }
        }
        bdglLeave.setPeopleName(name.substring(0, name.length() - 1));
    }
    
    /**
     * 审批人员请假
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:shenpi')")
    @Log(title = "人员请假", businessType = BusinessType.UPDATE)
    @PutMapping("/shenpi")
    public AjaxResult shenpi(@RequestBody BdglLeave bdglLeave) {   //判断人员是否归位  归位修改人员在位状态
        updateBdglLeave(bdglLeave);
        return toAjax(bdglLeaveService.updateBdglLeave(bdglLeave));
    }
    
    /**
     * 特殊审批人员请假
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:teshu')")
    @Log(title = "人员请假", businessType = BusinessType.UPDATE)
    @PutMapping("/teshu")
    public AjaxResult tshenpi(@RequestBody BdglLeave bdglLeave) {   //判断人员是否归位  归位修改人员在位状态
        updateBdglLeave(bdglLeave);
        return toAjax(bdglLeaveService.updateBdglLeave(bdglLeave));
    }

    /**
     * 删除人员请假
     */
    @PreAuthorize("@ss.hasPermi('peopleChuRu:bdglLeave:remove')")
    @Log(title = "人员请假", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bdglLeaveService.deleteBdglLeaveByIds(ids));
    }

    @GetMapping("/getYingJIUSer")
    public AjaxResult getYingJIUSer(Long deptId) {
        Long deptId1 = getDeptId();
        SysDept sysDept = deptService.selectDeptById(deptId1);
        SysUser sysUser = new SysUser();
        if (sysDept.getAncestors().split(",").length == 2) {
            sysUser.setDeptId(deptId1);
        } else if (sysDept.getAncestors().split(",").length == 3) {
            sysUser.setDeptId(sysDept.getParentId());
        }
        List<SysUser> sysUsers = sysUserService.selectUsers(sysUser);
        return AjaxResult.success(sysUsers);
    }
    @GetMapping("/getLIanJIUSer")
    public AjaxResult getLIanJIUSer(Long deptId) {
        Long deptId1 = getDeptId();
        SysDept sysDept = deptService.selectDeptById(deptId1);
        SysUser sysUser = new SysUser();
        if (sysDept.getAncestors().split(",").length == 3) {
            sysUser.setDeptId(deptId1);
            List<SysUser> sysUsers = sysUserService.selectUsers(sysUser);
            return AjaxResult.success(sysUsers);
        }
        return null;
    }
    @GetMapping("/getZhengZhiUSer")
    public AjaxResult getZhengZhiUSer() {
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        Long deptId=0L;
        for (SysDept sysDept : sysDepts) {
            if(sysDept.getDeptName().contains("政治工作部")){
                deptId=sysDept.getDeptId();
                break;
            }
        }
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);
        List<SysUser> sysUsers = sysUserService.selectUsers(sysUser);
        return AjaxResult.success(sysUsers);
    }
}
