package cn.chnmuseum.party.web.controller;

import cn.chnmuseum.party.auth.SHA256PasswordEncryptionService;
import cn.chnmuseum.party.auth.SecureRandomSaltService;
import cn.chnmuseum.party.auth.util.AESUtils;
import cn.chnmuseum.party.common.enums.AuditOperationEnum;
import cn.chnmuseum.party.common.log.MethodLog;
import cn.chnmuseum.party.common.log.OperModule;
import cn.chnmuseum.party.common.log.OperType;
import cn.chnmuseum.party.common.util.DateUtil80;
import cn.chnmuseum.party.model.Role;
import cn.chnmuseum.party.model.TUser;
import cn.chnmuseum.party.service.RoleService;
import cn.chnmuseum.party.service.impl.TUserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.chnmuseum.party.web.controller.base.BaseController;
import cn.chnmuseum.party.model.TInteraction;
import cn.chnmuseum.party.service.TInteractionService;
import cn.chnmuseum.party.common.enums.AuditStatusEnum;
import cn.chnmuseum.party.common.validator.groups.Add;
import cn.chnmuseum.party.common.validator.groups.Update;
import cn.chnmuseum.party.common.vo.GenericPageParam;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * 看板互动 前端控制器
 * </pre>
 *
 * @author Danny Lee
 * @since 2021-03-23
 */
@Slf4j
@RestController
@RequestMapping("/interaction")
@Api(tags = {"看板互动操作接口"})
public class TInteractionController extends BaseController {

    @Resource
    private TInteractionService tInteractionService;

    @Resource
    private TUserServiceImpl userService;

    @Resource
    private RoleService roleService;


    @PostMapping("/add")
    @RequiresAuthentication  //@RequiresPermissions("/interaction/add")
    @ApiOperation(value = "添加看板互动", notes = "添加看板互动")
    @MethodLog(operModule = OperModule.INTERACTIVE, operType = OperType.ADD)
    public Map<String, Object> saveTInteraction(TInteraction tInteraction) {
        TUser user = getcurUser();
        // 保存业务节点信息
        boolean result = false;
        try {
            Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
            // 验证互动审核员账号
            if (StringUtils.isBlank(tInteraction.getName()) || StringUtils.isBlank(tInteraction.getPassword())) {
                resultMap.put("resultCode", "400");
                resultMap.put("message", "互动管理员账号或密码不能为空");
                return resultMap;
            }
            // 只能填写当前操作的互动审核员账号
            if (!tInteraction.getName().equals(user.getUserName())) {
                resultMap.put("resultCode", "400");
                resultMap.put("message", "请填写当前登录用户的账号和密码");
                return resultMap;
            }
            TUser tUser = userService.selectByUsername(tInteraction.getName());
            if (tUser == null) {
                resultMap.put("resultCode", "400");
                resultMap.put("message", "用户名不正确!");
                return resultMap;
            }
            if (AuditOperationEnum.DISABLE.name().equals(tUser.getStatus())) {
                resultMap.put("resultCode", "400");
                resultMap.put("message", "此帐号已禁用,请联系管理员!");
                return resultMap;
            }
            if (tUser.getPermanent() != null && !tUser.getPermanent()) {
                if (user.getEffectiveDate() != null && user.getEffectiveDate().isAfter(LocalDate.now()) || user.getExiredDate() != null && user.getExiredDate().isBefore(LocalDate.now())) {
                    resultMap.put("resultCode", "400");
                    resultMap.put("message", "此帐号已失效,请联系管理员!");
                    return resultMap;
                }
            }
            //密码解密
            String s = AESUtils.aesDecrypt(tInteraction.getPassword());
            byte[] salt = tUser.getPasswordSalt();
            String s1 = new String(SHA256PasswordEncryptionService.createPasswordHash(s, salt));
            if (!s1.equals(new String(tUser.getPasswordHash()))) {
                resultMap.put("resultCode", "400");
                resultMap.put("message", "密码不正确!");
                return resultMap;
            }
            List<Role> roles = roleService.selectRoleByUserId(tUser.getId());
            List<String> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
            if (!roleIds.contains("17")) {
                resultMap.put("resultCode", "400");
                resultMap.put("message", "所填写账号非互动审核员!");
                return resultMap;
            }
            tInteraction.setUserId(user.getId());
            tInteraction.setCreateTime(LocalDateTime.now());
            result = tInteractionService.save(tInteraction);
            // 返回操作结果
            if (result) {
                return getSuccessResult();
            } else {
                // 保存失败
                return getFailResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }

    @PutMapping("/update")
    @RequiresAuthentication  //@RequiresPermissions("/interaction/update")
    @ApiOperation(value = "修改看板互动信息", notes = "修改看板互动信息")
    @MethodLog(operModule = OperModule.INTERACTIVE, operType = OperType.UPDATE)
    public Map<String, Object> updateTInteraction(TInteraction tInteraction) {
        boolean flag = false;
        try {
            flag = tInteractionService.updateById(tInteraction);
            if (!flag) {
                return getFailResult();
            }
            return getSuccessResult();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getFailResult();
    }


    @DeleteMapping("/delete")
    @RequiresAuthentication  //@RequiresPermissions("/interaction/delete")
    @ApiOperation(value = "根据ID删除看板互动", notes = "根据ID删除看板互动")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "标识ID", paramType = "query", dataType = "String")
    })
    @MethodLog(operModule = OperModule.INTERACTIVE, operType = OperType.DELETE)
    public Map<String, Object> deleteTInteraction(String id) {
        boolean result = tInteractionService.removeById(id);
        if (result) {
            return getSuccessResult();
        }
        return getFailResult();
    }


    @PostMapping("/getList")
    @RequiresAuthentication  //@RequiresPermissions("/interaction/getList")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "orgId", value = "机构id", paramType = "query", dataType = "String")
    })
    @ApiOperation(value = "获取看板互动列表", notes = "获取看板互动列表")
    @MethodLog(operModule = OperModule.INTERACTIVE, operType = OperType.SELECT)
    public Map<String, Object> getTInteractionPageList(String orgId) {
        Page<TInteraction> list = null;
        try {
            list = tInteractionService.selectPageList(getPage(), orgId);
            return getResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }


    @ApiOperation(value = "获取看板互动详情", notes = "获取看板互动详情")
    @GetMapping("/getById")
    @RequiresAuthentication  //@RequiresPermissions("/interaction/getById")
    @MethodLog(operModule = OperModule.INTERACTIVE, operType = OperType.SELECT)
    public Map<String, Object> getById(String id) {
        TInteraction tInteraction = null;
        try {
            tInteraction = tInteractionService.getById(id);
            return getResult(tInteraction);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFailResult();
    }


//	@ApiImplicitParams(value = {
//			@ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
//			@ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
//			@ApiImplicitParam(name = "nameOrCode", value = "名称或编码", paramType = "query", dataType = "String"),
//			@ApiImplicitParam(name = "startDate", value = "创建时间-开始", paramType = "query", dataType = "String"),
//			@ApiImplicitParam(name = "endDate", value = "创建时间-结束", paramType = "query", dataType = "String")
//	})
//    @PostMapping("/getPageList")
//		@RequiresAuthentication  //@RequiresPermissions("/interaction/getPageList")
//		@ApiOperation(value = "获取看板互动分页列表", notes = "获取看板互动分页列表")
//    public Map<String, Object> getTInteractionPageList(GenericPageParam genericPageParam) {
//		LambdaQueryWrapper<TInteraction> queryWrapper = new LambdaQueryWrapper<>();
//		// 对名称或编码模糊查询
//		if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
//			queryWrapper.like(TInteraction::getUsername, genericPageParam.getNameOrCode());
//		}
//		// 根据创建时间区间检索
//		if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
//			queryWrapper.ge(TInteraction::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
//				.le(TInteraction::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
//		}
//		// 设置排序规则
//		queryWrapper.orderByDesc(TInteraction::getCreateTime);
//		Page<TInteraction> page = this.tInteractionService.page(getPage(), queryWrapper);
//		for (TInteraction tInteraction : page.getRecords()) {
//
//		}
//		return getResult(page);
//    }


}