package org.jeecg.modules.basedata.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdPersonnel;
import org.jeecg.modules.basedata.entity.FdPersonnelTree;
import org.jeecg.modules.basedata.service.IFdPersonnelService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.basedata.service.impl.FdPersonnelServiceImpl;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 人员表
 * @author： jeecg-boot
 * @date： 2019-05-09
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdPersonnel")
@Slf4j
public class FdPersonnelController {
    @Autowired
    private IFdPersonnelService fdPersonnelService;

    @Resource
    private FdPersonnelServiceImpl fdPersonnelServiceimpl;

    @Resource
    private ISysUserRoleService userRoleService;

    /**
     * 分页列表查询
     *
     * @param fdPersonnel
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<FdPersonnel>> queryPageList(FdPersonnel fdPersonnel,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<FdPersonnel>> result = new Result<IPage<FdPersonnel>>();
        QueryWrapper<FdPersonnel> queryWrapper = QueryGenerator.initQueryWrapper(fdPersonnel, req.getParameterMap());
        Page<FdPersonnel> page = new Page<FdPersonnel>(pageNo, pageSize);
        IPage<FdPersonnel> pageList = fdPersonnelService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /***
     * @Title:分页联表查询
            * @Description:TODO
            * @param fdPersonnel, pageNo, pageSize, req]
            * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.basedata.entity.FdPersonnel>>
            * @exception 
            * @author 陈创
            * @date 2019/11/4 16:31
            * @updatehistory:
     *   2019/11/4 16:31 新增
            */
    @GetMapping(value = "/findPagelist")
    public Result<IPage<FdPersonnel>> findPagelist(FdPersonnel fdPersonnel,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<FdPersonnel>> result = new Result<IPage<FdPersonnel>>();
        String code=fdPersonnel.getCode();//人员编码
        String name=fdPersonnel.getName();//人员名称
        String pkDepart=fdPersonnel.getPkDepart();//公司或者部门
        String pkOrg=fdPersonnel.getPkOrg();//公司
        if(StringUtils.isNotBlank(code)){
            fdPersonnel.setCode(null);
        }
        if(StringUtils.isNotBlank(name)){
            fdPersonnel.setName(null);
        }
        if(StringUtils.isNotBlank(pkDepart)){
            fdPersonnel.setPkDepart(null);
        }
        if(StringUtils.isNotBlank(pkOrg)){
            fdPersonnel.setPkOrg(null);
        }
        QueryWrapper<FdPersonnel> queryWrapper = QueryGenerator.initQueryWrapper(fdPersonnel, req.getParameterMap());
        queryWrapper.eq("p.del_flag","0");
        if(StringUtils.isNotBlank(code)){
            queryWrapper.like("p.code",code);
        }
        if(StringUtils.isNotBlank((name))){
            queryWrapper.like("p.name",name);
        }
        if(StringUtils.isNotBlank(pkDepart)){
            queryWrapper.eq("p.pk_depart",pkDepart);
        }
        if(StringUtils.isNotBlank(pkOrg)){
            queryWrapper.eq("p.pk_org",pkOrg);
        }
        queryWrapper.orderByDesc("p.create_time");
        Page<FdPersonnel> page = new Page<FdPersonnel>(pageNo, pageSize);
        IPage<FdPersonnel> pageList = fdPersonnelService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /***
     * @Title:分页联表查询（有权限）
     * @Description:TODO
     * @param fdPersonnel, pageNo, pageSize, req]
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.basedata.entity.FdPersonnel>>
     * @exception
     * @author 陈创
     * @date 2019/11/4 16:31
     * @updatehistory:
     *   2019/11/4 16:31 新增
     */
    @GetMapping(value = "/findPagelist1")
    @RequiresPermissions("url:depart:view")
    public Result<IPage<FdPersonnel>> findPagelist1(FdPersonnel fdPersonnel,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        Result<IPage<FdPersonnel>> result = new Result<IPage<FdPersonnel>>();
        String code=fdPersonnel.getCode();//人员编码
        String name=fdPersonnel.getName();//人员名称
        String pkDepart=fdPersonnel.getPkDepart();//部门
        String pkOrg=fdPersonnel.getPkOrg();//公司
        if(StringUtils.isNotBlank(code)){
            fdPersonnel.setCode(null);
        }
        if(StringUtils.isNotBlank(name)){
            fdPersonnel.setName(null);
        }
        if(StringUtils.isNotBlank(pkDepart)){
            fdPersonnel.setPkDepart(null);
        }
        if(StringUtils.isNotBlank(pkOrg)){
            fdPersonnel.setPkOrg(null);
        }
        QueryWrapper<FdPersonnel> queryWrapper = QueryGenerator.initQueryWrapper(fdPersonnel, req.getParameterMap());
        queryWrapper.eq("p.del_flag","0");
        if(StringUtils.isNotBlank(code)){
            queryWrapper.like("p.code",code);
        }
        if(StringUtils.isNotBlank((name))){
            queryWrapper.like("p.name",name);
        }
        if(StringUtils.isNotBlank(pkDepart)){
            queryWrapper.eq("p.pk_depart",pkDepart);
        }
        if(StringUtils.isNotBlank(pkOrg)){
            queryWrapper.eq("p.pk_org",pkOrg);
        }
        queryWrapper.orderByDesc("p.create_time");
        Page<FdPersonnel> page = new Page<FdPersonnel>(pageNo, pageSize);
        IPage<FdPersonnel> pageList = fdPersonnelService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdPersonnel
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdPersonnel> add(@RequestBody @Valid FdPersonnel fdPersonnel, BindingResult bindingResult) {
        Result<FdPersonnel> result = new Result<FdPersonnel>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()){
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdPersonnel.setEnable("0");
            fdPersonnel.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
            fdPersonnelService.save(fdPersonnel);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败:"+e.getMessage());

        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdPersonnel
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdPersonnel> edit(@RequestBody @Valid FdPersonnel fdPersonnel, BindingResult bindingResult) {
        Result<FdPersonnel> result = new Result<FdPersonnel>();
        FdPersonnel fdPersonnelEntity = fdPersonnelService.getById(fdPersonnel.getId());
        if (fdPersonnelEntity == null) {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()){
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdPersonnelService.updateById(fdPersonnel);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<FdPersonnel> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdPersonnel> result = new Result<FdPersonnel>();
        FdPersonnel fdPersonnel = fdPersonnelService.getById(id);
        if (fdPersonnel == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdPersonnelService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdPersonnel> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdPersonnel> result = new Result<FdPersonnel>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdPersonnelService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdPersonnel> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdPersonnel> result = new Result<FdPersonnel>();
        FdPersonnel fdPersonnel = fdPersonnelService.getById(id);
        if (fdPersonnel == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdPersonnel);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * @Author licc
     * @Description //TODO 查询审批人员信息
     * @Date 10:28 2019/5/27
     * @Param
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.BmPersonnelTree>
     **/
    @GetMapping(value = "/queryApprover")
    public Result<List<FdPersonnelTree>> queryApprover() {
        Result<List<FdPersonnelTree>> result = new Result<List<FdPersonnelTree>>();
        List<FdPersonnel> list = fdPersonnelService.queryApprover();
        fdPersonnelServiceimpl.getRoleByPersonnelList(list);
        List<FdPersonnelTree> treeLists=new ArrayList<FdPersonnelTree>();
        getTreeList(treeLists,list,null);
        findLeaf(treeLists);
        result.setResult(treeLists);
        result.setSuccess(true);
        return result;
    }


    private void getTreeList(List<FdPersonnelTree> treeList, List<FdPersonnel> bmlist, FdPersonnelTree temp) {
        for (FdPersonnel fdPersonnel : bmlist) {
            String tempPid = fdPersonnel.getParentId();
            FdPersonnelTree tree = new FdPersonnelTree(fdPersonnel);
            if(temp == null) {
                if(oConvertUtils.isEmpty(tempPid)){
                    treeList.add(tree);
                }
                if(!tree.getIsLeaf()) {
                    getTreeList(treeList, bmlist, tree);
                }
            }else if(tempPid != null && tempPid.equals(temp.getValue())){
                temp.getChildren().add(tree);
                if(!tree.getIsLeaf()) {
                    getTreeList(treeList, bmlist, tree);
                }
            }
        }
    }

    private void findLeaf(List<FdPersonnelTree> treeList){
        for(FdPersonnelTree bmPersonnelTree : treeList){
            if(bmPersonnelTree.getChildren().isEmpty()){
                bmPersonnelTree.setIsLeaf(true);
            }else{
                findLeaf(bmPersonnelTree.getChildren());
            }
        }
    }


    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<FdPersonnel> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                FdPersonnel fdPersonnel = JSON.parseObject(deString, FdPersonnel.class);
                queryWrapper = QueryGenerator.initQueryWrapper(fdPersonnel, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdPersonnel> pageList = fdPersonnelService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "人员表列表");
        mv.addObject(NormalExcelConstants.CLASS, FdPersonnel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("人员表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FdPersonnel> listFdPersonnels = ExcelImportUtil.importExcel(file.getInputStream(), FdPersonnel.class, params);
                for (FdPersonnel fdPersonnelExcel : listFdPersonnels) {
                    fdPersonnelService.save(fdPersonnelExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdPersonnels.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * @return org.jeecg.common.api.vo.Result<java.util.Map < java.lang.String, java.lang.Object>>
     * @Author gurui
     * @Description //TODO 分页查询所有项目数据
     * @Date 10:07 2019/5/10
     * @Param [bmProject, pageNo, pageSize, req]
     **/
    @GetMapping(value = "/listAllPage")
    public Result<Map<String, Object>> getListOpsition(FdPersonnel fdPersonnel,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        Result<Map<String, Object>> result = new Result<>();
        Map<String, Object> map = Maps.newHashMap();//limit参数
        map.put("fdPersonnel", fdPersonnel);
        map.put("current", pageNo);//当前页
        map.put("size", pageSize);//每页显示
        Map<String, Object> list = null;
        try {
            list = fdPersonnelService.getPageFdPersonnel(map);
            result.setSuccess(true);
            result.setMessage("查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("未查到数据");
        }
        result.setResult(list);
        return result;
    }

    /***
     * @Title:查询部门下的全部人员
            * @Description:TODO
            * @param
            * @return org.jeecg.common.api.vo.Result<java.util.List<java.util.Map<java.lang.Object,java.lang.Object>>>
            * @exception 
            * @author 陈创
            * @date 2019/7/16 12:58
            * @updatehistory:
     *   2019/7/16 12:58 新增
            */
    @GetMapping(value = "/getPersonnelOrDepart")
    public Result<List<Map<Object,Object>>> getPersonnelOrDepart(){
        Result<List<Map<Object,Object>>> result=new Result<>();
        List<Map<Object,Object>> mapList=fdPersonnelService.getPersonnelOrDepart();
        result.setResult(mapList);
        return result;
    }

    // 根据 code查询name
    @RequestMapping(value = "/queryNameByCode", method = RequestMethod.GET)
    public String queryNameByCode(@RequestParam(name="code",required=true)String code) {
        String name = fdPersonnelService.queryNameByCode(code);
        return name;
    }


    /**
     * 查询所有用户所对应的角色信息
     *
     * @return
     */
    @RequestMapping(value = "/queryUserRoleMap", method = RequestMethod.GET)
    public Result<Map<String, String>> queryUserRole() {
        Result<Map<String, String>> result = new Result<>();
        Map<String, String> map = userRoleService.queryUserRole();
        result.setResult(map);
        result.setSuccess(true);
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 修改
    * @Date 2020/8/19 17:11
    * @Param [fdPersonnel, bindingResult]
    * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.basedata.entity.FdPersonnel>
    */
    @PutMapping(value = "/personnelUpdate")
    @NotDuplicate
    public Result<FdPersonnel> personnelUpdate(@RequestBody @Valid FdPersonnel fdPersonnel, BindingResult bindingResult) {
        Result<FdPersonnel> result = new Result<FdPersonnel>();
        FdPersonnel fdPersonnelEntity = fdPersonnelService.getById(fdPersonnel.getId());
        if (fdPersonnelEntity == null) {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()){
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdPersonnelService.personnelUpdate(fdPersonnel);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

}


