package com.qunzhixinxi.hnqz.admin.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.config.UpmsConfig;
import com.qunzhixinxi.hnqz.admin.entity.SysDeptSub;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptMapper;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptSubService;
import com.qunzhixinxi.hnqz.admin.service.SysUserService;
import com.qunzhixinxi.hnqz.admin.service.WmSettlementService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.ding.config.DingConfig;
import com.qunzhixinxi.hnqz.common.ding.entity.*;
import com.qunzhixinxi.hnqz.common.ding.service.DingService;
import com.qunzhixinxi.hnqz.common.ding.utils.JsonUtils;
import com.qunzhixinxi.hnqz.common.ding.utils.SignUtils;
import com.qunzhixinxi.hnqz.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 任务表
 *
 * @author zhangwt
 * @date 2020-12-01
 */
@Slf4j
@Controller
@RequestMapping
@Api(value = "ding", tags = "灵工信息认证")
public class WmSettlementController {

	@Autowired
	private DingService dingService;

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	private WmSettlementService wmSettlementService;

	@Autowired
	private SysDeptService deptService;

	@Autowired
	private SysDeptSubService sysDeptSubService;

	@Autowired
	private SysUserService sysUserService;


	public static String ReadAsChars(HttpServletRequest request) {

		BufferedReader br = null;
		StringBuilder sb = new StringBuilder("");
		try {
			br = request.getReader();
			String str;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}


	/**
	 * 测试人力家
	 *
	 * @return
	 */
	@Inner(value = false)
	@ApiOperation(value = "人力家", notes = "人力家")
	@PostMapping("/employ/callback")
	@ResponseBody
	public NotifyResponse employNotify() {
		String body = ReadAsChars(this.request);
		log.info("人力家通知结果：{}", body);

		SysDeptSub query = new SysDeptSub();
//		query.setAppId("888999");

		JSONObject jsonObject = JSON.parseObject(body);
		String data = jsonObject.get("data").toString();
		String sign = jsonObject.get("sign").toString();
		String appId = jsonObject.get("appId").toString();
		query.setAppId(appId);

//		SysDept config = deptService.getOne(Wrappers.query(query));
//		List<SysDept> sysDeptList = deptService.listScope(query);
		log.info("query: {}",query);

		List<SysDeptSub> subList = sysDeptSubService.list(Wrappers.query(query));

		SysDeptSub config = new SysDeptSub();
		if(CollectionUtils.isNotEmpty(subList)){
			config = subList.get(0);
		}
		log.info("config: {}",config);

		log.info("rsaPublicKey: {}",config.getRsaPublicKey());

		log.info("data:" + jsonObject.get("data"));
		log.info("sign:" + jsonObject.get("sign"));
		log.info("appId:" + jsonObject.get("appId"));

		boolean verify = SignUtils.verify(config.getRsaPublicKey(), data, sign);
		if (!verify) {
			return NotifyResponse.failure("验签失败");
		}

		NotifyResponse response = wmSettlementService.confirm(data);

		return response;
	}


	/**
	 * 测试人力家
	 *
	 * @return
	 */
	@ApiOperation(value = "灵工信息认证", notes = "灵工信息认证")
	@PostMapping("/check")
	@ResponseBody
	public R check(@RequestBody Map map) {
		List list = new ArrayList<>();
		list.add(map);
		DingConfig config = new DingConfig();
		config.setAppId("888999");
		config.setAppSecret("5T8134269D467IGa0ZC7s907666r2C43");
		config.setQueryUrl("https://test-f.renlijia.com");
		return R.ok(dingService.check(config, list));
	}

	/**
	 * 测试人力家
	 *
	 * @return
	 */
	@Inner(value = false)
	@ApiOperation(value = "子账户余额查询", notes = "子账户余额查询")
	@PostMapping("/query")
	@ResponseBody
	public R query() {
		DingConfig config = new DingConfig();
		config.setAppId("888999");
		config.setAppSecret("5T8134269D467IGa0ZC7s907666r2C43");
		config.setQueryUrl("https://test-f.renlijia.com");
		SysUser sysUser = sysUserService.getByIdIgnore("671");
		return R.ok(dingService.query(config));
	}

	/**
	 * 结算单推送
	 *
	 * @return
	 */
	@ApiOperation(value = "结算单推送", notes = "结算单推送")
	@PostMapping("/pay")
	@ResponseBody
	public R pay(@RequestBody Map map) {
		List list = new ArrayList<>();
		DingConfig config = new DingConfig();
		config.setAppId("888999");
		config.setAppSecret("5T8134269D467IGa0ZC7s907666r2C43");
		config.setQueryUrl("https://test-f.renlijia.com");
		list.add(map);
		String subjectName = "灵工测试结算主体";
		String statementNo = "2222";
		String statementName = "9月15日市场推广服务费用结算";
		Integer bizType = 30;

		return R.ok(dingService.pay(config, subjectName, statementNo, statementName, bizType, list));
	}

	@Autowired
	private  UpmsConfig upmsConfig;
	/**
	 * 测试人力家
	 *
	 * @return
	 */
	@Inner(value = false)
	@GetMapping("/test")
	@ResponseBody
	public R test() {

		System.out.println(upmsConfig.getApiUrl());
		return R.ok();
	}


}
