package org.jeecg.modules.stm.wb.manage.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 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.stm.utils.PdfUtils;
import org.jeecg.modules.stm.utils.StmConstans;
import org.jeecg.modules.stm.utils.SubVo;
import org.jeecg.modules.stm.utils.UserUtil;
import org.jeecg.modules.stm.wb.manage.entity.WbCompanyDetail;
import org.jeecg.modules.stm.wb.manage.entity.WbCompanyInfo;
import org.jeecg.modules.stm.wb.manage.entity.WbCompanyThirdApi;
import org.jeecg.modules.stm.wb.manage.entity.WbPullDataLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;


import org.jeecg.modules.stm.wb.manage.service.IWbCompanyDetailService;
import org.jeecg.modules.stm.wb.manage.service.IWbCompanyInfoService;
import org.jeecg.modules.stm.wb.manage.service.IWbCompanyThirdApiService;
import org.jeecg.modules.stm.wb.manage.service.IWbPullDataLogService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: wb_company_info
 * @Author: jeecg-boot
 * @Date:   2024-03-09
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/wb.manage/wbCompanyInfo")
@Slf4j
public class WbCompanyInfoController extends JeecgController<WbCompanyInfo, IWbCompanyInfoService> {
	@Autowired
	private IWbCompanyInfoService wbCompanyInfoService;
	 @Autowired
	 private IWbCompanyDetailService wbCompanyDetailService;
	@Autowired
	private IWbCompanyThirdApiService wbCompanyThirdApiService;
	@Autowired
	private FreeMarkerConfigurer configurer;
	@Autowired
	private IWbPullDataLogService wbPullDataLogService;

	 /**
	 * 分页列表查询
	 *
	 * @param wbCompanyInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "wb_company_info-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<WbCompanyInfo>> queryPageList(WbCompanyInfo wbCompanyInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WbCompanyInfo> queryWrapper = QueryGenerator.initQueryWrapper(wbCompanyInfo, req.getParameterMap());
		Page<WbCompanyInfo> page = new Page<WbCompanyInfo>(pageNo, pageSize);
		IPage<WbCompanyInfo> pageList = wbCompanyInfoService.page(page, queryWrapper);

		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param wbCompanyInfo
	 * @return
	 */
	@AutoLog(value = "wb_company_info-添加")
	  
	@RequiresPermissions("wb.manage:wb_company_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WbCompanyInfo wbCompanyInfo) {
		wbCompanyInfoService.save(wbCompanyInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param wbCompanyInfo
	 * @return
	 */
	@AutoLog(value = "wb_company_info-编辑")
	  
	@RequiresPermissions("wb.manage:wb_company_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WbCompanyInfo wbCompanyInfo) {
		wbCompanyInfoService.updateById(wbCompanyInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "wb_company_info-通过id删除")
	  
	@RequiresPermissions("wb.manage:wb_company_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		wbCompanyInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "wb_company_info-批量删除")
	  
	@RequiresPermissions("wb.manage:wb_company_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wbCompanyInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "wb_company_info-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<WbCompanyInfo> queryById(@RequestParam(name="id",required=true) String id) {
		WbCompanyInfo wbCompanyInfo = wbCompanyInfoService.getById(id);
		if(wbCompanyInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wbCompanyInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wbCompanyInfo
    */
    @RequiresPermissions("wb.manage:wb_company_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WbCompanyInfo wbCompanyInfo) {
        return super.exportXls(request, wbCompanyInfo, WbCompanyInfo.class, "wb_company_info");
    }

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

//	/**
//	* 获取企查查数据
//	 */
//	@RequiresPermissions("wb.manage:wb_company_info:add")
//	@PostMapping(value = "/pullDataFromAPI")
//	public Result<String> pullDataFromAPI(@RequestBody WbCompanyInfo wbCompanyInfo) {
//		List<WbCompanyThirdApi> list =  this.wbCompanyThirdApiService.list();
//		String token = "e2d8ad17-523c-4712-a4d3-0b2350c9f889";
//		Result<String> result = new Result<>();
//		for(int i=0;i<list.size();i++) {
//			WbCompanyThirdApi api = list.get(i);
//			if (api.getHasPage() == 1) {
//				result = this.wbCompanyDetailService.pullDataFromAPIWithPage(wbCompanyInfo, api, token,null);
//			} else {
//				result = this.wbCompanyDetailService.pullDataFromAPI(wbCompanyInfo, api, token);
//			}
//		}
//		 return result;
//	 }

	@GetMapping(value = "/pullBatchDataFromAPI")
	public Result<String> pullBatchDataFromAPI(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		QueryWrapper<WbCompanyInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id", idList);
		List<WbCompanyInfo>  listCompany =  this.wbCompanyInfoService.list(queryWrapper);
		for(WbCompanyInfo wbCompanyInfo:listCompany) {
			//pullDataFromAPI(wbCompanyInfo);
		}
		return Result.OK("操作完成");
	}

	@GetMapping(value = "/pullDataFromAPI")
	public Result<String>  pullDataFromAPI(@RequestParam(name="cid",required=true) Integer cid,
												@RequestParam(name="apiIds") String apiIds) {
		String token = StmConstans.TIANYANCHA_TOKEN;
		WbCompanyInfo wbCompanyInfo = this.wbCompanyInfoService.getById(cid);
		List<String> idList = Arrays.asList(apiIds.split(","));
		QueryWrapper<WbCompanyThirdApi> queryWrapper = new QueryWrapper<>();
		//queryWrapper.in("api_id", idList);
		List<WbCompanyThirdApi> apiList =  this.wbCompanyThirdApiService.list(queryWrapper);
		Result<List<WbCompanyDetail>>  result = new Result<>();
		for(WbCompanyThirdApi api:apiList) {
			if(api.getWeight()==0) continue;
			if (api.getHasPage() == 1) {
				result = this.wbCompanyDetailService.pullDataFromAPIWithPage(wbCompanyInfo, api, token,1);
			} else {
				result = this.wbCompanyDetailService.pullDataFromAPI(wbCompanyInfo, api, token);
			}

			savePullLog(wbCompanyInfo,api,result);
		}
		return Result.OK("操作完成");
	}

	@GetMapping(value = "/queryDataFromAPI")
	public Result<Map<String,String>>
				queryDataFromAPI(@RequestParam(name="cid",required=true) Integer cid,
										  @RequestParam(name="apiId") Integer apiId) {

		QueryWrapper<WbCompanyDetail> queryDetailWrapper = new QueryWrapper<>();
		queryDetailWrapper.eq("cid",cid);
		List<WbCompanyDetail> wbDetailList = this.wbCompanyDetailService.list(queryDetailWrapper);
		if(wbDetailList!=null&&wbDetailList.size()>0) {
			return Result.OK(getMapFromList(wbDetailList));
		}
		Result<List<WbCompanyDetail>>  result = new Result<>();
		String token = StmConstans.TIANYANCHA_TOKEN;
		WbCompanyInfo wbCompanyInfo = this.wbCompanyInfoService.getById(cid);
		QueryWrapper<WbCompanyThirdApi> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("api_id", apiId);
		List<WbCompanyThirdApi> apiList =  this.wbCompanyThirdApiService.list(queryWrapper);
		WbCompanyThirdApi api = apiList.get(0);
		if (api.getHasPage() == 1) {
			result = this.wbCompanyDetailService.pullDataFromAPIWithPage(wbCompanyInfo, api, token,1);
		} else {
			result = this.wbCompanyDetailService.pullDataFromAPI(wbCompanyInfo, api, token);
		}
		savePullLog(wbCompanyInfo,api,result);
		return   Result.OK(getMapFromList(result.getResult()));
	}


	/**
	 * 验证 cmmi证书
	 */
	@RequiresPermissions("wb.manage:wb_company_info:add")
	@PostMapping(value = "/checkCMMI")
	public Result<String> checkCMMI(@RequestBody WbCompanyInfo wbCompanyInfo) {
		this.wbCompanyInfoService.checkCMMI(wbCompanyInfo);
		return Result.OK("成功！");
	}


	@RequestMapping(value = "/exportPdf")
	public void exportPdf(WbCompanyInfo wbCompanyInfo, HttpServletResponse response) {
		try {
			SubVo subVo = new SubVo();
			String strTitle = wbCompanyInfo.getName();
			subVo.setTitle(strTitle);
			subVo.setTreeNodes(null);
			PdfUtils.setFileName("wbsurvey.pdf");
			PdfUtils.setTplName("wbsurvey.ftl");
			PdfUtils.download(configurer,subVo,response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	//保存记录
	private void savePullLog(WbCompanyInfo wbCompanyInfo,WbCompanyThirdApi wbCompanyThirdApi,
							 Result<List<WbCompanyDetail>>  result) {
		try {
			WbPullDataLog wbPullDataLog = new WbPullDataLog();
			wbPullDataLog.setCreateTime(new Date());
			wbPullDataLog.setCreateBy(UserUtil.getUserCode());
			wbPullDataLog.setCid(wbCompanyInfo.getId());
			wbPullDataLog.setApiId(wbCompanyThirdApi.getApiId());
			wbPullDataLog.setSta(result.getCode());
			wbPullDataLog.setApiName(wbCompanyThirdApi.getName());
			wbPullDataLog.setCname(wbCompanyInfo.getName());
			wbPullDataLog.setStaMsg(result.getMessage());
			wbPullDataLogService.save(wbPullDataLog);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Map<String,String> getMapFromList(List<WbCompanyDetail> wbCompanyDetails) {
		Map<String,String> retMap = new HashMap<>();
		for(WbCompanyDetail wbCompanyDetail:wbCompanyDetails) {
			retMap.put(wbCompanyDetail.getAttrKey(),wbCompanyDetail.getAttrVal());
		}
		return retMap;
	}
 }
