package com.rf.psychological.institution.rest;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.dao.vo.SaveInstitutionVO;
import com.rf.psychological.enums.UserRole;
import com.rf.psychological.enums.UserStatus;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.institution.service.InstitutionService;
import com.rf.psychological.scale.service.UserRecordService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.Constant;
import com.rf.psychological.utils.JWTUtil;
import com.rf.psychological.utils.Result;
import com.rf.psychological.dao.dto.InstitutionRecordingDTO;
import com.rf.psychological.dao.dto.InstitutionRecordingUserDTO;
import com.rf.psychological.institution.model.InstitutionEntity;
import com.rf.psychological.scale.dao.model.UserRecordEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/institution")
@Api(tags = "机构模块")
public class InstitutionController extends BaseController {

    @Autowired
    private InstitutionService institutionService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRecordService userRecordService;


    /**
     * 获取机构列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @SafetyProcess
    @GetMapping("/getAllInstitutionList")
    @ApiOperation(value = "根据条件模糊查询机构列表")
    public Result getSubjectListByName(int pageNum, int pageSize, String searchKey) {
        if (pageSize == 0) {
            pageSize = 20;
        }
       // List<InstitutionEntity> allInstitutionByName = this.institutionService.findAllInstitutionByName(pageNum, pageSize, searchKey);
        Page<InstitutionEntity> institutionEntities = this.institutionService.findAllInstitution(pageNum,pageSize,searchKey);
        //long total = institutionEntities.getTotalElements();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", institutionEntities.getContent());
        jsonObject.put("allNum", institutionEntities.getTotalElements());
        return success(jsonObject);
    }

    /**
     * 获取机构用户列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @SafetyProcess
    @GetMapping("/getAllInstitutionUser")
    @ApiOperation(value = "根据条件模糊查询所有机构管理员")
    public Result getAllInstitutionUser(int pageNum, int pageSize, String searchKey) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        Page<UserEntity> userEntities = userService.findUserByPhoneOrInstitutionName(pageNum,pageSize,searchKey);
       // List<InstitutionUserEntity> allByName = institutionUserService.findAllByName(pageNum, pageSize, searchKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("institutionUserList", userEntities.getContent());
        jsonObject.put("allNum", userEntities.getTotalElements());
        return success(jsonObject);
    }

    /**
     * 根据查询某机构下所有机构管理员
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @SafetyProcess
    @GetMapping("/getInAdminByInNo")
    @ApiOperation(value = "根据查询某机构下所有机构管理员")
    public Result getInAdminByInNo(int pageNum, int pageSize, String institutionNo, String searchKey) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        Page<UserEntity> userEntities = userService.findUserByPhoneOrNameInInstitutionNo(pageNum,pageSize,institutionNo,searchKey, UserRole.ADMIN,true);
        //List<InstitutionUserEntity> allByName = institutionUserService.findAllInAdminByInNo(pageNum, pageSize, institutionNo, searchKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("institutionUserList", userEntities.getContent());
        jsonObject.put("allNum", userEntities.getTotalElements());
        return success(jsonObject);
    }

    @SafetyProcess
    @PostMapping("/saveUser")
    @ApiOperation(value = "机构管理员（注：非机构超级管理员）保存")
    public Result institutionSaveUser(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonData = JSONObject.parseObject(data);
        JSONObject jsonInstitutionUserEntity = jsonData.getJSONObject("data");
        UserEntity institutionUserEntity = jsonInstitutionUserEntity.toJavaObject(UserEntity.class);
        log.info("institutionUserEntity--->" + institutionUserEntity);
        if(StringUtils.isEmpty(institutionUserEntity.getPhone()) ||
                StringUtils.isEmpty(institutionUserEntity.getPassword()) ||
                StringUtils.isEmpty(institutionUserEntity.getGender()) ||
                StringUtils.isEmpty(institutionUserEntity.getPetName()) ||
                StringUtils.isEmpty(institutionUserEntity.getBirthday()) ){
            return fail("", "请按要求填写所需信息");
        }

        InstitutionEntity byInstitutionId = this.institutionService.findByInstitutionId(institutionUserEntity.getInstitutionNo());
        if (byInstitutionId == null) {
            return fail("", "机构编号不存在");
        }
        UserEntity byPhone = this.userService.findPhoneAndInstitutionNoAndRoleType( institutionUserEntity.getPhone(),institutionUserEntity.getInstitutionNo(),Constant.QUESTION_TYPE_TWO);
        if (byPhone == null) {
            institutionUserEntity.setInstitutionName(byInstitutionId.getInstitutionName());
            this.userService.save(institutionUserEntity);
            return success();
        } else {
            return fail("", "用户名已注册");
        }

    }

    @SafetyProcess
    @GetMapping("/getUserRecording")
    @ApiOperation(value = "查询机构下所有用户已经做的测试记录")
    public Result getUserRecording(int pageNum, int pageSize, String institutionNo, String type, String searchKey) throws ParseException {
        if (pageSize == 0) {
            pageSize = 20;
        }
        String beginFormat = "", endFormat = "";
        /*log.info("开始时间：" + beginTime);
        log.info("结束时间：" + endTime);
        if (!beginTime.equals("") && !endTime.equals("")) {
            beginTime = beginTime + " " + "00:00:00";
            endTime = endTime + " " + "24:00:00";
            //格式化为数据库的时间样式
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
            Date beginDate = simpleDateFormat1.parse(beginTime);
            Date endDate = simpleDateFormat1.parse(endTime);
            beginFormat = simpleDateFormat2.format(beginDate);
            endFormat = simpleDateFormat2.format(endDate);
        }
        log.info("格式化后为beginFormat:" + beginFormat);
        log.info("格式化后为endFormat:" + endFormat);*/
        int num;
        List<InstitutionRecordingDTO> institutionUserRecordingList = this.userRecordService.getInstitutionUserRecording(pageNum, pageSize, type, institutionNo, searchKey, beginFormat, endFormat);
        num = this.userRecordService.allCountByInstitutionNo(institutionNo, type, searchKey, "", "");
        log.info("institutionUserRecordingList:" + JSONObject.toJSONString(institutionUserRecordingList));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("institutionUserRecordingList", institutionUserRecordingList);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    @SafetyProcess
    @GetMapping("/getTestUser")
    @ApiOperation(value = "查询机构下测试量表下的用户")
    public Result getTestUser(int pageNum, int pageSize, String institutionNo, String name, String searchKey, String beginTime, String endTime, String groupId) throws ParseException {
        if (pageSize == 0) {
            pageSize = 20;
        }
        String beginFormat = "", endFormat = "";
        log.info("开始时间：" + beginTime);
        log.info("结束时间：" + endTime);
        if (!beginTime.equals("") && !endTime.equals("")) {
            beginTime = beginTime + " " + "00:00:00";
            endTime = endTime + " " + "23:59:59";
            //格式化为数据库的时间样式
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
            Date beginDate = simpleDateFormat1.parse(beginTime);
            Date endDate = simpleDateFormat1.parse(endTime);
            beginFormat = simpleDateFormat2.format(beginDate);
            endFormat = simpleDateFormat2.format(endDate);
        }
        log.info("格式化后为beginFormat:" + beginFormat);
        log.info("格式化后为endFormat:" + endFormat);
        int num;
        //添加分组过滤
        List<InstitutionRecordingUserDTO> institutionUserRecordingList = this.userRecordService.getInstitutionRecording(pageNum, pageSize, institutionNo, name, searchKey, beginFormat, endFormat, groupId);
        num = this.userRecordService.allCountInstitutionRecording(institutionNo, name, searchKey, beginFormat, endFormat, groupId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("institutionUserRecordingList", institutionUserRecordingList);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }


    @SafetyProcess
    @Deprecated
    @OperationLogAnnotation
    @PostMapping("/delete")
    @ApiOperation("删除机构用户")
    public Result deleteUser(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        log.info("json:" + json);
        JSONObject jsonData = JSONObject.parseObject(data);
        if (!jsonData.containsKey("phone") || !jsonData.containsKey("institutionNo")) {
            return fail("", "用户名或机构编号不能为空");
        }
        String phone = jsonData.getString("phone");
        String institutionNo = (String) jsonData.get("institutionNo");
        UserEntity institutionUserEntity = new UserEntity();
        //institutionUserEntity = userService.findPhoneAndInstitutionNo( phone,institutionNo);
        if (institutionUserEntity != null) {
            //userService.deleteByPhoneAndInstitutionNo(phone, institutionNo);
            return success();
        } else {
            return fail("", "手机号不存在");
        }
    }

    /**
     * 修改用户状态
     *
     * @return
     */
    @SafetyProcess
@OperationLogAnnotation
    @GetMapping("/udpateStatus")
    @ApiOperation(value = "修改机构用户状态")
    public Result udpateStatus(String phone, String userStatus, String institutionNo) {
        if (phone == null || "".equals(phone) || userStatus == null || "".equals(userStatus) || institutionNo == null || "".equals(institutionNo)) {
            return fail("", "请传入手机号和更改状态和机构编号的字段");
        }
        userService.updateUserStatusByPhone(phone, userStatus, institutionNo);
        return success();
    }

    /**
     * 用户测试记录(根据type查询是量表还是认知任务)
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/findRecording/{phone}/{type}/{institutionNo}")
    @ApiOperation(value = "用户测试记录(根据type查询是量表还是认知任务)")
    public Result mineTest(int pageNum, int pageSize, String beginTime, String endTime, @PathVariable String phone, @PathVariable String institutionNo, @PathVariable String type) throws ParseException {
        if (pageSize == 0) {
            pageSize = 20;
        }
        log.info("开始时间：" + beginTime);
        log.info("结束时间：" + endTime);
        int num;
        List<UserRecordEntity> userRecordEntityList = new ArrayList<UserRecordEntity>();
        if (!beginTime.equals("") && !endTime.equals("")) {
            String beginFormat = "", endFormat = "";
            beginTime = beginTime + " " + "00:00:00";
            endTime = endTime + " " + "23:59:59";
            //格式化为数据库的时间样式
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
            Date beginDate = simpleDateFormat1.parse(beginTime);
            Date endDate = simpleDateFormat1.parse(endTime);
            beginFormat = simpleDateFormat2.format(beginDate);
            endFormat = simpleDateFormat2.format(endDate);
            log.info("格式化后为beginFormat:" + beginFormat);
            log.info("格式化后为endFormat:" + endFormat);
            userRecordEntityList = this.userRecordService.getListByPhoneAndTypeAndTime(pageNum, pageSize, phone, institutionNo, type, beginFormat, endFormat);
            num = this.userRecordService.countByPhoneAndTypeAndTime(phone, type, beginFormat, endFormat, institutionNo);
        }else {
            userRecordEntityList = this.userRecordService.getListByPhoneAndType(pageNum, pageSize, phone, institutionNo, type);
            num = this.userRecordService.countByPhoneAndType(phone, type,institutionNo);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userRecordEntityList", userRecordEntityList);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    /**
     * 根据手机号查询机构管理员信息
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/findInfo")
    @ApiOperation(value = "根据手机号查询机构管理员信息")
    public Result findInstitutionUserInfoByPhone(String phone, String institutionNo) {
        UserEntity byPhone = userService.findPhoneAndInstitutionNoAndRoleType( phone,institutionNo,Constant.DEFAULT_VALUE_ONE);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("institutionUserEntity", byPhone);
        return success(jsonObject);
    }


    @SafetyProcess
    @OperationLogAnnotation
    @GetMapping("/del/{institutionId}")
    @ApiOperation(value = "删除机构")
    public Result mineTest(@PathVariable String institutionId) {

        try {
            this.institutionService.delInstitution(institutionId);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail();
        }
    }


    /**
     * 添加机构信息
     *
     * @param json
     * @return
     * @throws Exception
     */
    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/save")
    @ApiOperation(value = "添加机构管理员信息")
    @Transactional(rollbackFor = Exception.class)
    public Result institutionSave(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONObject.parseObject(data);
        SaveInstitutionVO saveInstitutionVO = jsonObject.toJavaObject(SaveInstitutionVO.class);
        try {
            String institutionName = saveInstitutionVO.getInstitutionName();
            List<InstitutionEntity> institution = institutionService.findByInstitutionName(institutionName);
            if (CollectionUtils.isNotEmpty(institution) ) {
                return fail("", "机构名已存在");
            }
            institutionService.saveInstitutionAndUser(saveInstitutionVO);
            return success("", "保存成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("保存失败");
        }
    }

    @SafetyProcess
    @GetMapping("/updateIsTestNum")
    @ApiOperation(value = "更新测试次数是否有效",notes = "1-->是;0-->否")
    public Result updateIsTestNum(@RequestParam String institutionNo, @RequestParam Integer isTestNum)  {
        if (StringUtils.isEmpty(institutionNo)){
            return fail("机构编号值不能为空");
        }
        if (isTestNum >1 || isTestNum <0){
            return fail("请确认参数是否符合要求");
        }
        try {
            InstitutionEntity entity = institutionService.findByInstitutionId(institutionNo);
            if (entity == null){
                return fail("机构不存在,请确认参数");
            }
            entity.setIsTestNum(isTestNum);
            institutionService.update(entity);
            return success(entity, "保存成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("保存失败");
        }
    }
    @SafetyProcess
    @GetMapping("/updateTestNum")
    @ApiOperation(value = "更新测试次数")
    public Result updateTestNum(@RequestParam String institutionNo, @RequestParam Integer testNum)  {

        if (testNum < 0){
            return fail("测试次数不满足条件");
        }
        if (StringUtils.isEmpty(institutionNo)){
            return fail("机构编号值不能为空");
        }
        try {
            InstitutionEntity entity = institutionService.findByInstitutionId(institutionNo);
            if (entity == null){
                return fail("机构不存在,请确认参数");
            }
            entity.setTestNum(testNum);
            institutionService.update(entity);
            return success(entity, "保存成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("保存失败");
        }
    }

    @SafetyProcess
    @GetMapping("/updateIsRegistrantsNum")
    @ApiOperation(value = "更新最大注册人数是否有效",notes = "1-->是;0-->否")
    public Result updateIsRegistrantsNum(@RequestParam String institutionNo, @RequestParam Integer isRegistrantsNum)  {
        if (StringUtils.isEmpty(institutionNo)){
            return fail("机构编号值不能为空");
        }
        if (isRegistrantsNum >1 || isRegistrantsNum <0){
            return fail("请确认参数是否符合要求");
        }
        try {
            InstitutionEntity entity = institutionService.findByInstitutionId(institutionNo);
            if (entity == null){
                return fail("机构不存在,请确认参数");
            }
            entity.setIsRegistrantsNum(isRegistrantsNum);
            institutionService.update(entity);
            return success(entity, "保存成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("保存失败");
        }
    }


    @SafetyProcess
    @GetMapping("/updateRegistrantsNum")
    @ApiOperation(value = "更新最大注册人数")
    public Result updateRegistrantsNum(@RequestParam String institutionNo, @RequestParam Integer registrantsNum)  {
        if (StringUtils.isEmpty(institutionNo)){
            return fail("机构编号值不能为空");
        }
        try {
            InstitutionEntity entity = institutionService.findByInstitutionId(institutionNo);
            if (entity == null){
                return fail("机构不存在,请确认参数");
            }
            entity.setRegistrantsNum(registrantsNum);
            entity = institutionService.update(entity);
            return success(entity, "保存成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("保存失败");
        }
    }

    @SafetyProcess
    @GetMapping("/newNumber")
    @ApiOperation("获取机构编号")
    public Result newNumber()  {
        try {
           String number =  institutionService.newNumber();
            return success(number);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }




}
