package com.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.platform.entity.Result;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.service.impl.FdkkService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.utils.Base64Converter;
import com.platform.vos.CurrentUserLoginVo;
import com.platform.vos.ReturnDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("token")
public class TokenController extends AbstractController{

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FdkkService fdkkService;


    @Autowired
    private ZhiHouseService zhiHouseService;


    @PostMapping("/renewToken")
    @ResponseBody
    public Result renewToken(@RequestBody Map<String,String> param) {
        String sceneNum = param.get("sceneNum");
        String sceneUrl = param.get("sceneUrl");
        String userName = param.get("userName");
        if(ObjectUtils.isEmpty(userName) || ObjectUtils.isEmpty(sceneNum) || ObjectUtils.isEmpty(sceneUrl)){
            throw new CommonBaseException(ResultCodeEnum.D101,"参数有误！");
        }
        // 判断场景为四维看看或者指房宝
        if(sceneUrl.contains("www.4dkankan.com") || sceneUrl.contains("test.4dkankan.com")){
            CurrentUserLoginVo user = getUser();
            if(ObjectUtils.isEmpty(user.getFdkkUser())){
                throw new CommonBaseException(500, "请绑定四维看看账号！");
            }
            String password = Base64Converter.decode(Base64Converter.subText(user.getFdkkPassword()));
            ResponseEntity<String> responseEntity = fdkkService.login(user.getFdkkUser(), password);
            if(responseEntity.getStatusCode()!= HttpStatus.OK){
                throw new CommonBaseException(500,"请求失败");
            }
            JSONObject result = JSONObject.parseObject(responseEntity.getBody());
            if (result.getInteger("code") != 0) {
                throw new CommonBaseException(ResultCodeEnum.D101, "四维看看账号密码有误，请重新绑定");
            }
            return Result.success("操作成功",result.getJSONObject("data").getString("token"));
        }

        // 生成token
        ReturnDTO result = zhiHouseService.generateSceneEditToken(param.get("token"),userName,sceneNum);
        return Result.success(result.getMessage());
    }
}
