package org.jeecg.modules.api.okki.site.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.api.okki.site.entity.OkkiSite;
import org.jeecg.modules.api.okki.site.service.IOkkiSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description: 站点
 * @Author: jeecg-boot
 * @Date:   2024-04-29
 * @Version: V1.0
 */
@Api(tags="站点")
@RestController
@RequestMapping("/site/okkiSite")
@Slf4j
public class OkkiSiteController extends JeecgController<OkkiSite, IOkkiSiteService> {
	@Autowired
	private IOkkiSiteService okkiSiteService;

	private final static String URL = "https://cms.dev.xiaoman.cn/shop-api/external/site";

	private final static String CLIENT_SECRET = "";
	
	/**
	 * 分页列表查询
	 *
	 * @param okkiSite
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "站点-分页列表查询")
	@ApiOperation(value="站点-分页列表查询", notes="站点-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<OkkiSite>> queryPageList(OkkiSite okkiSite,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<OkkiSite> queryWrapper = QueryGenerator.initQueryWrapper(okkiSite, req.getParameterMap());
		Page<OkkiSite> page = new Page<OkkiSite>(pageNo, pageSize);
		IPage<OkkiSite> pageList = okkiSiteService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param okkiSite
	 * @return
	 */
	@AutoLog(value = "站点-添加")
	@ApiOperation(value="站点-添加", notes="站点-添加")
	@RequiresPermissions("site:okki_site:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody OkkiSite okkiSite) {
		okkiSiteService.save(okkiSite);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param okkiSite
	 * @return
	 */
	@AutoLog(value = "站点-编辑")
	@ApiOperation(value="站点-编辑", notes="站点-编辑")
	@RequiresPermissions("site:okki_site:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody OkkiSite okkiSite) {
		okkiSiteService.updateById(okkiSite);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "站点-通过id删除")
	@ApiOperation(value="站点-通过id删除", notes="站点-通过id删除")
	@RequiresPermissions("site:okki_site:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		okkiSiteService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "站点-批量删除")
	@ApiOperation(value="站点-批量删除", notes="站点-批量删除")
	@RequiresPermissions("site:okki_site:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.okkiSiteService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "站点-通过id查询")
	@ApiOperation(value="站点-通过id查询", notes="站点-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<OkkiSite> queryById(@RequestParam(name="id",required=true) String id) {
		OkkiSite okkiSite = okkiSiteService.getById(id);
		if(okkiSite==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(okkiSite);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param okkiSite
    */
    @RequiresPermissions("site:okki_site:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OkkiSite okkiSite) {
        return super.exportXls(request, okkiSite, OkkiSite.class, "站点");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("site:okki_site:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OkkiSite.class);
    }

	/**
	 * 完成装修
	 * @param okkiSite
	 * @return
	 */
	@PostMapping(value = "status")
	public Result<String> changeStatus(@RequestBody OkkiSite okkiSite) throws Exception{
		// TODO:: 请求okki平台接口
		String url = "https://cms.dev.xiaoman.cn/shop-api/External/site";
		String clientSecret = "rAqZAp9oo0crNariGVVpt5AvPeVhCKXJ";
		Map<String, String> query = new TreeMap<>();
		query.put("sign_method", "hmac-md5");
		query.put("timestamp", String.valueOf(System.currentTimeMillis()));
		query.put("site_id", String.valueOf(okkiSite.getSiteId()));
		query.put("method", "update_site_status");

		Map<String, Object> postData = new HashMap<>();
		postData.put("status", 3);

		String queryStr = buildQueryString(query);
		String body = toJsonString(postData);
		String signStr = queryStr + body;
		query.put("signature", generateHmacMD5(signStr, clientSecret));

		String okkiUrl = url + "?" + buildQueryString(query);
		String res = doPost(okkiUrl, body);
		if (!res.isEmpty()) {
			okkiSite.setStatus(3);
			okkiSiteService.updateById(okkiSite);
			return Result.OK("操作成功");
		}else {
			return Result.error("操作失败");
		}
	}


//	public static void main(String[] args) throws Exception {
//		String url = "https://cms.dev.xiaoman.cn/shop-api/External/site";
//		String clientSecret = "rAqZAp9oo0crNariGVVpt5AvPeVhCKXJ";
//		Map<String, String> query = new TreeMap<>();
//		query.put("sign_method", "hmac-md5");
//		query.put("timestamp", String.valueOf(System.currentTimeMillis()));
//		query.put("site_id", "1000002");
//		query.put("method", "update_site_status");
//
//		Map<String, Object> postData = new HashMap<>();
//		postData.put("status", 3);
//
//		String queryStr = buildQueryString(query);
//		String body = toJsonString(postData);
//		String signStr = queryStr + body;
//		query.put("signature", generateHmacMD5(signStr, clientSecret));
//
//		String okkiUrl = url + "?" + buildQueryString(query);
//		String res = doPost(okkiUrl, body);
//		System.out.println(res);
//	}

	private static String buildQueryString(Map<String, String> params) {
		StringBuilder query = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			if (query.length() > 0) {
				query.append("&");
			}
			query.append(entry.getKey()).append("=").append(entry.getValue());
		}
		return query.toString();
	}

	private static String generateHmacMD5(String data, String secret) throws Exception {
		SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacMD5");
		Mac mac = Mac.getInstance("HmacMD5");
		mac.init(keySpec);
		byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
		StringBuilder sb = new StringBuilder(hmacBytes.length * 2);
		for (byte b : hmacBytes) {
			sb.append(String.format("%02x", b));
		}
		return sb.toString();
	}

	private static String toJsonString(Object object) throws Exception {
		com.google.gson.Gson gson = new com.google.gson.Gson();
		return gson.toJson(object);
	}

	private static String doPost(String url, String data) throws Exception {
		java.net.URL apiUrl = new URL(url);
		System.out.println(url);
		HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setDoOutput(true);
		try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
			outputStream.write(data.getBytes(StandardCharsets.UTF_8));
			outputStream.flush();
		}

		int responseCode = connection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
				String line;
				StringBuilder response = new StringBuilder();
				while ((line = in.readLine()) != null) {
					response.append(line);
				}
				return response.toString();
			}
		}
		throw new Exception("HTTP request failed with response code: " + responseCode);
	}
}
