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.*;
import com.liquidnet.service.adam.service.IAdamRealNameService;
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.ErrorMapping;
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.util.*;

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

    @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.getNowTime());

        adamUserInfoService.edit(editUserInfoVo);

        return ResponseDto.success(editUserInfoVo);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "音乐风格")
    @GetMapping(value = {"tag/ms"})
    public ResponseDto<List<AdamTagParentVo>> getMsTag() {
        List<AdamTagParentVo> tagMsVoList = new ArrayList<>();
        tagMsVoList.add(AdamTagParentVo.getNew().setVal("MMS01").setDesc("民歌").setTagVos(Arrays.asList(
                AdamTagVo.getNew().setVal("MMS0101").setDesc("A"),
                AdamTagVo.getNew().setVal("MMS0102").setDesc("B")
        )));
        tagMsVoList.add(AdamTagParentVo.getNew().setVal("MMS02").setDesc("house").setTagVos(Arrays.asList(
                AdamTagVo.getNew().setVal("MMS0201").setDesc("C"),
                AdamTagVo.getNew().setVal("MMS0202").setDesc("D")
        )));
        tagMsVoList.add(AdamTagParentVo.getNew().setVal("MMS03").setDesc("R&B").setTagVos(Arrays.asList(
                AdamTagVo.getNew().setVal("MMS0301").setDesc("E"),
                AdamTagVo.getNew().setVal("MMS0302").setDesc("F")
        )));
        return ResponseDto.success(tagMsVoList);
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "性别列表")
    @GetMapping(value = {"tag/sex"})
    public ResponseDto<List<AdamTagVo>> getSexTag() {
        List<AdamTagVo> tagSexVoList = new ArrayList<>();
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS00").setDesc("其他性别"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS01").setDesc("男性"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS02").setDesc("女性"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS03").setDesc("跨性别女性"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS04").setDesc("跨性别男性"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS05").setDesc("双性别者"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS06").setDesc("性别模糊"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS07").setDesc("性别流动"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS08").setDesc("无性别者"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS09").setDesc("不确定性别"));
        tagSexVoList.add(AdamTagVo.getNew().setVal("MS10").setDesc("不在乎性别"));
        return ResponseDto.success(tagSexVoList);
    }

    @ApiOperationSupport(order = 4)
    @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(ErrorMapping.get("10002"));

        String uid = CurrentUtil.getCurrentUid();

        adamUserInfoService.editMobile(uid, mobile);

        return ResponseDto.success();
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "实名认证")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "name", value = "姓名"),
            @ApiImplicitParam(type = "form", required = true, dataType = "String", name = "idCard", value = "证件号"),
    })
    @PostMapping(value = {"identity"})
    public ResponseDto<AdamRealInfoVo> identity(@RequestParam String name, @RequestParam String idCard) {
        // TODO: 2021/5/10
        log.info("name:{},idCard:{}", name, idCard);

        AdamRealInfoVo infoVo = adamUserService.identity(CurrentUtil.getCurrentUid(), name, idCard);

        return ResponseDto.success(infoVo);
    }

//    @ApiOperationSupport(order = 6)
//    @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 = 7)
    @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(ErrorMapping.get("10007"));
        }

        // 判断该用户是否已绑定同类型第三方账号
        AdamThirdPartInfoVo bindThirdPartVo = adamThirdPartyService.queryByUidAndPlatform(currentUid, parameter.getPlatform());
        if (null != bindThirdPartVo) return ResponseDto.failure(ErrorMapping.get("10008"));

        adamUserService.bindTpa(currentUid, parameter);
        return ResponseDto.success(adamThirdPartyService.queryByUid(currentUid));
    }

    @ApiOperationSupport(order = 8)
    @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 (Arrays.asList("dev", "test").contains(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;
        }
    }
}
