package yangtz.cs.liu.wechat.controller.userInfo;

import com.core.utils.UploadToServer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.util.UserInfoUtil;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.student.SchoolStudentParent;
import yangtz.cs.liu.campus.service.student.ISchoolStudentParentService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static com.ruoyi.common.utils.SecurityUtils.matchesPassword;
import static yangtz.cs.liu.wechat.constant.LoginTypeConstant.TEACHER_LOGIN;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/wx/userInfo")
public class WxUserInfoController extends BaseController {

    @Autowired
    private ISchoolStudentService schoolStudentService;

    @Autowired
    private ISchoolStudentParentService schoolStudentParentService;

    @Autowired
    private ISchoolStudentService studentService;

    @Autowired
    private UserInfoUtil userInfoUtil;

    @Autowired
    private ISchoolTeacherService schoolTeacherService;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${ruoyi.serverAddress}")
    private String serverAddress;

    @Value("${server.port}")
    private String port;

    /****************************************家长端****************************************/

    /**
     * 学生信息展示
     *
     * @return
     */
    @GetMapping("/studentInfo/{studentId}")
    public AjaxResult studentInfo(@PathVariable("studentId") Long studentId) {
        return AjaxResult.success(schoolStudentParentService.getUserInfo(studentId));
    }



    /**
     * 新增监护人
     *
     * @param schoolStudentParent
     * @return
     */
    @PostMapping("/add/{studentId}")
    public AjaxResult add(@PathVariable("studentId") Long studentId, @RequestBody @Validated SchoolStudentParent schoolStudentParent) {
        return toAjax(schoolStudentParentService.addParent(studentId, schoolStudentParent));
    }



    /**
     * 修改
     *
     * @param schoolStudentParent
     * @return
     */
    @PutMapping("/edit/{studentId}")
    public AjaxResult edit(@PathVariable("studentId") Long studentId, @RequestBody @Validated SchoolStudentParent schoolStudentParent) {
        if (StringUtils.isNull(schoolStudentParent.getId()) || StringUtils.isNull(schoolStudentParent.getUserId())) {
            AjaxResult.error("父母信息id未传");
        }
        SchoolStudentParent parent = schoolStudentParentService.getById(schoolStudentParent.getId());
        schoolStudentParent.setRelationship(parent.getRelationship());
        return toAjax(schoolStudentParentService.updateParent(studentId, schoolStudentParent));
    }


    /****************************************教职工端****************************************/


    /**
     * 查询用户（老师）信息
     *
     * @return
     */
    @GetMapping("/teacherInfo/{teacherId}")
    public AjaxResult teacherInfo(@PathVariable("teacherId") Long teacherId) {
        return AjaxResult.success(schoolTeacherService.getById(teacherId));
    }


    /**
     * 教职工修改密码
     *
     * @param newPassword 新密码
     * @param oldPassword 旧密码
     * @return
     */
    @PostMapping("/editPassword")
    public AjaxResult editPassword(String newPassword, String oldPassword,String phonenumber) {
        SysUser sysUser = new SysUser();
        sysUser.setUserLoginType(TEACHER_LOGIN);
        sysUser.setPhonenumber(phonenumber);
        SysUser user = sysUserService.getUser(sysUser);
        if (!matchesPassword(oldPassword,user.getPassword())){
            throw new ServiceException("原密码错误，请检查");
        }
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        return toAjax(sysUserService.updateUser(user));
    }

    /**
     * 用户修改头像(上传头像)
     */
    @PutMapping("/editAvatar")
    public AjaxResult editAvatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            SysUser user = sysUserService.selectUserById(userInfoUtil.getMpLoginUser().getUserId());
            //String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            Map map = UploadToServer.uploadAvatar(serverAddress,file);
            String avatar = map.get("url").toString();
            if (sysUserService.updateUserAvatar(user.getUserName(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                return ajax;
            }
        }
        return AjaxResult.error("图片修改异常");
    }

    /**
     * 家长端用户修改头像(上传头像)
     */
    @PutMapping("/editStudentAvatar")
    public AjaxResult editStudentAvatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
//            SysUser user = sysUserService.selectUserById(userInfoUtil.getMpLoginUser().getUserId());
            //String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            Map map = UploadToServer.uploadAvatar(serverAddress,file);
            String avatar = map.get("url").toString();
//            if (studentService.updateStudentAvatar(user.getStudentId(),avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                return ajax;
//            }
        }
        return AjaxResult.error("图片修改异常");
    }

    /**
     * 上传故障图片
     */
    @PutMapping("/editFailure")
    public AjaxResult editFailure(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            Map map = UploadToServer.uploadFailure(serverAddress,file);
            String failure = map.get("url").toString();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", failure);
            return ajax;
        }
        return AjaxResult.error("图片上传异常");
    }


    /**
     * 修改个人信息(家长端)
     * @param schoolStudent
     * @return
     */
    @PutMapping("/changePrepare")
    public AjaxResult changePrepare(@RequestBody SchoolStudent schoolStudent){
        schoolStudent.setId(userInfoUtil.getStudentId());
        return AjaxResult.success(schoolStudentService.updateById(schoolStudent));
    }

}
