package org.springblade.flow.shop.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springblade.common.cache.FlowCache;
import org.springblade.common.enums.AppConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.flow.shop.entity.AuthInfoData;
import org.springblade.flow.shop.entity.ShopEnum;
import org.springblade.flow.shop.task.callback.ShopInvitationFailCallback;
import org.springblade.ldt.shop.entity.Audit;
import org.springblade.ldt.shop.entity.Shop;
import org.springblade.ldt.shop.service.IAuditService;
import org.springblade.ldt.shop.service.IShopService;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.common.YeepayApiConstant;
import org.springblade.yeePay.common.YeepayProduct;
import org.springblade.yeePay.entity.saas.WechatApplyDto;
import org.springblade.yeePay.service.YeepayCommonService;
import org.springblade.yeePay.service.YeepaySaasService;

import java.util.*;

/**
 * @author: lianghanqiang
 * @description: 微信实名认证申请
 * @since: 9/17/21 -- 11:29 AM
 */
public class WechatApplyTask implements JavaDelegate {

	private IShopService shopService;
	private IAuditService auditService;
	private YeepaySaasService yeepaySaasService;
	private YeepayCommonService yeepayCommonService;
	private YeePayConst yeePayConst;
	private QueryAuthStatus queryAuthStatus;

	{
		shopService = SpringUtil.getBean(IShopService.class);
		auditService = SpringUtil.getBean(IAuditService.class);
		yeepaySaasService = SpringUtil.getBean(YeepaySaasService.class);
		yeepayCommonService = SpringUtil.getBean(YeepayCommonService.class);
		yeePayConst = SpringUtil.getBean(YeePayConst.class);
	}

	@Override
	public void execute(DelegateExecution delegateExecution) {

		//流程变量
		Map<String, Object> variables = delegateExecution.getVariables();
		Audit audit = auditService.getById(Convert.toStr(variables.get("auditId")));
		Shop shop = shopService.getById(Convert.toStr(variables.get("shopId")));

		//封装微信申请参数
		WechatApplyDto wechatApplyDto = buildWechatApplyDto(audit,shop);

		//提交微信实名认证申请
		YopResponse yopResponse = yeepaySaasService.wechatApply(wechatApplyDto);
		JSONObject resObj = JSON.parseObject(yopResponse.getStringResult());

		//队列信息封装
		AuthInfoData authInfoData = AuthInfoData.builder()
			.variables(variables)
			.shop(shop)
			.audit(audit)
			.build();

		authInfoData.setApplymentId(resObj.getString("applymentId"));
		authInfoData.setSubMerchantNo(wechatApplyDto.getSubMerchantNo());
		authInfoData.setReportFee(YeepayApiConstant.reportFeeType.valueOf(wechatApplyDto.getReportFee()));
		authInfoData.setIsNotify(Boolean.FALSE);

		//加入微信认证队列
		if (!Objects.equals(resObj.getString("returnMsg"),"成功")) {
			queryAuthStatus.applyReject(authInfoData,resObj.toJSONString());
		}else {
			FlowCache.addAuthMember(authInfoData);
		}
	}

	/**
	 * 封装微信实名认证参数
	 * */
	private WechatApplyDto buildWechatApplyDto(Audit audit, Shop shop){
		WechatApplyDto wechatApplyDto = WechatApplyDto.builder().build();

		String identificationBackCopy = yeepayCommonService.addFileToYeepay(audit.getIdCardContrary());
		String identificationFrontCopy = yeepayCommonService.addFileToYeepay(audit.getIdCardFront());

		if (Objects.equals(audit.getTypeOfEnterprise(), AppConstant.ENTERPRISE_TYPE.MINICRO.name())){
			//小微企业
			String[] pics = shop.getShopPic().split(",");
			String storeHeaderCopy = yeepayCommonService.addFileToYeepay(pics[0]);
			String storeIndoorCopy = yeepayCommonService.addFileToYeepay(pics[1]);
			wechatApplyDto.setMicroBizType(YeepayApiConstant.microBizType.MICRO_TYPE_STORE.name());
			wechatApplyDto.setStoreName(audit.getShopName());
			wechatApplyDto.setStoreAddressCode(shop.getLocationCode().split(",")[2]);
			wechatApplyDto.setStoreHeaderCopy(storeHeaderCopy);
			wechatApplyDto.setStoreIndoorCopy(storeIndoorCopy);
			wechatApplyDto.setCompanyAddress(audit.getAddress());

		}else{
			//非小微企业
			//填充所需参数
			//相关图片上传到易宝服务器
			String certCopyUrl = yeepayCommonService.addFileToYeepay(audit.getBusinessLicense());
			wechatApplyDto.setCertCopy(certCopyUrl);
			wechatApplyDto.setLicenceValidDate(transferDateForIdCard(audit.getValidDate()));
			wechatApplyDto.setCompanyAddress(audit.getOfficeAddress());
		}
		wechatApplyDto.setIdentificationType("IDENTIFICATION_TYPE_IDCARD");
		wechatApplyDto.setIdentificationBackCopy(identificationBackCopy);
		wechatApplyDto.setIdentificationFrontCopy(identificationFrontCopy);
		wechatApplyDto.setApplicantIdCard(audit.getLegalLicenceNo());
		wechatApplyDto.setSubMerchantNo(shop.getMerchantNo());
		wechatApplyDto.setRequestNo(IdUtil.simpleUUID());
		wechatApplyDto.setApplicantName(audit.getLegalPerson());
		wechatApplyDto.setApplicantPhone(audit.getContactMobile());
		wechatApplyDto.setReportFee("XIANXIA");
		wechatApplyDto.setIdentificationValidDate(transferDateForIdCard(audit.getValidDate()));
		return wechatApplyDto;
	}

	/**
	 * 2004年12月23日至2004年12月23日 ->>>>>>> ["2018-09-01","2018-09-01"]
	 *
	 */
	private static String transferDateForlicence(String date){
		if (StringUtil.isBlank(date)) {
			return null;
		}
		String[] dates = date.split("至");
		List<String> dateStr = new ArrayList<>(4);
		Arrays.stream(dates).forEach(item -> {
			dateStr.add(Objects.equals("长期",item)? "forever": DateUtil.parse(item).toString("yyyy-MM-dd"));
		});
		return JSON.toJSONString(dateStr);
	}

	/**
	 * 20171025-20271025 ->>>>>>> ["2018-09-01","2018-09-01"]
	 *
	 */
	public static String transferDateForIdCard(String date){
		if (StringUtil.isBlank(date)) {
			return null;
		}
		String[] dates = date.split("-");
		List<String> dateStr = new ArrayList<>(4);
		Arrays.stream(dates).forEach(item -> {
			dateStr.add( DateUtil.parse(item).toString("yyyy-MM-dd"));
		});
		return JSON.toJSONString(dateStr);
	}

}
