/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fadada.api.bean.req.template.*;
import com.fadada.api.bean.rsp.BaseRsp;
import com.fadada.api.bean.rsp.template.GetCompanyTemplatePreviewUrlRsp;
import com.fadada.api.bean.rsp.template.GetTemplateDetailRsp;
import com.fadada.api.bean.rsp.template.GetTemplateMainUrlRsp;
import com.fadada.api.bean.rsp.template.UploadCompanyTemplateFileRsp;
import com.fadada.api.client.TemplateClient;
import com.fadada.api.exception.ApiException;
import com.yifu.cloud.plus.v1.yifu.archives.entity.FddContractTemplate;
import com.yifu.cloud.plus.v1.yifu.archives.entity.FddContractTemplateFile;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.FddContractTemplateMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddContractTemplateFileService;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddContractTemplateService;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddReqLogService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.FddUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 法大大员工合同模板
 *
 * @author fxj
 * @date 2022-06-28 16:24:12
 */
@Service
@RequiredArgsConstructor
public class FddContractTemplateServiceImpl extends ServiceImpl<FddContractTemplateMapper, FddContractTemplate> implements FddContractTemplateService {

	@Autowired
	private FddUtil fddUtil;
	@Autowired
	private FddReqLogService reqLogService;
	@Autowired
	private FddContractTemplateFileService templateFileService;

	/**
	 * 法大大员工合同模板简单分页查询
	 *
	 * @param fddContractTemplate 法大大员工合同模板
	 * @return IPage<FddContractTemplate>
	 */
	@Override
	public IPage<FddContractTemplate> getFddContractTemplatePage(Page<FddContractTemplate> page, FddContractTemplate fddContractTemplate) throws ApiException {
		IPage<FddContractTemplate> fddContractTemplatePage = baseMapper.getFddContractTemplatePage(page, fddContractTemplate);
		List<FddContractTemplate> records = fddContractTemplatePage.getRecords();
		for (FddContractTemplate record : records) {
			//发送请求
			GetTemplateDetailReq req = new GetTemplateDetailReq();
			req.setToken(fddUtil.getToken());
			req.setTemplateId(record.getFddTemplateId());
			TemplateClient client = new TemplateClient(fddUtil.getFadadaApiClient());
			BaseRsp<GetTemplateDetailRsp> rsp = client.getTemplateDetail(req);
			//校验参数
			if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
				String fileId = rsp.getData().getTemplateFiles().get(CommonConstants.ZERO_INT).getFileId();
				FddContractTemplateFile fddContractTemplateFile = templateFileService.getOne(Wrappers.<FddContractTemplateFile>query().lambda().eq(FddContractTemplateFile::getFddTemplateId, record.getFddTemplateId()));
				if(fddContractTemplateFile!=null&&!StringUtils.equals(fddContractTemplateFile.getFddFileId(),fileId)){
					fddContractTemplateFile.setFddFileId(fileId);
					templateFileService.updateById(fddContractTemplateFile);
				}
			}
		}
		return fddContractTemplatePage;
	}

	@Override
	public R saveInfo(FddContractTemplate fddContractTemplate) {
		long count = this.count(Wrappers.<FddContractTemplate>query().lambda()
				.eq(FddContractTemplate::getLocalName,fddContractTemplate.getLocalName())
		);
		if (count > CommonConstants.ZERO_INT) {
			return R.failed("已存在相同模板名称记录");
		}
		boolean save = this.save(fddContractTemplate);
		if (save) {
			return R.ok();
		}
		return R.failed("失败");
	}

	@Override
	public R<Boolean> changeInfo(FddContractTemplate fddContractTemplate) {
		long count = this.count(Wrappers.<FddContractTemplate>query().lambda()
				.eq(FddContractTemplate::getLocalName,fddContractTemplate.getLocalName())
				.notIn(FddContractTemplate::getId, fddContractTemplate.getId()));
		if (count > CommonConstants.ZERO_INT) {
			return R.failed("已存在相同模板名称记录");
		}
		return new R<>(this.updateById(fddContractTemplate));
	}

	@Override
	public R<String> upload(MultipartFile file, String id) throws ApiException, IOException {
		FddContractTemplate entity = this.getById(id);
		if (entity == null) {
			return R.failed("未查询到相关记录");
		}
		if (StringUtils.isNotEmpty(entity.getFddTemplateId())) {
			return R.failed("已上传法大大模板");
		}
		//发送请求
		UploadCompanyTemplateFileReq req = new UploadCompanyTemplateFileReq();
		req.setToken(fddUtil.getToken());
		req.setFileType(CommonConstants.ONE_INT, null);
		TemplateClient client = new TemplateClient(fddUtil.getFadadaApiClient());
		BaseRsp<UploadCompanyTemplateFileRsp> rsp = client.uploadCompanyTemplateFile(req, FddSealInfoServiceImpl.multipartFileToFile(file));
		reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getMethodName(),req, rsp);
		//校验参数
		if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
			entity.setFddTemplateId(rsp.getData().getTemplateId());
			this.updateById(entity);
			//生成文件模板记录
			FddContractTemplateFile templateFile = new FddContractTemplateFile();
			templateFile.setFddTemplateId(entity.getFddTemplateId());
			templateFile.setFddFileId(rsp.getData().getFileId());
			templateFileService.save(templateFile);
			return R.ok();
		} else {
			return R.failed("上传失败");
		}
	}

	@Override
	public R<String> delCompanyTemplateFile(String id) throws ApiException {
		FddContractTemplate entity = this.getById(id);
		if (entity == null) {
			return R.failed("未查询到相关记录");
		}
		if (StringUtils.isEmpty(entity.getFddTemplateId())) {
			return R.failed("法大大模板未上传");
		}
		//发送请求
		DelCompanyTemplateFileReq req = new DelCompanyTemplateFileReq();
		req.setToken(fddUtil.getToken());
		DelCompanyTemplateFileReq.TemplateInfo templateInfo = new DelCompanyTemplateFileReq.TemplateInfo();
		templateInfo.setTemplateId(entity.getFddTemplateId());
		req.setTemplateInfo(templateInfo);
		TemplateClient client = new TemplateClient(fddUtil.getFadadaApiClient());
		BaseRsp<UploadCompanyTemplateFileRsp> rsp = client.delCompanyTemplateFile(req);
		reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getMethodName(),req, rsp);
		//校验参数
		if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
			baseMapper.updateTeFddTemplateNull(entity.getId());
			//删除附件
			templateFileService.remove(Wrappers.<FddContractTemplateFile>query().lambda().eq(FddContractTemplateFile::getFddTemplateId,entity.getFddTemplateId()));
			return R.ok();
		} else {
			return R.failed("删除失败");
		}
	}

	@Override
	public R<String> getTemplateMainUrl(String id) throws ApiException {
		FddContractTemplate entity = this.getById(id);
		if (entity == null) {
			return R.failed("未查询到相关记录");
		}
		if (StringUtils.isEmpty(entity.getFddTemplateId())) {
			return R.failed("法大大模板未上传");
		}
		//发送请求
		GetTemplateMainUrlReq req = new GetTemplateMainUrlReq();
		req.setToken(fddUtil.getToken());
		GetTemplateMainUrlReq.TemplateInfo templateInfo = new GetTemplateMainUrlReq.TemplateInfo();
		templateInfo.setTemplateId(entity.getFddTemplateId());
		req.setTemplateInfo(templateInfo);
		TemplateClient client = new TemplateClient(fddUtil.getFadadaApiClient());
		BaseRsp<GetTemplateMainUrlRsp> rsp = client.getTemplateMainUrl(req);
		reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getMethodName(),req, rsp);
		//校验参数
		if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
			entity.setModifyUploadStatus(CommonConstants.ONE_STRING);
			this.updateById(entity);
			return new R<>(rsp.getData().getEditTemplateUrl());
		} else {
			return R.failed("获取失败");
		}
	}


	@Override
	public R<String> getCompanyTemplatePreviewUrl(String id) throws ApiException {
		FddContractTemplate entity = this.getById(id);
		if (entity == null) {
			return R.failed("未查询到相关记录");
		}
		if (StringUtils.isEmpty(entity.getFddTemplateId())) {
			return R.failed("法大大模板未上传");
		}
		//发送请求
		GetEditCompanyTemplateUrlReq req = new GetEditCompanyTemplateUrlReq();
		req.setToken(fddUtil.getToken());
		GetEditCompanyTemplateUrlReq.TemplateInfo templateInfo = new GetEditCompanyTemplateUrlReq.TemplateInfo();
		templateInfo.setTemplateId(entity.getFddTemplateId());
		req.setTemplateInfo(templateInfo);
		TemplateClient client = new TemplateClient(fddUtil.getFadadaApiClient());
		BaseRsp<GetCompanyTemplatePreviewUrlRsp> rsp = client.getCompanyTemplatePreviewUrl(req);
		reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getMethodName(),req, rsp);
		//校验参数
		if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
			return new R<>(rsp.getData().getTemplatePreviewUrl());
		} else {
			return R.failed(rsp.getMsg());
		}
	}
}

