package thyyxxk.webserver.api.bjdeshun;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.auth.PassToken;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.api.bjdeshun.EvaluatorDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.api.bjdeshun.EvaluateRecord;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/bjdeshun/evaluator")
public class EvaluatorController {
    private final EvaluatorDao dao;
    private final UserCache userCache;
    private final RestTemplate template;
    private static final String CLIENT = "http://{IP}:10791/inf/{ACTION}";

    @Autowired
    public EvaluatorController(EvaluatorDao dao, UserCache userCache, RestTemplate template) {
        this.dao = dao;
        this.userCache = userCache;
        this.template = template;
    }

    @PassToken
    @PostMapping("/signInWhenUserLogin")
    public void signInWhenUserLogin (@RequestBody EvaluateRecord body) throws Exception {
//        String url = CLIENT.replace("{IP}", body.getClientIp())
//                .replace("{ACTION}", "SO");
//        String result = new RestTemplate().postForObject(url, null, String.class);
//        log.info("【{}】执行签退：{}", body.getClientIp(), result);
//        signIn(body);
    }

    @PassToken
    @PostMapping("/start")
    public ResultVo<String> start(HttpServletRequest request, @RequestBody EvaluateRecord body) throws Exception {
//        log.info("启动评价器：{}", body);
//        QueryWrapper<EvaluateRecord> wrapper = new QueryWrapper<>();
//        wrapper.eq("pat_no", body.getPatNo());
//        wrapper.eq("times", body.getTimes());
//        wrapper.eq("type", body.getType());
//        int count = dao.selectCount(wrapper);
//        if (count > 0) {
//            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR,
//                    "该笔交易已完成评价，请勿重复发起。");
//        }
//        if (StringUtil.isBlank(body.getClientIp())) {
//            body.setClientIp(IpAddressUtil.getIPAddress(request));
//        }
//        if (notSignedIn(body.getClientIp())) {
//            signIn(body);
//        }
//        return executeCall(body);
        return null;
    }

    private boolean notSignedIn(String ip) {
        String url = CLIENT.replace("{IP}", ip)
                .replace("{ACTION}", "LS");
        String result = template.postForObject(url, null, String.class);
        log.info("【{}】查询登录状态：{}", ip, result);
        if (null == result) {
            return true;
        }
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        JSONObject info = resultJson.getJSONObject("info");
        return StringUtil.isBlank(info.getString("name"));
    }

    private void signIn(EvaluateRecord body) throws Exception {
        JSONObject params = new JSONObject();
        params.put("num", userCache.get(body.getStaffId()).getCodeRs());
        params.put("name", body.getStaffName());
        params.put("photo", "");
        String url = CLIENT.replace("{IP}", body.getClientIp())
                .replace("{ACTION}", "SS");
        String result = template.postForObject(url, params, String.class);
        log.info("【{}】执行登录：{}", body.getClientIp(), result);
        if (null == result) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        if (!resultJson.getString("code").equals("0")) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR, resultJson.getString("text"));
        }
        boolean unSignedIn;
        do {
            TimeUnit.SECONDS.sleep(2);
            unSignedIn = notSignedIn(body.getClientIp());
        } while (unSignedIn);
    }

    private String queryProgress(String ip) {
        String url = CLIENT.replace("{IP}", ip)
                .replace("{ACTION}", "PR");
        String result = template.postForObject(url, null, String.class);
        log.info("【{}】查询耗时操作进度：{}", ip, result);
        if (null == result) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        String progress = resultJson.getString("progress");
        if (StringUtil.isBlank(progress)) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        return progress;
    }

    private ResultVo<String> executeCall(EvaluateRecord body) {
        String url = CLIENT.replace("{IP}", body.getClientIp())
                .replace("{ACTION}", "ES");
        String result = template.postForObject(url, null, String.class);
        log.info("【{}】评价结果：{}", body.getClientIp(), result);
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        Integer data = resultJson.getInteger("data");
        if (null == data) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        // 评价器只有4个按键，
        // 原始值是 1-很满意，2-满意，3-基本满意，4-不满意。
        // 通过 6-x 转换为 2-不满意，3-基本满意，4-满意，5-很满意
        body.setRateValue(6 - data);
        dao.insert(body);
        return ResultVoUtil.success();
    }
}
