package com.yunyan.web.controller.system;

import java.util.List;

import com.yunyan.business.pojo.admin.dto.SysDeptEditDto;
import com.yunyan.common.annotation.Anonymous;
import com.yunyan.common.core.domain.entity.SysUser;
import com.yunyan.system.domain.dto.SysDeptImportDataDto;
import com.yunyan.business.pojo.admin.vo.SysDeptOverviewVo;
import com.yunyan.common.core.domain.AjaxResultVo;
import com.yunyan.common.core.page.TableDataInfo;
import com.yunyan.common.utils.SecurityUtils;
import com.yunyan.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.yunyan.common.annotation.Log;
import com.yunyan.common.constant.UserConstants;
import com.yunyan.common.core.controller.BaseController;
import com.yunyan.common.core.domain.AjaxResult;
import com.yunyan.common.core.domain.entity.SysDept;
import com.yunyan.common.enums.BusinessType;
import com.yunyan.common.utils.StringUtils;
import com.yunyan.system.service.ISysDeptService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 部门信息
 *
 * @author yunyan
 */
@Slf4j
@Api(tags = "6.0.2 部门(部门概况)")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @ApiOperation(value="获取部门列表", notes="获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResultVo<List<SysDept>> list(SysDept dept)
    {
        //long startTime = System.currentTimeMillis();
        List<SysDept> depts = deptService.selectDeptList(dept);
//        List<SysDept> depts = new ArrayList<>();
        SysDept sysDept = new SysDept();

//        depts.add(sysDept);

        /*long endTime = System.currentTimeMillis();
        long usedTime = (endTime-startTime)/1000;
        log.debug("耗时 [{}] - [{}]", usedTime, endTime - startTime);*/
        return AjaxResultVo.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResultVo<SysDept> getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResultVo.success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return warn("部门存在用户,不允许删除");
        }
        if(true){
            return AjaxResult.error("删除前请联系管理员!");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    @ApiOperation(value="获取部门概况列表", notes="获取部门概况列表")
    @PreAuthorize("@ss.hasPermi('system:dept:overviewlist')")
    @GetMapping("/list/overview")
    public TableDataInfo<List<SysDept>> overviewlist(SysDept dept)
    {
        startPage();
        List<SysDept> depts = deptService.selectDeptList(dept);
        return getDataTable(depts);
//        return AjaxResultVo.success(depts);
    }

    @ApiOperation(value="查询部门概况信息", notes="查询部门概况信息")
    @PreAuthorize("@ss.hasPermi('system:dept:overview')")
    @GetMapping(value = "/overview/{deptId}")
    public AjaxResultVo<SysDeptOverviewVo> overview(@PathVariable Long deptId)
    {
        SysDept dept = deptService.getById(deptId);
        if(null == dept) {
            return AjaxResultVo.error("查询异常~");
        }
        SysDeptOverviewVo vo = new SysDeptOverviewVo();
        BeanUtils.copyProperties(dept, vo);
        return AjaxResultVo.success(vo);
    }

    @ApiOperation(value="部门概况修改", notes="部门概况修改")
    @PreAuthorize("@ss.hasPermi('system:dept:overviewEdit')")
    @Log(title = "部门概况修改", businessType = BusinessType.UPDATE)
    @PutMapping("/overview")
    public AjaxResult edit(@Validated @RequestBody SysDeptEditDto dto)
    {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(dto, dept);
        return toAjax(deptService.updateById(dept));
    }

    @Deprecated
    @ApiOperation(value="查询当前用户的第一个单位信息", notes="查询当前用户的第一个单位信息")
    //@PreAuthorize("@ss.hasPermi('system:dept:userDeptInfo')")
    @GetMapping(value = "/userDeptInfo")
    public AjaxResultVo<SysDept> userDeptInfo()
    {
        List<Long> deptIdList = SecurityUtils.getDeptIdList();
        if(deptIdList.isEmpty()) {
            return AjaxResultVo.error("当前用户还未设置单位归属");
        }
        SysDept dept = deptService.getById(deptIdList.get(0));
        if(null == dept) {
            return AjaxResultVo.error("部门查询异常~");
        }

        return AjaxResultVo.success(dept);
    }

    // @Anonymous
    @ApiOperation(value="部门导入", notes="部门导入")
    @Log(title = "部门管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:dept:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String area) throws Exception
    {
        ExcelUtil<SysDeptImportDataDto> util = new ExcelUtil<>(SysDeptImportDataDto.class);
        List<SysDeptImportDataDto> deptList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        // String operName = "admin";
        String message = deptService.importDept(deptList, updateSupport, operName, area);
        return success(message);
    }

    @PreAuthorize("@ss.hasPermi('system:dept:importTemplate')")
    @ApiOperation(value="部门模板导出", notes="部门模板导出")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        deptService.importTemplate(response, "部门导入模板");
    }

}
