package org.shunt.contorller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.lang.Assert;
import com.admin.common.utils.StringUtils;
import com.admin.common.utils.file.FileUploadUtils;
import com.admin.major.domain.MajorInfo;
import com.admin.major.service.IMajorInfoService;
import lombok.extern.slf4j.Slf4j;
import org.shunt.aop.ApiAuth;
import org.shunt.aop.ApiAuthIgnore;
import org.shunt.aop.ShuntApi;
import org.shunt.cache.ApplyCacheUtils;
import org.shunt.common.FileTypeEnum;
import org.shunt.common.JWTAuthUtil;
import org.shunt.common.XmoseRequest;
import org.shunt.common.XmoseResponse;
import org.shunt.contorller.request.*;
import org.shunt.contorller.response.ApplyResultVO;
import org.shunt.contorller.response.AuthorDTO;
import org.shunt.contorller.response.BannerVO;
import org.shunt.contorller.response.MajorApplyViewVO;
import org.shunt.contorller.response.ScheduleVO;
import org.shunt.contorller.response.ShuntQuotaVO;
import org.shunt.contorller.response.SpecialApplyViewVO;
import org.shunt.contorller.response.StudentScoreVO;
import org.shunt.contorller.response.UserInfoVO;
import org.shunt.service.ShuntService;
import org.shunt.service.WechatService;
import org.shunt.service.bean.WechatUserDetailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import com.admin.common.config.AdminConfig;
import com.admin.major.domain.StudentInfo;
import com.admin.major.service.IStudentInfoService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

@ShuntApi
@Api("专业分流")
@RestController
@RequestMapping("/shunt")
@Slf4j
public class ShuntController {

    @Autowired
    private ShuntService service;
    @Autowired
    private WechatService wechatService;

	@Autowired
    private AdminConfig adminConfig;

	@Autowired
    @Qualifier("studentInfoServiceImpl")
    private IStudentInfoService studentInfoService;

    @Autowired
    @Qualifier("majorInfoServiceImpl")
    private IMajorInfoService majorInfoService;


	@PostMapping("/banner")
    @ApiOperation(value = "首页-Banner接口", notes="首页-Banner接口")
    @ApiAuth
    public @ResponseBody XmoseResponse<List<BannerVO>> bannerList(@RequestBody XmoseRequest<?> request) {
        List<BannerVO> bannerVOList = new ArrayList<BannerVO>();
        bannerVOList.add(BannerVO.builder().bannerTitle("默认学院图").bannerImageUrl("https://slmajor.gdsdxy.edu.cn/pic/banner.jpg").jumUrl("").jumType(0).build());
//        bannerVOList.add(BannerVO.builder().bannerTitle("特别申请").bannerImageUrl("http://106.52.229.24/pic/banner.jpg").jumUrl("https://lanhuapp.com/web/#/item/project/stage?tid=b324be1d-148e-4b89-8ac4-62e7e4db2bc5&pid=bc5ad6c1-3c5e-4c3a-b176-1659377fe375").jumType(2).build());
//        bannerVOList.add(BannerVO.builder().bannerTitle("特别申请查询").bannerImageUrl("http://106.52.229.24/pic/banner.jpg").jumUrl("https://lanhuapp.com/web/#/item/project/stage?tid=b324be1d-148e-4b89-8ac4-62e7e4db2bc5&pid=bc5ad6c1-3c5e-4c3a-b176-1659377fe375").build());

        return XmoseResponse.success(bannerVOList);
    }

	@PostMapping("/schedule")
    @ApiOperation(value = "首页-日程安排列表", notes="首页-日程安排列表")
    @ApiAuth
    public @ResponseBody XmoseResponse<List<ScheduleVO>> scheduleList(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.getSchedule(authorDTO));
    }


    @PostMapping("/quota")
    @ApiOperation(value = "专业分流-专流名额", notes="专业分流-专流名额")
    @ApiAuth
    public @ResponseBody XmoseResponse<ShuntQuotaVO> getMajorQuota(@RequestBody XmoseRequest<?> request) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.getMajorQuota(authorDTO));
    }

    @PostMapping("/score")
    @ApiAuth
    @ApiOperation(value = "专业分流-本人成绩", notes="专业分流-本人成绩")
    public @ResponseBody XmoseResponse<StudentScoreVO> getScore(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.getStudentScore(authorDTO));
    }

    @GetMapping("/major-info")
    @ApiOperation(value = "专业详情", notes="专业详情")
    @ApiAuth
    public @ResponseBody XmoseResponse<List<MajorInfo>> majorInfo(/*@RequestBody XmoseRequest<?> request*/) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
        List<MajorInfo> majorInfos = majorInfoService.selectMajorInfoList(new MajorInfo() {{
            setYear(String.valueOf(authorDTO.getYearId()));
            setCollegeId(Long.valueOf(authorDTO.getCollegeId()));
        }});
        return XmoseResponse.success(majorInfos);
    }

    @PostMapping("/special-apply-view")
    @ApiOperation(value = "首页-特别申请浏览", notes="首页-特别申请浏览")
    @ApiAuth
    public @ResponseBody XmoseResponse<SpecialApplyViewVO>viewSpecialApply(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.viewSpecialApply(authorDTO));
    }

    @PostMapping("/special-apply-result")
    @ApiAuth
    @ApiOperation(value = "首页-特别申请结果查询", notes="首页-特别申请结果查询")
    public @ResponseBody XmoseResponse<ApplyResultVO>getSpecialApplyResult(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.getSpecialApplyResult(authorDTO));
    }

    @PostMapping("/special-apply")
    @ApiAuth
    @ApiOperation(value = "首页-特别申请", notes="首页-特别申请")
    public @ResponseBody XmoseResponse<?> specialApply(@RequestBody XmoseRequest<SpecialApplyRequest> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	request.getData().setStudentId(authorDTO.getUserId());
    	request.getData().setYearId(authorDTO.getYearId());
    	request.getData().setCollegeId(authorDTO.getCollegeId());
    	service.specialApply(request.getData(), authorDTO);
    	return XmoseResponse.success();
    }

    @PostMapping("/special-apply-submit")
    @ApiAuth
    @ApiOperation(value = "首页-特别申请提交", notes="首页-特别申请提交")
    public @ResponseBody XmoseResponse<?> specialApplySubmit(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	service.specialApplySubmit(authorDTO);
    	return XmoseResponse.success();
    }

    @PostMapping("/major-apply-view")
    @ApiAuth
    @ApiOperation(value = "专业分流-志愿填报浏览", notes="专业分流-志愿填报浏览")
    public @ResponseBody XmoseResponse<MajorApplyViewVO>viewMajorApply(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.viewMajorApply(authorDTO));
    }
    @PostMapping("/major-apply-result")
    @ApiAuth
    @ApiOperation(value = "首页-专业分流申请结果查询", notes="首页-专业分流申请结果查询")
    public @ResponseBody XmoseResponse<ApplyResultVO>getMajorApplyResult(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.getMajorApplyResult(authorDTO));
    }

    @PostMapping("/major-apply")
    @ApiAuth
    @ApiOperation(value = "专业分流-分流申请", notes="专业分流-分流申请")
    public @ResponseBody XmoseResponse<?> majorApply(@RequestBody XmoseRequest<MajorApplyRequest> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	request.getData().setStudentId(authorDTO.getUserId());
    	request.getData().setYearId(authorDTO.getYearId());
    	request.getData().setCollegeId(authorDTO.getCollegeId());
    	service.majorApply(request.getData());
       return XmoseResponse.success();
    }


    @PostMapping("/major-apply-submit")
    @ApiAuth
    @ApiOperation(value = "专业分流-提交", notes="专业分流-提交")
    public @ResponseBody XmoseResponse<?> majorApplySubmit(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	service.majorApplySubmit(authorDTO);
    	return XmoseResponse.success();
    }

    @PostMapping("/apply-result")
    @ApiAuth
    @ApiOperation(value = "首页-进度查询", notes="首页-进度查询")
    public @ResponseBody XmoseResponse<ApplyResultVO> getApplyResult(@RequestBody XmoseRequest<?> request) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
        return XmoseResponse.success(service.getApplyResult(authorDTO));
    }

    @PostMapping("/upload")
    @ApiAuth
    @ApiOperation(value = "上传文件", notes="上传文件")
    public XmoseResponse<?> upload(XmoseRequest<?> request, @RequestParam("fileType") FileTypeEnum fileType, @RequestParam("file") MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = AdminConfig.getProfile() + fileType.getPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            return XmoseResponse.success(new HashMap<String,String>(){{
                put("filePath", adminConfig.getFileRequestPath() + fileName);
            }});
        } catch (Exception e) {
            e.printStackTrace();
            return XmoseResponse.fail(XmoseResponse.CODE_INTERNEL,"上传文件失败");
        }
    }


    @PostMapping("/login")
    @ApiOperation(value = "企微登录", notes="企微登录")
    @ApiAuthIgnore
    public @ResponseBody XmoseResponse<Map<String, Object>> login(@RequestBody XmoseRequest<LoginRequest> request) {
        LoginRequest loginRequest = request.getData();

        String openId = null;
//        loginRequest.setAppId("ww5bf897f5ac93d406");
        loginRequest.setAppId("wx135bad1e23d17274");

        log.info("login {}", loginRequest);
        if (loginRequest.getCode() != null && loginRequest.getCode().startsWith("_")) {
            openId = loginRequest.getCode().substring(1);
        }else {
            WechatUserDetailInfo wechatUserDetailInfo = wechatService.getWechatUserInfo(loginRequest);
            log.info("login detail {}", wechatUserDetailInfo);
//            openId = wechatUserDetailInfo.getOpenId();
            openId = wechatUserDetailInfo.getUserid();
        }

        if (StringUtils.isBlank( openId)){
            return XmoseResponse.fail(XmoseResponse.CODE_UNSUPPORTED, "没有系统访问权限");
        }

        StudentInfo studentInfoParam = new StudentInfo();
        studentInfoParam.setOpenId(openId);
        StudentInfo studentInfo = studentInfoService.selectStudentInfoList(studentInfoParam)
                .stream()
                .findFirst()
                .orElseThrow(() -> new RuntimeException("内部异常"));

        String jwt = JWTAuthUtil.createJWT(studentInfo);
        String finalOpenId = openId;
        HashMap<String, Object> result = new HashMap<String, Object>() {{
            put("token", jwt);
            put("userId", finalOpenId);
        }};
        return XmoseResponse.success(result);
    }


    @PostMapping("/userinfo")
    @ApiAuth
    @ApiOperation(value = "用户-查询用户信息", notes="用户-查询用户信息")
    public @ResponseBody XmoseResponse<UserInfoVO> getUserInfo(@RequestBody XmoseRequest<?> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	return XmoseResponse.success(service.getUserInfo(authorDTO));
    }
    @PostMapping("/set-avatar")
    @ApiAuth
    @ApiOperation(value = "用户-设置头像", notes="用户-设置头像")
    public @ResponseBody XmoseResponse<UserInfoVO> setAvatar(@RequestBody XmoseRequest<AvatarSetRequest> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	request.getData().setStudentId(authorDTO.getUserId());
    	service.setAvatar(request.getData());
    	return XmoseResponse.success();
    }

    @PostMapping("/set-email")
    @ApiAuth
    @ApiOperation(value = "用户-设置邮箱", notes="用户-设置邮箱")
    public @ResponseBody XmoseResponse<UserInfoVO> setEmail(@RequestBody XmoseRequest<EmailSetRequest> request) {
    	AuthorDTO authorDTO = JWTAuthUtil.getAuth();
    	request.getData().setStudentId(authorDTO.getUserId());
    	service.setEmail(request.getData());
    	return XmoseResponse.success();
    }

    @PostMapping("/course-apply")
    @ApiAuth
    @ApiOperation(value = "课程申请", notes="课程申请")
    public @ResponseBody XmoseResponse<?> courseApply(@RequestBody XmoseRequest<CourseApplyRequest> request) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
        service.saveCourseApply(request.getData(),authorDTO);
        return XmoseResponse.success();
    }

    @PostMapping("/course-apply-submit")
    @ApiAuth
    @ApiOperation(value = "课程申请", notes="课程申请")
    public @ResponseBody XmoseResponse<?> courseApplySubmit(@RequestBody XmoseRequest<CourseApplyRequest> request) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
        service.courseApplySubmit(request.getData(),authorDTO);
        return XmoseResponse.success();
    }

    @PostMapping("/course-result")
    @ApiAuth
    @ApiOperation(value = "课程申请结果", notes="课程申请结果")
    public @ResponseBody XmoseResponse<?> courseApplyResult(@RequestBody XmoseRequest<MajorApplyRequest> request) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
        service.courseApplyResult(request.getData(),authorDTO);
        return XmoseResponse.success();
    }

    @PostMapping("/proposal-apply")
    @ApiAuth
    @ApiOperation(value = "提交建议", notes="提交建议")
    public @ResponseBody XmoseResponse<?> proposalApply(@RequestBody XmoseRequest<ProposalRequest> request) {
        AuthorDTO authorDTO = JWTAuthUtil.getAuth();
        request.getData().setUserId(authorDTO.getUserId());
        service.proposalApply(request.getData());
        return XmoseResponse.success();
    }


}
