package com.xxfc.platform.universal.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.MQServiceBiZ;
import com.xxfc.platform.universal.entity.IdInformation;
import com.xxfc.platform.universal.service.CertificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 实名认证
 */
@RestController
@RequestMapping("certif")
@Slf4j
public class CertificationController   {



    @Autowired
    private CertificationService certificationService;


    @Autowired
    private UserFeign userFeign;

    @Qualifier("applicationTaskExecutor")
    @Autowired
    private TaskExecutor executor;

    @Autowired
    private MQServiceBiZ mqServiceBiZ;


    private ExecutorService executorService = Executors.newCachedThreadPool();

    /**
     * 实名认证
     * @param idInformation
     * @param request
     * @return
     */
    @PostMapping("/app/certificate")
    public ObjectRestResponse  certificate(@RequestBody IdInformation idInformation, HttpServletRequest request) {
        if (idInformation == null) {
            ObjectRestResponse.createFailedResult(ResultCode.INCOMPLETE_DATA,"无法识别,请重新上传");
        }
        String token = request.getHeader("Authorization");
        log.info("------token======"+token);
        if (StringUtils.isEmpty(token)) {
            ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_NULL_CODE,"无法识别,请重新上传");
        }
        //获得用户信息
        ObjectRestResponse<AppUserDTO> appUserDTOObjectRestResponse= userFeign.userDetailByToken(token);
        log.info("----用户信息========="+appUserDTOObjectRestResponse.getData());

        if (appUserDTOObjectRestResponse==null||appUserDTOObjectRestResponse.getData()==null||appUserDTOObjectRestResponse.getData().getId()==0) {
            return ObjectRestResponse.createFailedResult(ResultCode.GET_APPUSER_FAILED_CODE,"无法识别,请重新上传");
        }
        AppUserDTO appUserDTO = appUserDTOObjectRestResponse.getData();
        idInformation.setUserLoginId(appUserDTO.getUserid());
        //获取用户认证信息
        ObjectRestResponse orr = null;
        try {
            orr = userFeign.authentication(idInformation.getUserLoginId(), null,null, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (orr==null) {
            return ObjectRestResponse.createFailedResult(ResultCode.GET_AUTH_INFO_FAILED_CODE,"无法识别,请重新上传");
        }
        Integer type = idInformation.getCertificateType();
        log.info("----type========="+type);
        try {
            if (type!=null&&type==0){
                ObjectRestResponse<Integer> result = certificationService.certificate(idInformation);
                if (result.getRel()) {
                    CompletableFuture.supplyAsync(()->{
                        setIntegral(appUserDTO.getUserid(),result.getData());
                        return null;
                    },executorService);
//                    Thread thread = new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            setIntegral(appUserDTO.getUserid(),result.getData());
//                        }
//                    });
//                   thread.start();
            }
                return result ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"无法识别,请重新上传");

    }

    private void setIntegral(Integer userid, Integer iId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userid);
        jsonObject.put("integralRuleCode", "CRETIFICATION");
        jsonObject.put("channelId", iId);
        mqServiceBiZ.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
    }

    @GetMapping(value = "/app/unauth/selectByUser")
    public IdInformation getOneByUserId(Integer userId) {
        return certificationService.getByUser(userId);
    }
}
