package com.zd.system.controller;

import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.redis.service.RedisService;
import com.zd.common.security.annotation.InnerAuth;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.system.api.domain.*;
import com.zd.system.api.model.LoginUser;
import com.zd.system.domain.SysPost;
import com.zd.system.service.*;
import com.zd.system.service.impl.TeacherServiceImpl;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户学生信息
 *
 * @author zd
 */
@RestController
@RequestMapping("/user/teacher")
@Api(tags = {"教职工管理"})
public class SysTeacherController extends BaseController {
    @Autowired
    private ISysTeacherService sysTeacherService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private ISysPermissionService permissionService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private TeacherServiceImpl teacherService;
    @Autowired
    RedisService redisService;

    private static String USER_TYPE = "11";
    /**
     * 获取教职工列表 "system:user_teacher:list"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.LIST)
    @GetMapping("/list")
    public TableDataInfo<TeacherListVO> list(SysUser user) {
        user.setUserType(USER_TYPE);
        startPage();
        List<SysUser> list = sysTeacherService.selectUserList(user);
        //组合管理实验室数据
        teacherService.queryTeacherSuBCount(list);
        return getDataTable(list);
    }

    /**
     * 获取教职工下拉框列表
     */
    @PostMapping("/option")
    public AjaxResult option(@RequestBody SysUser user) {
        user.setUserType(USER_TYPE);
        List<Map<String, Object>> list = sysTeacherService.selectOption(user);
        return AjaxResult.success(list);
    }

    //"system:user_teacher:export"
    @Log(title = "教职工导出", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.EXPORT)
    @PostMapping({"/export","/export/{ids}"})
    public void export(HttpServletResponse response, SysUser user,@PathVariable(value = "ids",required = false) Long... ids) throws IOException {
        if(ids!=null&&ids.length>0)
        {
            user = new SysUser();
            user.setIds(Arrays.asList(ids));
        }
        user.setUserType(USER_TYPE);
        List<SysUser> list = sysTeacherService.selectUserList(user);
        teacherService.queryTeacherSuBCount(list);

        List<SysUserTeaCherByExport> teacherList = new ArrayList<>();
        for (SysUser sysUser : list) {
            teacherList.add(new SysUserTeaCherByExport(sysUser));
        }
        ExcelUtil<SysUserTeaCherByExport> util = new ExcelUtil<SysUserTeaCherByExport>(SysUserTeaCherByExport.class);
        //本地日期,不包括时分秒
        LocalDate nowDate = LocalDate.now();
        util.exportExcel(response, teacherList, "用户数据", null, "教职工信息导出表"+nowDate);
    }

    //"system:user_teacher:import"
    @Log(title = "教职工管理", businessType = BusinessType.IMPORT)
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, SysUserTeaCherByExcel sysUserTeaCherByExcel) throws Exception {
        ExcelUtil<SysUserTeaCherByExcel> util = new ExcelUtil<SysUserTeaCherByExcel>(SysUserTeaCherByExcel.class);
        List<SysUserTeaCherByExcel> userList = util.importExcel(file.getInputStream(),true);
        String operName = SecurityUtils.getUsername();
        List<SysUserTeaCherByExcel> sysUserTeaCherByExcels = sysTeacherService.importUserByTeaCher(userList, updateSupport, operName, sysUserTeaCherByExcel);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("totalNum",userList.size());
        resultMap.put("successNum",userList.size()- sysUserTeaCherByExcels.size());
        resultMap.put("failureNum", sysUserTeaCherByExcels.size());
        resultMap.put("downFile", sysUserTeaCherByExcels.size()>0?true:false);
        if(sysUserTeaCherByExcels.size()>0){
            redisService.setCacheObject("exportByTeaCher"+SecurityUtils.getUserId(), sysUserTeaCherByExcels, 1L, TimeUnit.HOURS);
        }
        return AjaxResult.success(resultMap);
    }

    @Log(title = "教职工管理导出错误数据", businessType = BusinessType.IMPORT)
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.IMPORT)
    @PostMapping("/importErrorData")
    public void importErrorData(HttpServletResponse response) throws Exception {
        String tips = "导入注意事项：（未按如下要求填写，会导致数据不能正常导入）\n" +
                "1、请不要修改此表格的格式，包括插入删除行和列、合并拆分单元格等。请在表格里面逐行录入数据。一次最多导入5000条数据信息。\n" +
                "2、需要填写的单元格字段规则校验，请按照提示输入。\n" +
                "3、请不要随意复制单元格，这样会破坏字段规则校验。\n" +
                "4、带有星号（*）的红色字段为必填项。\n" +
                "5、请注意：工号、联系电话是唯一的，不能重复，不可多条；工号限制最大7个字符，联系电话限制最大13个字符。\n" +
                "6、请注意：出生日期填写为：YYYY-MM-DD。\n" +
                "7、所在部门需填写系统中已录入的部门名称，否则无法正常导入。";
        ExcelUtil<SysUserTeaCherByExcel> util = new ExcelUtil<SysUserTeaCherByExcel>(SysUserTeaCherByExcel.class);
        List<SysUserTeaCherByExcel> sysUserTeaCherByExcels = redisService.getCacheObject("exportByTeaCher"+SecurityUtils.getUserId());
        if(sysUserTeaCherByExcels.size()>0){
            util.exportExcel(response, sysUserTeaCherByExcels, "未导入的用户数据", tips, "教职工信息批量导入模板");
        }
    }

    @PostMapping("/importTemplate")
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.EXCELTEMPLATE)
    public void importTemplate(HttpServletResponse response) throws IOException {
        String tips = "导入注意事项：（未按如下要求填写，会导致数据不能正常导入）\n" +
                "1、请不要修改此表格的格式，包括插入删除行和列、合并拆分单元格等。请在表格里面逐行录入数据。一次最多导入5000条数据信息。\n" +
                "2、需要填写的单元格字段规则校验，请按照提示输入。\n" +
                "3、请不要随意复制单元格，这样会破坏字段规则校验。\n" +
                "4、带有星号（*）的红色字段为必填项。\n" +
                "5、请注意：工号、联系电话是唯一的，不能重复，不可多条；工号限制最大7个字符，联系电话限制最大13个字符。\n" +
                "6、请注意：出生日期填写为：YYYY-MM-DD。\n" +
                "7、所在部门需填写系统中已录入的部门名称，否则无法正常导入。";
        ExcelUtil<SysUserTeaCherByExcel> util = new ExcelUtil<SysUserTeaCherByExcel>(SysUserTeaCherByExcel.class);
//        util.importTemplateExcel(response, "用户数据");
        util.exportExcel(response, null, "教职工信息批量导入模板", tips, "教职工信息批量导入模板");
    }

    /**
     * 新增用户 "system:user_teacher:add"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.ADD)
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        user.setUserType(USER_TYPE);
        if (UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setPassword(SecurityUtils.encryptPassword(password));
        return toAjax(sysTeacherService.insertUser(user));
    }


    /**
     * 修改用户 "system:user_teacher:edit"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.EDIT)
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        sysTeacherService.checkUserAllowed(user);
        user.setUserType(USER_TYPE);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysTeacherService.update(user));
    }

    /**
     * 修改用户 "system:user_teacher:edit"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.EDIT)
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editNatureLinkage")
    public AjaxResult editNatureLinkage(@Validated @RequestBody SysUser user) {
        sysTeacherService.checkUserAllowed(user);
        user.setUserType(USER_TYPE);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysTeacherService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        if(StringUtils.isNotEmpty(user.getNature()) && user.getNature().equals("1")){
            user.setStatus("1");
        }
        return toAjax(sysTeacherService.update(user));
    }


    /**
     * 删除用户 "system:user_teacher:remove"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.REMOVE)
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return AjaxResult.error("当前用户不能删除");
        }
        return toAjax(sysTeacherService.deleteUserByIds(userIds));
    }

    /**
     * 修改用户所属部门 "system:user_teacher:edit"   （老师专用）
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.EDIT)
    @Log(title = "修改用户所属部门", businessType = BusinessType.UPDATE)
    @PutMapping("/editUserByDept")
    public AjaxResult editUserByDept(@RequestBody List<SysUser> userList) {
        return toAjax(sysTeacherService.editUserByDept(userList));
    }


    /**
     * 重置密码 "system:user_teacher:edit"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.RESETPWD)
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        user.setUserType(USER_TYPE);
        sysTeacherService.checkUserAllowed(user);
        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysTeacherService.resetPwd(user));
    }


    /**
     * 根据用户编号获取详细信息 "system:user_teacher:query"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_USER_TEACHER+ PerFun.QUERY)
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll(new SysPost()));
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = sysTeacherService.selectUserById(userId);
            if(StringUtils.isNotNull(sysUser)){
                if(StringUtils.isNotEmpty(sysUser.getCardNum())){
                    try{
                        long num = Long.parseLong(sysUser.getCardNum(),16);
                        sysUser.setCardNum(num+"");
                    }catch (Exception e){
                        logger.info("卡号解密失败===="+sysUser.getCardNum());
                    }
                }
            }

            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }
}
