package com.ym.mec.collectfee.controller;


import com.ym.mec.collectfee.common.web.BaseController;
import com.ym.mec.collectfee.entity.*;
import com.ym.mec.collectfee.service.ApplyInfoService;
import com.ym.mec.collectfee.service.CourseGroupInfoService;
import com.ym.mec.collectfee.service.OrderService;
import com.ym.mec.collectfee.service.SchoolService;
import com.ym.mec.collectfee.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("user")
//@Api("用户服务")
public class UserController extends BaseController {

    @Autowired
    private ApplyInfoService applyInfoService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CourseGroupInfoService courseGroupInfoService;


    /**
     * 查询用户详情
     *
     * @param phone
     * @param clazzId
     * @return
     */
    @GetMapping("/getUserDetailByPhone")
//    @ApiOperation(value = "根据乐团编号、用户手机，查询用户详情")
//    @ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "用户手机", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "clazzId", value = "乐团编号", required = true, dataType = "Integer")})
    public Object getUserDetailByPhone(String phone, Integer clazzId, Integer cityId) {
        if (StringUtils.isEmpty(phone) || clazzId == null || cityId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }

        ApplyInfo userByPhone = applyInfoService.findUserByPhone(phone, null);

        if (userByPhone == null && applyInfoService.mecUserIsExist(phone)) {
            return failed(Constants.PARAM_EXIST_ERROR_MSG);
        }
        if (userByPhone != null && !userByPhone.getClassId().equals(clazzId)) {//如果改用户存在其他团中
            return failed(Constants.PARAM_EXIST_ERROR_MSG);
        }
        School school = schoolService.get(clazzId);
        if (school != null) {
            if (school.getCityId() == null) {
                school.setCityId(cityId);
                school.setUpdateTime(new Date());
                schoolService.update(school);
            }
            if (userByPhone != null) {
                userByPhone.setPushStatus(school.getStatus());
            }
        }
        return succeed(userByPhone);
    }

    /**
     * 用户报名
     *
     * @param applyInfo
     * @return
     */
//    @ApiOperation(value = "学生报名乐团")
    @PostMapping("/userApply")
    public Object userApply(ApplyInfo applyInfo) {
        if (applyInfo != null) {
            try {
                Date date = new Date();
                applyInfo.setCreateTime(date);
                applyInfo.setUpdateTime(date);
                applyInfoService.insert(applyInfo);
                School school = schoolService.get(applyInfo.getClassId());
                if (school == null) {
                    return failed("乐团数据不存在");
                } else {
                    school.setSchoolId(applyInfo.getSchoolId());
                    school.setUpdateTime(date);
                    schoolService.update(school);
                }
                return succeed(applyInfo.getId());
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof DuplicateKeyException) {
                    return failed("该用户已存在");
                }
                return failed("报名失败");
            }
        }
        return failed(Constants.PARAM_VERIFY_ERROR_MSG);
    }

    /**
     * 根据乐团id获取乐团详情，查询乐团状态也通过该接口
     *
     * @param schoolId
     * @return
     */
//    @ApiOperation(value = "根据乐团编号获取乐团详情，查询乐团状态也通过该接口")
    @PostMapping("/getClassDetail")
//    @ApiImplicitParams({ @ApiImplicitParam(name = "clazzId", value = "乐团编号", required = true, dataType = "Integer"),
//            @ApiImplicitParam(name = "schoolId", value = "学校编号", required = true, dataType = "Integer")})
    public Object getSchoolDetail(Integer schoolId) {
        if (schoolId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        return succeed(orderService.getSchoolDetail(schoolId));
    }

    /**
     * 根据学生编号获取乐团注册页面数据
     *
     * @param stuId
     * @return
     */
//    @ApiOperation(value = "根据学生编号获取乐团注册页面数据")
    @PostMapping("/getUserRegisterViewDetail")
    public Object getUserRegisterViewDetail(Integer stuId) {
        if (stuId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        return succeed(applyInfoService.getUserRegisterViewDetail(stuId));
    }

    /**
     * 推送用户到mec注册
     * @return
     */
    /*@PostMapping("/userRegister")
    public Object userRegister(String phone){
        return succeed(applyInfoService.userRegister(phone));
    }*/

    /**
     * 获取乐团课程组列表
     *
     * @return
     */
    @PostMapping("/getCourses")
//    @ApiOperation(value = "根据乐团编号，获取乐团课程组列表")
//    @ApiImplicitParams({ @ApiImplicitParam(name = "clazzId", value = "乐团编号", required = true, dataType = "Integer")})
    public Object getCourses(Integer clazzId) {
        if (clazzId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        return succeed(courseGroupInfoService.getCourses(clazzId));
    }

    //    @ApiOperation(value = "获取所有乐团列表")
    @PostMapping("/getMusicTeams")
    public Object getMusicTeams(MusicTeamsPageInfo pageInfo) {
        return succeed(schoolService.queryPage(pageInfo));
    }

    //    @ApiOperation(value = "根据乐团编号，获取学员列表")
    @PostMapping("/getMusicTeamStu")
    public Object getMusicTeamStu(StudentsQueryInfo queryInfo) {
        return succeed(applyInfoService.queryUserPage(queryInfo));
    }

    //    @ApiOperation(value = "获取所有分部列表")
    @GetMapping("/getBranches")
    public Object getBranches() {
        return succeed(applyInfoService.getBranches());
    }

    //    @ApiOperation(value = "获取学校详情")
    @GetMapping("/getSchool")
    public Object getSchool(Integer schoolId) {
        if (schoolId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        return succeed(applyInfoService.get(schoolId));
    }

    /**
     * 保存学校列表
     * @return
     */
//    @GetMapping("/saveSeminary")
//    public Object saveSeminary(){
//        applyInfoService.saveSeminary();
//        return succeed();
//    }

    /**
     * 修改乐团信息
     *
     * @return
     */
//    @ApiOperation(value = "修改乐团信息")
    @PostMapping("/updateClass")
    public Object updateClass(School school) {
        school.setUpdateTime(new Date());
        schoolService.update(school);
        return succeed();
    }

    /**
     * 开启乐团缴费功能
     *
     * @return
     */
//    @ApiOperation(value = "开启乐团缴费功能")
    @PostMapping("/openClassPay")
    public Object openClassPay(Integer id, String smsMsg, int type, int isSingle) {//1是线上 2 线下
        if (id == null || (isSingle > 1 || isSingle < 0) || (type == 2 && StringUtils.isEmpty(smsMsg))) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        schoolService.openClassPay(id, smsMsg, type, isSingle);
        return succeed();
    }


    /**
     * 关闭乐团缴费
     *
     * @return
     */
//    @ApiOperation(value = "关闭乐团缴费功能")
    @PostMapping("/closeClassPay")
    public Object closeClassPay(Integer id) {
        if (id == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        School school = schoolService.get(id);
        school.setStatus(5);
        return succeed(schoolService.update(school));
    }


    /**
     * 修改学生信息
     *
     * @return
     */
//    @ApiOperation(value = "修改学生信息")
    @PostMapping("/updateUser")
    @Transactional(rollbackFor = Exception.class)
    public Object updateUser(@ModelAttribute ApplyInfo applyInfo) throws Exception {

        if (applyInfo.getId() == null || applyInfo.getId() <= 0) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }

        if (applyInfo.getStatus() != null && applyInfo.getStatus() != 1) {
            return failed("不能修改报名成功以外的状态");
        }

        ApplyInfo oldApplyInfo = applyInfoService.get(applyInfo.getId());
        if (oldApplyInfo == null) {
            return failed("报名信息不存在，请核对");
        }
        boolean flag = false;

        if (applyInfo.getStatus().equals(1) && !oldApplyInfo.getStatus().equals(1)) {
            flag = true;
        }

        Date date = new Date();
        applyInfo.setUpdateTime(date);
        applyInfoService.update(applyInfo);

        //改成成功，推送mec
        if (flag) {
            ApplyInfo newApplyInfo = applyInfoService.get(applyInfo.getId());
            // 增加报名人数
            CourseGroupInfo courseGroupInfo = courseGroupInfoService.get(newApplyInfo.getCourseId());
            courseGroupInfo.setRegNum(courseGroupInfo.getRegNum() + 1);
            courseGroupInfoService.upByIdAndVersion(courseGroupInfo);
            //推送mec
            applyInfoService.userRegister(newApplyInfo.getPatriarchPhone()); //推送mec
        }
        return succeed("修改成功");
    }

    /**
     * 修改学生信息
     *
     * @return
     */
//    @ApiOperation(value = "批量调剂学员专业")
    @PostMapping("/updateUserSub")
    public Object updateUserSub(String userId, Integer subId, Integer courseId) {
        if (StringUtils.isEmpty(userId) || subId == null || courseId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        applyInfoService.updateUserSub(userId, subId, courseId);
        return succeed("修改成功");
    }

    //    @ApiOperation(value = "学员课程班查询,本接口用于查询指定学员报名的课程班（小课或乐团）列表")
    @PostMapping("/queryUserCourse")
//    @ApiImplicitParams({ @ApiImplicitParam(name = "userId", value = "用户编号", required = true, dataType = "Integer")})
    public Object queryUserCourse(Integer userId) {
        if (userId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        List<Branch> branches = applyInfoService.getBranches();
        MecUser mecUser = applyInfoService.findMecUser(userId);
        Map<String, Object> resultMap = new HashMap<>(2);
        if (branches != null && branches.size() > 0 && mecUser != null) {
            for (Branch branch : branches) {
                if (branch.getBranchId().equals(mecUser.getBranchId())) {
                    resultMap.put("memo", branch.getMemo());
                    break;
                }
            }
        }
        resultMap.put("courses", applyInfoService.queryUserCourse(userId));
        return succeed(resultMap);
    }

    /**
     * 推送学生续费成功的订单数据到mec
     * @return
     */
//    @PostMapping("/pushRenew")
//    public Object pushRenew(RenewBean renewBean){
//        applyInfoService.pushRenew(renewBean);
//        return succeed();
//    }

    /**
     * 查询mec用户信息
     *
     * @return
     */
    @PostMapping("/findMecUser")
    public Object findMecUser(Integer userId) {
        if (userId == null) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        return succeed(applyInfoService.findMecUser(userId));
    }

    @PostMapping("/mecUserIsExist")
    public Object mecUserIsExist(String phone) {
        return succeed(applyInfoService.mecUserIsExist(phone));
    }

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    @GetMapping("/sendSmsCode")
    public Object sendLoginVerifyCode(String mobile, HttpSession session) {
        if (StringUtils.isEmpty(mobile)) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        applyInfoService.sendValidCode(mobile, session);
        return succeed();
    }

    /**
     * 验证短信验证码
     *
     * @param smsCode
     * @return
     */
    @PostMapping("/verifySmsCode")
    public Object verifySmsCode(String mobile, String smsCode, HttpSession session) {
        if (StringUtils.isEmpty(smsCode)) {
            return failed(Constants.PARAM_VERIFY_ERROR_MSG);
        }
        if (applyInfoService.verifySmsCode(mobile, smsCode, session)) {
            return succeed();
        }
        return failed("验证失败");
    }
}
