package org.springblade.zf.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.application.feign.ApplicationClient;
import org.springblade.command.feign.FzyjClient;
import org.springblade.command.pojo.entity.*;
import org.springblade.command.pojo.vo.FileuploadVO;
import org.springblade.command.pojo.vo.FzyjFkVO;
import org.springblade.command.pojo.vo.FzyjYjVO;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.http.util.HttpUtil;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.system.feign.ISysClient;
import org.springblade.system.feign.IUserClient;
import org.springblade.system.pojo.entity.Dept;
import org.springblade.system.pojo.vo.DictBizVO;
import org.springblade.system.pojo.vo.ZdAllVO;
import org.springblade.zf.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 转发 控制器
 *
 * @author wth
 * @since 2024-07-04
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/transpond")
@Tag(name = "转发接口", description = "转发接口")
public class ZfController extends BladeController {

	private final String ip = "http://localhost";

	private ApplicationClient applicationClient;

	private FzyjClient fzyjClient;

	private IDictBizClient dictBizClient;

	private ISysClient sysClient;

	private IUserClient userClient;

	/**
	 * 转发
	 */
	@Transactional
	@PostMapping("/request")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "转发接口", description = "传入RequestVO")
	public ResponseVO request(@RequestBody RequestVO requestVO, @RequestHeader Map<String, String> headers) {
		// 解析固定的请求格式
		KeyValueVO keyValueVO = requestVO.getParameter().getCondition().getKeyValueList().get(0);
		RequestCommonVO requestCommonVO = JSONObject.parseObject(keyValueVO.getValue(), RequestCommonVO.class);
		// 拼装固定的返回格式
		ResponseVO responseVO = new ResponseVO();
		responseVO.getData().getDataList().add(new DataListVO());
		FieldValuesVO fieldValuesVO = new FieldValuesVO();
		// 鉴权服务
		if (requestCommonVO.getServiceName().equals("blade-auth")) {
			// 登录
			if (requestCommonVO.getMappingName().equals("/oauth/token")) {
				String url = ip + "/" + requestCommonVO.getServiceName() + requestCommonVO.getMappingName();
				String response = HttpUtil.post(url, headers, requestCommonVO.getParams());
				fieldValuesVO.setValue(response);
			}
		} else if (AuthUtil.getUserId() == null || AuthUtil.getUserId().equals(-1L)) {
			fieldValuesVO.setValue(JSONObject.toJSONString(R.fail(401, "请求未授权，请重新登录")));
		} else {
			// 系统模块
			if (requestCommonVO.getServiceName().equals("blade-system")) {
				if (requestCommonVO.getMappingName().equals("/dict-biz/getDictionary")) {
					// 获取字典
					R<ZdAllVO> result = dictBizClient.getDictionary();
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				} else if (requestCommonVO.getMappingName().equals("/dict-biz/getTreeByCode")) {
					// app菜单
					R<List<DictBizVO>> result = dictBizClient.getTreeByCode(requestCommonVO.getParams());
					for (DictBizVO dictBizVO1 : result.getData()) {
						int zlrwTotal = 0;
						int zlrwYqs = 0;
						int zlrwYfk = 0;
						int gdrwTotal = 0;
						int gdrwYqs = 0;
						int gdrwYfk = 0;
						int tsrwTotal = 0;
						int tsrwYqs = 0;
						int tsrwYfk = 0;
						R rDept = sysClient.getDeptById();
						Dept dept = (Dept)rDept.getData();
						for (DictBizVO dictBizVO2 : dictBizVO1.getChildren()) {
							if (dictBizVO2.getId().equals(1811669515281408001L)) {
								// 疑似电信诈骗劝阻 总数量
								dictBizVO2.setNum(dept.getDeptCategory() != 6 ? fzyjClient.countByDept() : fzyjClient.countByUserId());
								zlrwTotal = zlrwTotal + dictBizVO2.getNum();
								// 疑似电信诈骗劝阻 已签收数量
								dictBizVO2.setNum1(dept.getDeptCategory() != 6 ? fzyjClient.countYqsByDept() : fzyjClient.countYqsByUserId());
								zlrwYqs = zlrwYqs + dictBizVO2.getNum1();
								// 疑似电信诈骗劝阻 已反馈数量
								dictBizVO2.setNum2(dept.getDeptCategory() != 6 ? fzyjClient.countYfkByDept() : fzyjClient.countYfkByUserId());
								zlrwYfk = zlrwYfk + dictBizVO2.getNum2();
							}
						}
						if (dictBizVO1.getId().equals(1811669161420562433L)) {
							// 指令任务 总数量
							dictBizVO1.setNum(zlrwTotal);
							// 指令任务 已签收数量
							dictBizVO1.setNum1(zlrwYqs);
							// 指令任务 已反馈数量
							dictBizVO1.setNum2(zlrwYfk);
						} else if (dictBizVO1.getId().equals(1811669598978744322L)) {
							// 规定任务 总数量
							dictBizVO1.setNum(gdrwTotal);
							// 规定任务 已签收数量
							dictBizVO1.setNum1(gdrwYqs);
							// 规定任务 已反馈数量
							dictBizVO1.setNum2(gdrwYfk);
						} else if (dictBizVO1.getId().equals(1811669722790404098L)) {
							// 推送任务 总数量
							dictBizVO1.setNum(tsrwTotal);
							// 推送任务 已签收数量
							dictBizVO1.setNum1(tsrwYqs);
							// 推送任务 已反馈数量
							dictBizVO1.setNum2(tsrwYfk);
						}
					}
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				} else if (requestCommonVO.getMappingName().equals("/dept/getByParentId")) {
					// 根据deptId查询子部门
					R result = sysClient.getDeptChild(Long.valueOf(requestCommonVO.getParams().get("deptId").toString()));
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				} else if (requestCommonVO.getMappingName().equals("/user/getByDeptId")) {
					// 根据deptId查询用户
					R result = userClient.getByDeptId(Long.valueOf(requestCommonVO.getParams().get("deptId").toString()));
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				}
			}
			// 指令中心服务
			if (requestCommonVO.getServiceName().equals("command-center")) {
				// 反诈预警
				if (requestCommonVO.getMappingName().equals("/fzyj/pageByUser")) {
					// 列表
					Query query = new Query();
					query.setSize(Integer.valueOf(requestCommonVO.getParams().get("size").toString()));
					query.setCurrent(Integer.valueOf(requestCommonVO.getParams().get("current").toString()));
					R result = fzyjClient.pageByDept(requestCommonVO.getParams(), query);
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				} else if (requestCommonVO.getMappingName().equals("/fzyj/detail")) {
					// 查询 疑似受害人信息 + 归属单位信息
					R result = fzyjClient.detail(Long.valueOf(requestCommonVO.getParams().get("syncId").toString()));
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				} else if (requestCommonVO.getMappingName().equals("/fzyj/yj")) {
					// 移交
					JSONObject jsonObject = new JSONObject();
					jsonObject.putAll(requestCommonVO.getParams());
					FzyjYjEntity fzyjYjEntity = jsonObject.toJavaObject(FzyjYjEntity.class);
					R result = fzyjClient.yj(fzyjYjEntity);
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
					// 移交给第三方平台
					FzyjYjVO fzyjYjVO = jsonObject.toJavaObject(FzyjYjVO.class);
					fzyjYjVO.setSendType(1);
					fzyjClient.dealUrgentRisks(fzyjYjVO);
				} else if (requestCommonVO.getMappingName().equals("/fzyj/fk")) {
					JSONObject jsonObject = new JSONObject();
					jsonObject.putAll(requestCommonVO.getParams());
					FzyjFkVO fzyjFkVO = jsonObject.toJavaObject(FzyjFkVO.class);
					List<FzyjShrEntity> shrList = fzyjFkVO.getShrList();
					R result = new R<>();
					if (requestCommonVO.getParams().get("smyj").toString().equals("1")) {
						// 需上门预警 指派
						FzyjUserEntity fzyjUserEntity = new FzyjUserEntity();
						BeanUtils.copyProperties(fzyjFkVO, fzyjUserEntity);
						fzyjClient.zp(fzyjUserEntity);
					}
					FzyjFkEntity fzyjFkEntity = jsonObject.toJavaObject(FzyjFkEntity.class);
					BeanUtils.copyProperties(fzyjFkVO, fzyjFkEntity);

					// 新增附件
					FileuploadVO fileuploadVO = new FileuploadVO();
					if (StringUtils.isNotBlank(fzyjFkEntity.getJmjgDm()) && fzyjFkEntity.getJmjgDm().equals("3")) {
						FzyjFjEntity fzyjFjEntity = fzyjFkVO.getFj();
						fzyjClient.saveFj(fzyjFjEntity);
						// 附件回写给第三方平台
						String uploadResult = fzyjClient.fileupload(fzyjFjEntity);
						// 处理返回结果
						fileuploadVO = JSONObject.parseObject(uploadResult, FileuploadVO.class);
						fzyjFkVO.setWebUrl(fileuploadVO.getWebUrl());
						fzyjFkVO.setLocalUrl(fileuploadVO.getLocalUrl());
						// cw=243*15=3645
						// jn=118*10=1180
						// le=38104*0.1=3810
						// zq=1138*2=2276
						// mb=333*3=999
						// 11900
						// xz=43687  460*21 = 9660
					}
					// 新增或更新受害人信息
					if (null != shrList && shrList.size() > 0) {
						fzyjClient.saveOrUpdateShr(shrList);
					}

					// 根据syncId查询是否有反馈记录
					R<FzyjFkEntity> oldFk = fzyjClient.getFkBySyncId(fzyjFkEntity.getSyncId());
					if (oldFk.getData().getSyncId() != null && !oldFk.getData().getSyncId().equals(0L)) {
						// 更新反馈
						fzyjFkEntity.setMjfk(1);
						result = fzyjClient.updateFkBySyncId(fzyjFkEntity);
						// 反馈回写给第三方平台
						fzyjFkVO.setDisposalWayDct("3");
						fzyjFkVO.setFsafadsDct("4");
						fzyjFkVO.setFkrType(2);
					} else {
						// 新增反馈
						result = fzyjClient.saveFk(fzyjFkEntity);
						if (!requestCommonVO.getParams().get("smyj").toString().equals("1")) {
							// 反馈回写给第三方平台
							fzyjFkVO.setDisposalWayDct("1");
							fzyjFkVO.setFsafadsDct("2");
							fzyjFkVO.setFkrType(1);
							fzyjClient.feedbackUrgentRisks(fzyjFkVO);
						}
					}

					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				}
			}
			// 应用管理服务
			if (requestCommonVO.getServiceName().equals("app-management")) {
				// 应用列表
				if (requestCommonVO.getMappingName().equals("/application/page")) {
					Query query = new Query();
					query.setSize(Integer.valueOf(requestCommonVO.getParams().get("size").toString()));
					query.setCurrent(Integer.valueOf(requestCommonVO.getParams().get("current").toString()));
					R result = applicationClient.page(requestCommonVO.getParams(), query);
					fieldValuesVO.setValue(JSONObject.toJSONString(result));
				}
			}
		}
		// 返回结果
		responseVO.getData().getDataList().get(0).getFieldValues().add(fieldValuesVO);
		return responseVO;
	}
}
