package com.changfa.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.changfa.base.BaseController;
import com.changfa.constants.ApiResult;
import com.changfa.custom.ExCondition;
import com.changfa.dto.QueryUserDto;
import com.changfa.dto.SaveUserDto;
import com.changfa.entity.TUser;
import com.changfa.enums.StatusEnum;
import com.changfa.service.ITRoleService;
import com.changfa.service.ITUserService;
import com.changfa.utils.BCrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping(value = "/sysUser",method = RequestMethod.POST)
@Api(tags = "用户编辑Api")
public class SysUserController extends BaseController {

    @Autowired
    private ITUserService userService;
    @Autowired
    private ITRoleService roleService;
   /* @Autowired
    private IDictService dictService;*/

    @Value("${iot.default.password}")
    private String defaultPwd;


    @ApiOperation("用户分页列表")
    @RequestMapping("/selectUserPage")
    @ApiResponses(@ApiResponse(code=200,message = "请求成功",response = TUser.class))

    public ApiResult selectUserPage(@RequestBody QueryUserDto queryUserDto){
        try{
            ExCondition exCondition = ExCondition.create();
            exCondition.like("userName",queryUserDto.getUserName());
            exCondition.like("account",queryUserDto.getAccount());
            exCondition.eq("b.role_id",queryUserDto.getRoleId());
            exCondition.eq("a.logic_del",0);
            exCondition.eq("a.is_show",1);
            Page page = new Page(queryUserDto.getPageNum(),queryUserDto.getPageSize());
            return ApiResult.success(this.userService.selectUserPage(page,exCondition));
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }



    @ApiOperation("新增或修改用户")
    @RequestMapping("/saveOrUpdateUser")
    public ApiResult saveOrUpdateUser(@RequestBody @Valid SaveUserDto user, @ApiIgnore Errors errors){
        try{
            if(errors.hasErrors()){
                return ApiResult.error(errors.getFieldError().getDefaultMessage());
            }
            ExCondition wrapper = new ExCondition();
            wrapper.eq("account",user.getAccount());
            wrapper.ne("id",user.getUserId());
            if(userService.count(wrapper) > 0){
                return ApiResult.error(StatusEnum.USER_INFO_IS_EXISTS);
            }
            wrapper = new ExCondition();
            wrapper.eq("id",user.getRoleId());
            if(roleService.count(wrapper) == 0){
                return ApiResult.error(StatusEnum.ROLE_NO_EXISTS);
            }
            /*List<Map<String,Object>> list =  dictService.listByCache(DictConstants.DEFAULT_PASSWORD);
            if (!ObjectUtils.isEmpty(list)) {
                defaultPwd  = list.get(0).getOrDefault("value",defaultPwd).toString();
            }*/
            user.setPassword(defaultPwd);
            if(userService.saveUser(user)){
                return ApiResult.success();
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }


    @ApiOperation("重置密码")
    @RequestMapping("/resetPwd")
    public ApiResult resetPwd(@RequestParam("userId")Integer userId){
        try{
           // List<Map<String,Object>> list =  dictService.listByCache(DictConstants.DEFAULT_PASSWORD);
            TUser user = new TUser();
            String salt = BCrypt.gensalt();
          /*  if (!ObjectUtils.isEmpty(list)) {
                defaultPwd  = list.get(0).getOrDefault("value",defaultPwd).toString();
            }*/
            user.setPassword(BCrypt.hashpw(defaultPwd,salt));
            user.setSalt(salt);
            user.setId(userId);
            if(this.userService.updateById(user)){
                return ApiResult.success();
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }


    @ApiOperation("删除用户")
    @RequestMapping("/deleteUserById")
    public ApiResult deleteUser(@RequestParam("userId")Integer userId){
        try{
           if(this.userService.deleteUser(userId)){
               return ApiResult.success();
           }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }


    @ApiOperation("用户修改密码")
    @RequestMapping("/updatePwd")
    public ApiResult updatePwd(@RequestParam("originPwd")String originPwd,@RequestParam("pwd")String pwd){
        try{
            TUser user = currentUser();
            user = this.userService.getById(user.getId());
            String salt = user.getSalt();
            if(!BCrypt.checkpw(originPwd,user.getPassword())){
                return ApiResult.error(StatusEnum.PASSWORD_ERROR);
            }
            user.setPassword(BCrypt.hashpw(pwd,salt));
            user.setSalt(salt);
            if(this.userService.updateById(user)){
                return ApiResult.success();
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }



    @ApiOperation("导入excel")
    @RequestMapping("/importUserExcel")
    public ApiResult importUserExcel(@RequestParam("files")MultipartFile files){
        try{
           return  this.userService.importExcel(files, true);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.FAIL);
    }


    @ApiOperation("下载用户模板")
    @RequestMapping("/downUserExcel")
    public void downUserExcel(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        // 对响应进行重新编码
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户模板", "utf-8");
        response.addHeader("Cache-Control", "no-cache");
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("static/excelTemplate/user.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLSX).withTemplate(templatePathName).build();
        excelWriter.finish();
    }
}
