package com.liquidnet.service.adam.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.dto.AdamThirdPartParam;
import com.liquidnet.service.adam.dto.AdamUserInfoParam;
import com.liquidnet.service.adam.dto.vo.AdamThirdPartInfoVo;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.adam.service.IAdamThirdPartyService;
import com.liquidnet.service.adam.service.IAdamUserInfoService;
import com.liquidnet.service.adam.service.IAdamUserService;
import com.liquidnet.service.base.ResponseDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@ApiSupport(order = 10020)
@Api(tags = "用户中心")
@Slf4j
@RestController
@RequestMapping("user")
public class AdamUserController {
    @Autowired
    Environment environment;
    @Autowired
    IAdamUserService adamUserService;
    @Autowired
    IAdamUserInfoService adamUserInfoService;
    @Autowired
    IAdamThirdPartyService adamThirdPartyService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "个人资料编辑")
    @PostMapping(value = {"edit"})
    public ResponseDto<AdamUserInfoVo> edit(@RequestBody AdamUserInfoParam parameter) {
        // TODO: 2021/5/10
        log.info("parameter:{}", JsonUtils.toJson(parameter));
        String currentUid = CurrentUtil.getCurrentUid();

        AdamUserInfoVo editUserInfoVo = adamUserService.queryByUid(currentUid);
        editUserInfoVo.setAvatar(parameter.getAvatar());
        editUserInfoVo.setBackground(parameter.getBackground());
        editUserInfoVo.setNickName(parameter.getNickName());
        editUserInfoVo.setSex(parameter.getSex());
        editUserInfoVo.setBirthday(parameter.getBirthday());
        editUserInfoVo.setArea(parameter.getArea());
        editUserInfoVo.setSignature(parameter.getSignature());
        editUserInfoVo.setTagMe(parameter.getTagMe());
        editUserInfoVo.setIsComplete(1);
        editUserInfoVo.setUpdatedAt(DateUtil.format(LocalDateTime.now(), DateUtil.Formatter.yyyyMMddHHmmss));

        adamUserInfoService.edit(editUserInfoVo);

        return ResponseDto.success(editUserInfoVo);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "手机号修改")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "mobile", value = "新手机号"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "code", value = "验证码"),
    })
    @PostMapping(value = {"edit/mobile"})
    public ResponseDto<Object> editMobile(@RequestParam String mobile, @RequestParam String code) {
        // TODO: 2021/5/10
        log.info("mobile:{},code:{}", mobile, code);

        if (!this.checkSmsCode(mobile, code)) return ResponseDto.failure("验证码无效");

        String uid = CurrentUtil.getCurrentUid();

        adamUserInfoService.editMobile(uid, mobile);

        return ResponseDto.success();
    }

//    @ApiOperationSupport(order = 3)
//    @ApiOperation(value = "密码修改")
//    @ApiImplicitParams({
//            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "mobile", value = "手机号"),
//            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "password", value = "密码"),
//            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "code", value = "验证码"),
//    })
//    @PostMapping(value = {"edit/pwd"})
//    public ResponseDto<Object> editPwd(@RequestParam String mobile, @RequestParam String password, @RequestParam String code) {
//        log.info("mobile:{},password:{},code:{}", mobile, password, code);
//
//        // TODO: 2021/5/10
//
//
//        return ResponseDto.success();
//    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "绑定第三方账号")
    @PostMapping(value = {"tpa/bind"})
    public ResponseDto<List<AdamThirdPartInfoVo>> bindTpa(@RequestBody AdamThirdPartParam parameter) {
        // TODO: 2021/5/10
        log.info("login by tpa:{}", JsonUtils.toJson(parameter));
        String currentUid = CurrentUtil.getCurrentUid();

        String existUid = adamUserService.queryUidByRedis(parameter.getOpenId(), parameter.getPlatform());
        if (StringUtils.isNotEmpty(existUid)) {
            if (existUid.equals(currentUid)) {
                return ResponseDto.success(adamThirdPartyService.queryByUid(currentUid));
            }
            Boolean force = parameter.getForce();
            if (null != force && force) {// 强制解绑，并重新绑定当前账号
                return ResponseDto.success(adamUserService.bindTpaForce(currentUid, existUid, parameter));
            }
            return ResponseDto.failure("第三方账号已绑定其它手机号");
        }
        return ResponseDto.success(adamUserService.bindTpa(currentUid, parameter));
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "解绑第三方账号")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "platform", value = "平台类型", allowableValues = "WEIBO,WECHAT,QQ"),
    })
    @PostMapping(value = {"tpa/unbind/{platform}"})
    public ResponseDto<List<AdamThirdPartInfoVo>> unbindTpa(@PathVariable String platform) {
        // TODO: 2021/5/10
        String currentUid = CurrentUtil.getCurrentUid();
        log.info("unbind tpa.platform:{},uid:{}", platform, currentUid);

        return ResponseDto.success(adamUserService.unBindTpa(currentUid, platform));
    }

    /* ---------------------------- Internal Method ---------------------------- */

    private boolean checkSmsCode(String mobile, String code) {
        if ("dev".equals(environment.getProperty("spring.profiles.active")) && "111111".equals(code)) {
            return true;
        }

        LinkedMultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.add("mobile", mobile);
        paramsMap.add("code", code);
        LinkedMultiValueMap<String, String> headersMap = new LinkedMultiValueMap<>();
        headersMap.add("token", null);

        try {
            // TODO: 2021/5/12
            String respStr = HttpUtil.get("https://service.zhengzai.tv/smsValidation", paramsMap, headersMap);
            log.info("###PHP.API.RESP:{}", respStr);

            Map respMap = JsonUtils.fromJson(respStr, Map.class);

            return StringUtils.equalsIgnoreCase("OK", (String) respMap.get("message"));
        } catch (Exception e) {
            log.error("验证码验证异常[mobile:{},code:{}]", mobile, code, e);
            return false;
        }
    }
}
