package com.ym.mec.student.controller;

import com.ksyun.ks3.dto.PostObjectFormFields;
import com.ym.mec.thirdparty.entity.UploadSign;
import io.swagger.annotations.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.CloudTeacherOrderDao;
import com.ym.mec.biz.dal.dto.CashAccountDetail;
import com.ym.mec.biz.dal.entity.AppVersionInfo;
import com.ym.mec.biz.dal.entity.CloudTeacherOrder;
import com.ym.mec.biz.dal.entity.MemberRankSetting;
import com.ym.mec.biz.dal.entity.Student;
import com.ym.mec.biz.dal.entity.Subject;
import com.ym.mec.biz.dal.entity.SysConfig;
import com.ym.mec.biz.dal.entity.SysSuggestion;
import com.ym.mec.biz.dal.entity.SysUserBankCard;
import com.ym.mec.biz.service.AppVersionInfoService;
import com.ym.mec.biz.service.ClassGroupService;
import com.ym.mec.biz.service.ImGroupNoticeService;
import com.ym.mec.biz.service.MemberRankPrivilegesService;
import com.ym.mec.biz.service.MemberRankSettingService;
import com.ym.mec.biz.service.OrganizationService;
import com.ym.mec.biz.service.StudentManageService;
import com.ym.mec.biz.service.StudentService;
import com.ym.mec.biz.service.SubjectService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysSuggestionService;
import com.ym.mec.biz.service.SysUserBankCardService;
import com.ym.mec.biz.service.SysUserCashAccountDetailService;
import com.ym.mec.biz.service.SysUserCashAccountService;
import com.ym.mec.biz.service.UploadFileService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.entity.UploadReturnBean;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.http.HttpUtil;
import com.ym.mec.util.upload.UploadUtil;

@Api(tags = "学生管理")
@RestController
public class StudentManageController extends BaseController {

    @Autowired
    private SysSuggestionService suggestionService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private SysUserCashAccountService sysUserCashAccountService;
    @Autowired
    private SysUserCashAccountDetailService sysUserCashAccountDetailService;
    @Autowired
    private ClassGroupService classGroupService;
    @Autowired
    private ImGroupNoticeService imGroupNoticeService;
    @Autowired
    private SysUserBankCardService sysUserBankCardService;
    @Autowired
    private StudentManageService studentManageService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private StudentService studentService;

	@Autowired
	private AppVersionInfoService appVersionInfoService;
    
    @Autowired
    private MemberRankSettingService memberRankSettingService;
    
    @Autowired
    private MemberRankPrivilegesService memberRankPrivilegesService;
    
    @Autowired
    private SysConfigService sysConfigService;
    
    @Autowired
    private CloudTeacherOrderDao cloudTeacherOrderDao;

    private final static Logger LOGGER = LoggerFactory.getLogger(StudentManageController.class);

    @Autowired
    private UploadFileService uploadFileService;

    @PostMapping(value = "uploadFile")
    public Object uploadFile(@ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile file) {
        try {
            if (file != null && StringUtils.isNotBlank(file.getOriginalFilename())) {
                UploadReturnBean bean = uploadFileService.uploadFile(file.getInputStream(), UploadUtil.getExtension(file.getOriginalFilename()));
                if (bean.isStatus()) {
                    return succeed(bean);
                }
                return failed(bean.getMessage());
            }
        } catch (Exception e) {
            LOGGER.error("上传失败", e);
        }
        return failed("上传失败");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "bucketName", dataType = "String", value = "为空时默认使用daya"),
            @ApiImplicitParam(name = "fileName", dataType = "String", value = "要上传的文件名称,不包含路径信息"),
            @ApiImplicitParam(name = "postData", dataType = "Map", value = "1.如果使用js sdk上传的时候设置了ACL请设置,例\"acl\":\"public-read\"值要与SDK中一致,没有则删除该项</br>" +
                    "2.提供js sdk中的key值,例\"key\":\"20150115/中文/${filename}\""),
            @ApiImplicitParam(name = "unknowValueField", dataType = "List", value = "对于用户无法确定表单值的放在unknownValueField中(比如有的上传控件会添加一些表单项,但表单项的值可能是随机的)"),
    })
    @ApiOperation(value = "获取上传文件签名", notes = "{\n" +
            "    \"bucketName\":\"\",\n" +
            "    \"filename\":\"test.png\",\n" +
            "    \"postData\":{\n" +
            "        \"acl\":\"public-read\",\n" +
            "        \"key\":\"20150115/中文/${filename}\"\n" +
            "    },\n" +
            "    \"unknowValueField\":[\"test\"]\n" +
            "}")
    @PostMapping("/getUploadSign")
    public HttpResponseResult<PostObjectFormFields> getUploadSign(@RequestBody UploadSign uploadSign) {
        return succeed(uploadFileService.getUploadSign(uploadSign));
    }

    @ApiOperation(value = "新增建议")
    @PostMapping("suggestion/add")
    public Object add(SysSuggestion sysSuggestion) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            return failed("请重新登录");
        }
    	sysSuggestion.setClientType("STUDENT");
        sysSuggestion.setUserId(sysUser.getId().longValue());
        if(StringUtils.isEmpty(sysSuggestion.getMobileNo())){
            sysSuggestion.setMobileNo(sysUser.getPhone());
        }
        suggestionService.insert(sysSuggestion);
        return succeed();
    }


    @ApiOperation(value = "获取学员基本信息")
    @GetMapping("student/queryUserInfo")
	public Object queryUserInfo(String platform) {
		SysUser user = sysUserFeignService.queryUserInfo();
		if (user == null) {
			return failed(HttpStatus.FORBIDDEN, "请登录");
		}
		Student student = studentService.get(user.getId());
		student.setId(user.getId());
		student.setUsername(user.getUsername());
		student.setAvatar(user.getAvatar());
		student.setPhone(user.getPhone());
		student.setCurrentClass(user.getCurrentClass());
		student.setCurrentGrade(user.getCurrentGrade());
		student.setBirthdate(user.getBirthdate());
		student.setGender(user.getGender());
		student.setRealName(user.getRealName());
		student.setIdCardNo(user.getIdCardNo());
		student.setImToken(user.getImToken());
		student.setOrganId(user.getOrganId());
		
		if(StringUtils.isNotBlank(student.getSubjectIdList())){
			List<Subject> subjectList = subjectService.findBySubjectByIdList(student.getSubjectIdList());
			student.setSubjectNames(subjectList.stream().map(t -> t.getName()).collect(Collectors.joining(",")));
		}
		
		if(StringUtils.isNotBlank(student.getExtSubjectIds())){
			List<Subject> subjectList = subjectService.findBySubjectByIdList(student.getExtSubjectIds());
			
			student.setExtSjectNamesMap(subjectList.stream().collect(Collectors.toMap(Subject :: getId, Subject :: getName)));
		}

		Map<String, Object> datas = new HashMap<String, Object>();
		datas.put("student", student);
		
        List<CloudTeacherOrder> dataList = cloudTeacherOrderDao.queryByUserIdAndStatus(user.getId(),1);
        if(dataList != null && dataList.size() > 0){
        	datas.put("isExistPendingMember", true);
        }else{
        	datas.put("isExistPendingMember", false);
        }

		if (StringUtils.isNotBlank(platform)) {
			AppVersionInfo appVersionInfo = null;
			List<AppVersionInfo> list = appVersionInfoService.queryNewestByPlatform(platform);
			if (list.size() > 0) {
				appVersionInfo = list.get(0);
			}
			datas.put("appVersionInfo", appVersionInfo);
		}

		// 查询权限
		if (student.getMemberRankSettingId() == null || student.getMemberRankSettingId() == 0) {
			List<MemberRankSetting> memberRankSettingList = memberRankSettingService.queryListByIsDefault(true);
			if (memberRankSettingList != null && memberRankSettingList.size() > 0) {
				datas.put("userPrivileges", memberRankPrivilegesService.queryByMemberRankId(memberRankSettingList.get(0).getId()));
			}
		} else {
			datas.put("userPrivileges", memberRankPrivilegesService.queryByMemberRankId(student.getMemberRankSettingId()));
		}
		SysConfig sysConfig = sysConfigService.findByParamName(SysConfigService.HOMEWORK_OPEN_FLAG);
		if (sysConfig == null) {
			datas.put("homeworkOpenFlag", 0);
		} else {
			datas.put("homeworkOpenFlag", Integer.parseInt(sysConfig.getParanValue()));
		}
        // 获取会员等级图标
        MemberRankSetting memberRankSetting = memberRankSettingService.get(student.getMemberRankSettingId());
        if (memberRankSetting != null) {
            student.setMemberRankImg(memberRankSetting.getIcon());
        }
        //是否是试用会员
		if(student.getExperienceMemberRankSettingId() == null){
            datas.put("isExperience", 0);
        }else {
            int i = DateUtil.daysBetween(student.getExperienceMembershipEndTime(),student.getMembershipEndTime());
            if(i > 0){
                datas.put("isExperience", 0);
            }else {
                datas.put("isExperience", 1);
                if (memberRankSetting != null) {
                    student.setMemberRankImg(memberRankSetting.getExperienceIcon());
                }
            }
        }
		return succeed(datas);
	}

    @ApiOperation(value = "根据群编号，获取群组所有成员基本信息")
    @GetMapping("classGroup/findGroupUsers")
    public Object findGroupUsers(Integer groupId,String search) {
        if (groupId == null) {
            return failed("参数校验错误");
        }
        return succeed(classGroupService.findGroupUsers(groupId,search));
    }

    @ApiOperation(value = "分页查询群公告列表")
    @GetMapping(value = "/queryNoticePage")
    public Object queryNoticePage(QueryInfo queryInfo){
        return succeed(imGroupNoticeService.queryPage(queryInfo));
    }

    @ApiOperation(value = "根据群编号，获取用户群名片")
    @GetMapping("classGroup/getUserInfoWithUserId")
    public Object getUserInfoWithUserId(Integer groupId,Integer userId) {
        if (groupId == null || userId == null) {
            return failed("参数校验错误");
        }
        return succeed(classGroupService.getUserInfoWithUserId(groupId,userId));
    }

    @ApiOperation(value = "获取用户账户信息")
    @GetMapping("userCashAccount/get")
    public Object add() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            return failed("请重新登录");
        }
        return succeed(sysUserCashAccountService.get(sysUser.getId()));
    }

    @ApiOperation(value = "分页查询用户交易明细")
    @GetMapping("userCashAccountDetail/queryPage")
    public Object queryPage(CashAccountDetail queryInfo) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if(user == null || user.getId() != null){
            return failed("请重新登录");
        }
        queryInfo.setUserId(user.getId());
        return succeed(sysUserCashAccountDetailService.queryPage(queryInfo));
    }

    @ApiOperation(value = "新增银行卡信息")
    @PostMapping("userBankCard/add")
    public Object add(SysUserBankCard sysUserBankCard) {
        if(sysUserBankCard == null){
            return failed("参数校验异常");
        }
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null || sysUser.getId() == null){
            return failed("获取用户失败");
        }
        sysUserBankCard.setUserId(sysUser.getId());
        return succeed(sysUserBankCardService.add(sysUserBankCard));
    }

    @ApiOperation(value = "删除银行卡信息")
    @PostMapping("userBankCard/del")
    public Object del(Long id) {
        if(id == null){
            return failed("参数校验失败");
        }
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null || sysUser.getId() == null){
            return failed("获取用户信息失败");
        }
        sysUserBankCardService.del(id,sysUser.getId());
        return succeed();
    }

    @ApiOperation(value = "分页查询银行卡信息列表")
    @GetMapping("userBankCard/queryPage")
    public Object queryPage() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null || sysUser.getId() == null){
            return failed("获取用户失败");
        }
        return succeed(sysUserBankCardService.findByUser(sysUser.getId()));
    }

    @ApiOperation(value = "修改用户")
    @PostMapping(value = "user/update", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Object update(SysUser sysUser) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user != null) {
            Date date = new Date();
            sysUser.setId(user.getId());
            sysUser.setUpdateTime(date);
            studentManageService.updateUser(sysUser);
            return succeed();
        }
        return failed("获取用户失败");
    }

    /**
     * 学员注册激活比例列表
     * @return
     */
    @GetMapping(value = "studentManage/queryStudentPer/{tenantId}")
    public Object queryStudentPer(@ApiParam(value = "机构Id", required = true) @PathVariable("tenantId") Integer tenantId) {
        return succeed(studentManageService.queryStudentPer(tenantId));
    }


    @ApiOperation(value = "获取子集科目列表")
    @GetMapping("subject/findSubSubjects")
    public Object findSubSubjects(){
        return succeed(subjectService.findSubSubjects(null));
    }

    @ApiOperation(value = "获取用户所在分部的年级列表）")
    @GetMapping("studentManage/getGradeList")
    public HttpResponseResult<Map<Integer,String>> getGradeList() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            return failed("请重新登录");
        }
        return succeed(organizationService.getGradeList(sysUser.getOrganId()));
    }

    @ApiOperation(value = "url短链接")
    @PostMapping("shortURL")
    public HttpResponseResult<String> shortURL(String orginURL) {
        return succeed(HttpUtil.getSortUrl(orginURL));
    }
}
