package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.*;
import cn.estsh.i3plus.core.apiservice.util.ExcelUtil;
import cn.estsh.i3plus.core.apiservice.util.FileUtil;
import cn.estsh.i3plus.core.apiservice.util.ZipUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.model.platform.UserDetailModel;
import cn.estsh.i3plus.pojo.platform.bean.*;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSClient;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description : 用户信息 服务
 * @Reference :
 * @Author : wei.peng
 * @Date : 2018-11-08 19:57
 * @Modify :
 **/
@RestController
@Api(description = "系统用户服务")
@RequestMapping(PlatformConstWords.BASE_URL + "/sys-user-info")
public class SysUserInfoController extends CoreBaseController{

    public static final Logger LOGGER = LoggerFactory.getLogger(SysUserInfoController.class);

    @Autowired
    private ISysUserInfoService sysUserInfoService;

    @Autowired
    private ISysDepartmentService departmentService;

    @Autowired
    private ISysPositionService sysPositionService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysFileService sysFileService;

    @PostMapping(value="/insert")
    @ApiOperation(value="添加用户信息",notes="返回内容添加用户信息")
    public ResultBean insertSysUserInfo(SysUserInfo userInfo){
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            checkSysUserInfo(userInfo,false);

            ConvertBean.modelInitialize(userInfo,user);
            userInfo.setUserInfoStatus(CommonEnumUtil.USER_STATUS.ENABLE.getValue());
            userInfo.setUserLoginNum(0);

            sysUserInfoService.checkSysUserInfoOnly(userInfo);

            SysUserInfo info = sysUserInfoService.insertSysUserInfo(userInfo);

            sysUserInfoService.refreshRefUserOrganize(info.getId(), userInfo.getDepartment().getOrganizeId(),user.getUserName());

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(info);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value="/update")
    @ApiOperation(value="修改用户信息",notes="根据用户信息id修改信息")
    public ResultBean updateSysUserInfoById(SysUserInfo userInfo){
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            checkSysUserInfo(userInfo,true);

            //修改初始化
            ConvertBean.modelUpdate(userInfo,user);
            sysUserInfoService.checkSysUserInfoOnly(userInfo);

            sysUserInfoService.updateSysUserInfo(userInfo);

            sysUserInfoService.refreshRefUserOrganize(userInfo.getId(), userInfo.getDepartment().getOrganizeId(),user.getUserName());

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value="/delete/{id}")
    @ApiOperation(value="删除用户信息",notes="根据用户信息id删除信息")
    public ResultBean deleteSysUserInfo(@PathVariable("id") String id){
        try {
            //条件验证
            ValidatorBean.checkNotNull(id,"id为空");

            sysUserInfoService.deleteSysUserInfoById(Long.parseLong(id));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/list")
    @ApiOperation(value="查询所有用户信息",notes="查询所有用户信息")
    public ResultBean findSysUserInfoAll(){
        try{
            List<SysUserInfo> SysUserInfoList = sysUserInfoService.listSysUserInfo();
            return ResultBean.success("操作成功").setResultList(SysUserInfoList)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/query")
    @ApiOperation(value="查询用户信息",notes="复杂查询用户信息带分页")
    public ResultBean querySysUserInfo(SysUserInfo SysUserInfo, Pager pager){
        try{
            ListPager<SysUserInfo> listPager = sysUserInfoService.querySysUserInfo(SysUserInfo, pager);
            return ResultBean.success("操作成功").setListPager(listPager).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/get/{id}")
    @ApiOperation(value="根据id查询用户信息",notes="根据id用户信息")
    public ResultBean getSysUserInfoById(@PathVariable("id") String id){
        try{
            ValidatorBean.checkIsNumber(id, "id 不能为空");

            SysUserInfo userInfo = sysUserInfoService.getSysUserInfoById(Long.parseLong(id));
            ValidatorBean.beginValid(userInfo).notNull("id",userInfo.getId());

            if(userInfo != null){
                return ResultBean.success("操作成功").setResultObject(userInfo).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/batch-delete")
    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除")
    public ResultBean deleteSysUserInfoByIds(String[] ids){
        try{
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的用户信息。")
                        .build();
            }
            sysUserInfoService.deleteSysUserInfoByIds(StringTool.getArrayLong(ids));
            return ResultBean.success("操作成功")
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find-ref-department/{userId}")
    @ApiOperation(value = "查询角色的所有角色权限关系", notes = "查询角色的所有角色权限关系")
    public ResultBean findRefDepartment(@PathVariable("userId") String userId) {
        try {
            ValidatorBean.checkNotNull(userId, "用户 id 不能为空");
            List<SysRefUserDepartment> list = sysUserInfoService.findRefUserDepartmentByUserId(Long.parseLong(userId));
            return ResultBean.success("操作成功")
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/query-ref-department")
    @ApiOperation(value = "查询角色的所有角色权限关系", notes = "查询角色的所有角色权限关系")
    public ResultBean queryRefDepartment(UserDetailModel model) {
        try {
            List<Long> idList = new ArrayList<>();

            List<SysRefUserDepartment> refs = sysUserInfoService.querySysRefUserDepartment(model);
            if(refs != null && refs.size() > 0){
                for (SysRefUserDepartment ref : refs) {
                    idList.add(ref.getUserId());
                }
            }

            List<SysUserInfo> result = sysUserInfoService.querySysUserInfoList(model, idList);

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find-ref-position/{userId}")
    @ApiOperation(value = "查询角色的所有角色权限关系", notes = "查询角色的所有角色权限关系")
    public ResultBean findRefPosition(@PathVariable("userId") String userId) {
        try {
            ValidatorBean.checkNotNull(userId, "用户 id 不能为空");
            List<SysRefUserPosition> list = sysUserInfoService.findSysRefUserPositionByUserId(Long.parseLong(userId));
            return ResultBean.success("操作成功")
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 用户唯一信息校验
     * @param userInfo
     * @param isId  是否检查ID 存在
     */
    private void checkSysUserInfo(SysUserInfo userInfo,boolean isId){

        try{
            //条件验证
            ValidatorBean.beginValid(userInfo)
                    .notNull("name",userInfo.getName())
                    .notNull("userEmpNo",userInfo.getUserEmpNo())
                    .checkNotZero("departmentId",userInfo.getDepartmentId())
//                    .checkNotZero("departmentIdList",userInfo.getDepartmentIdList())
                    .checkNotZero("positionId",userInfo.getPositionId());
            if(isId){
                ValidatorBean.beginValid(userInfo)
                        .notNull("id",userInfo.getId());
            }

            SysDepartment department = departmentService.getSysDepartmentById(userInfo.getDepartmentId());
            if(department == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("主部门信息不存在。")
                        .build();
            }

            SysPosition position = sysPositionService.getSysPositionById(userInfo.getPositionId());
            if(position == null){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("主岗位信息不存在。")
                        .build();
            }

            sysUserInfoService.checkSysUserInfoOnly(userInfo);

            userInfo.setDepartmentNameRdd(department.getName());
            userInfo.setPositionNameRdd(position.getName());
            userInfo.setDepartment(department);
            userInfo.setPosition(position);
        }catch(ImppBusiException busExcep){
            LOGGER.error(busExcep.getErrorMsg() + "：{}",busExcep.getErrorDetail(),busExcep);
        }catch(Exception e){
            LOGGER.error(ImppExceptionEnum.SYSTEM_EXCEPTION.getDescription() + "：{}",e.getMessage(),e);
        }
    }

    @GetMapping(value = "/export")
    @ApiOperation(value = "导出用户信息")
    public ResultBean exportSysUserInfo(SysUserInfo sysUserInfo, String[] colName, int pageSize,boolean isZip) {
        ListPager listPager;
        List result = new ArrayList();
        File zipFile = null;
        File excelDir = null;
        File excelFile;

        try {
            Pager pager = new Pager();
            pager.setCurrentPage(1);
            // 判断是否超过excel最大导出数量设定值
            int maxPageSize = Integer.parseInt(sysConfigService.getSysConfigByCode(PlatformConstWords.EXCEL_EXPORT_MAX_ROW).getConfigValue());
            if (pageSize == 0 || pageSize >= maxPageSize) {
                pager.setPageSize(maxPageSize);
            } else {
                pager.setPageSize(pageSize);
            }

            // 数据校验
            if(colName==null || colName.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.IMPP.getCode())
                        .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode())
                        .setErrorDetail("导出列不能为空")
                        .build();
            }

            excelDir = new File(System.getProperty("java.io.tmpdir") + File.separator + new Date().getTime());
            excelDir.mkdir();
            do {
                listPager = sysUserInfoService.querySysUserInfo(sysUserInfo, pager);
                pager = listPager.getObjectPager();

                // 将excel导出至临时文件夹并上传
                excelFile = new File(excelDir + File.separator + SysUserInfo.class.getSimpleName() + pager.getCurrentPage() + ".xls");
                excelFile.createNewFile();

                ExcelUtil.exportData(excelFile, listPager.getObjectList(), SysUserInfo.class, colName);
                result.add(sysFileService.uploadFile(excelFile));

                pager.setCurrentPage(pager.getCurrentPage() + 1);
            } while (pager.getCurrentPage() <= pager.getTotalPages());

            // 将所有excel文件打包
            if(isZip){
                zipFile = ZipUtil.zipFile(null, excelDir);
                result.add(sysFileService.uploadFile(zipFile));
                ExcelUtil.sendStationLetter(result,getSessionUser().getUser().getId());
                return ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
            } else {
                return ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        } finally {
            // 清理临时文件文件
            if (zipFile != null) {
                FileUtil.deletefile(zipFile.getPath());
            }
            FileUtil.deletefile(excelDir.getPath());
        }
    }

    @GetMapping("/get-col")
    @ApiOperation(value = "获取用户可导出字段")
    public ResultBean getSysUserInfoColName(){
        try {
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(ExcelUtil.getColName(SysUserInfo.class));
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
