package com.supplier.controller;

import com.supplier.model.Supplier;
import com.supplier.service.PersonalServce;
import com.supplier.util.ParsingToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息页面
 */
@RestController
@RequestMapping("personal")
public class PersonalController {

    @Autowired
    private PersonalServce personalServce;

    /**
     * 查询个人信息
     * @param request 获取头信息
     * @return 返回结果
     */
    @GetMapping("getPresonalMessage")
    public Map<String, Object> getPresonalMessage(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        try {
            //获取token
            Map<String, Object> userMap = ParsingToken.tokenParsing(request);
            String code = (String) userMap.get("code");
            Supplier supplier = personalServce.getPresonalMessage(code);
            map.put("msg", "200");
            map.put("data", supplier);
        } catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
        }
        return map;
    }

    /**
     * 修改手机号
     * @param supplier 参数
     * @param request 获取头部信息
     * @return 返回结果
     */
    @PutMapping("updatePhone")
    public Map<String, Object> updatePhone(Supplier supplier,HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        try{
            //获取token
            Map<String, Object> userMap = ParsingToken.tokenParsing(request);
            supplier.setCode((String) userMap.get("code"));
            int count = personalServce.checkCaptcha(supplier);//校验验证码是否正确
            if(count > 0){
                personalServce.updatePhone(supplier);
                map.put("msg", "200");
            } else {
                map.put("errMsg", "手机号或验证码不正确");
                map.put("msg", "300");
            }
        } catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
        }
        return map;
    }

    /**
     * 修改昵称
     * @param supplier 参数
     * @param request 请求头参数
     * @return 返回结果
     */
    @PutMapping("updateName")
    public Map<String, Object> updateName(Supplier supplier,HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        try {
            //获取token
            Map<String, Object> userMap = ParsingToken.tokenParsing(request);
            supplier.setCode((String) userMap.get("code"));
            personalServce.updatePhone(supplier);
            map.put("msg", "200");
        } catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
        }
        return map;
    }
}
