package cn.pluss.platform.controller;

import cn.pluss.platform.PushService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.entitiy.PushCidAlias;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.MobV2PushUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 发送下单，催单通知等接口
 *
 * @author DJH
 */
@RestController
@RequestMapping("/push/")
public class PushController {

    @Setter(onMethod_ = {@Autowired})
    private PushService pushService;

    @Autowired
    private UserAppService userAppService;


    @PostMapping("/pushMsg")
    public Result<Object> pushMsg(@RequestBody Map<String, Object> param) {
        String userId = (String) param.get("userId");
        String msgType = (String) param.get("type");

        Integer storeId = (Integer) param.get("storeId");

        if (StringUtils.isNotBlank(userId)) {
            pushService.pushMsg(userId, msgType);
        } else {
            pushService.pushMsg(storeId, msgType);
        }


        return ResultGenerator.genSuccessResult();
    }

    /**
     * 绑定cid
     *
     * @param param
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/bindalias")
    public Result<Object> bindAlias(@RequestBody Map<String, Object> param) throws IOException, NoSuchAlgorithmException {

        UserApp userApp = userAppService.queryUserAppByToken();

        String uid = userApp.getUserId().toString();
        String cid = param.get("cid").toString();

        MobV2PushUtil mobV2PushUtil = new MobV2PushUtil();
        String token = mobV2PushUtil.getToken();

        Map<String, Object> map = new HashMap<>();

        List<PushCidAlias> pushCidAliases = new ArrayList<>();
        PushCidAlias pushCidAlias = new PushCidAlias();
        pushCidAlias.setCid(cid);
        pushCidAlias.setAlias(uid);
        pushCidAliases.add(pushCidAlias);

        map.put("data_list", pushCidAliases);
        String json = new ObjectMapper().writeValueAsString(map);

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        header.add("token", token);

        HttpEntity<String> httpEntity = new HttpEntity<>(json, header);

        RestTemplate restTemplate = new RestTemplate();
        // 设置为UTF8编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        String tokenInfo = restTemplate.postForObject(
                "https://restapi.getui.com/v2/" + MobV2PushUtil.appId + "/user/alias", httpEntity,
                String.class);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(tokenInfo);
        JsonNode code = jsonNode.get("code");
        if (code.asText().equals("0")) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(jsonNode.get("msg").asText());
        }
    }

    /**
     * 解绑别名
     *
     * @param param
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/unbindingAlias")
    public Result<Object> unbindingAlias(@RequestBody Map<String, Object> param) throws IOException, NoSuchAlgorithmException {

        UserApp userApp = userAppService.queryUserAppByToken();

        String uid = userApp.getUserId().toString();
        String cid = param.get("cid").toString();

        MobV2PushUtil mobV2PushUtil = new MobV2PushUtil();
        String token = mobV2PushUtil.getToken();

        Map<String, Object> map = new HashMap<>();

        List<PushCidAlias> pushCidAliases = new ArrayList<>();
        PushCidAlias pushCidAlias = new PushCidAlias();
        pushCidAlias.setCid(cid);
        pushCidAlias.setAlias(uid);
        pushCidAliases.add(pushCidAlias);

        map.put("data_list", pushCidAliases);

        String json = new ObjectMapper().writeValueAsString(map);

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        header.add("token", token);

        HttpEntity<String> httpEntity = new HttpEntity<>(json, header);

        RestTemplate restTemplate = new RestTemplate();
        // 设置为UTF8编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        // delete, entity直接设为null即可
        ResponseEntity<Map> resultEntity = restTemplate.exchange("https://restapi.getui.com/v2/" + MobV2PushUtil.appId + "/user/alias",
                HttpMethod.DELETE,
                httpEntity,
                Map.class);
        if (resultEntity != null) {
            System.out.println("result:" + resultEntity);
        }

        Map<String, Object> res = resultEntity.getBody();


        String code = res.get("code").toString();
        if (code.equals("0")) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(res.get("msg").toString());
        }
    }
}
