package com.qunzhixinxi.hnqz.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qunzhixinxi.hnqz.admin.api.constant.CacheConstants;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.entity.input.SettleNoteStatusOutput;
import com.qunzhixinxi.hnqz.admin.mapper.WmSettleAccountReceiveMapper;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.ding.entity.*;
import com.qunzhixinxi.hnqz.common.ding.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
@AllArgsConstructor
public class WmSettlementServiceImpl implements WmSettlementService {

	private final SysUserService sysUserService;

	private final WmImportUserService importUserService;

	private final WmScorePackageService packageService;

	private final WmScorePackageSettleNoteService noteService;

	private final WmSettleAccountReceiveMapper receiveMapper;

	private final RedisTemplate redisTemplate;

	@Override
	public NotifyResponse confirm(String data) {
		NotifyResponse response = NotifyResponse.success();
		//判断接口类型
		JSONObject dataJson = JSON.parseObject(data);

		String callbackType = dataJson.get("callbackType").toString();
		//灵工认证状态通知
		if (NotifyType.FREELANCES_CHECK.getCode().equals(callbackType)) {
			log.info("灵工认证状态通知结果：{}", data);
			EmployCheckNotifyData notify = JsonUtils.deserializer(data, EmployCheckNotifyData.class);

			List<EmployCheckNotifyDataItem> freelancesResult = notify.getFreelancesResult();

			if (CollectionUtils.isEmpty(freelancesResult)) {
				log.info("灵工认证状态通知结果数据为空：{}", data);
				return response;
			}

			for (EmployCheckNotifyDataItem item : freelancesResult) {
				if(StringUtils.isEmpty(item.getIdCard())){
					log.info("灵工认证当前返回数据异常：{}", item);
					continue;
				}
				if(StringUtils.isEmpty(item.getName())){
					log.info("灵工认证当前返回数据异常：{}", item);
					continue;
				}
				if(StringUtils.isEmpty(item.getMobile())){
					log.info("灵工认证当前返回数据异常：{}", item);
					continue;
				}
				SysUser query = new SysUser();
				query.setRealname(item.getName());
				query.setUsername(item.getMobile());
				query.setIdCardNumber(item.getIdCard());
				List<SysUser> userList = sysUserService.list(Wrappers.query(query));
				if (CollectionUtils.isEmpty(userList)) {
					log.info("用户表灵工认证根据接口返回数据未查询到数据：{}", item);
					continue;
				}
				for (SysUser updateUser : userList) {
					updateUser.setCertRemark(item.getRemark());
					updateUser.setRljCertStatus(item.getStatus());
					sysUserService.updateById(updateUser);
				}


			}
		}
		//结算单发放结果通知

		/**
		 *  新结算
		 */
		if (NotifyType.FREELANCES_PAY.getCode().equals(callbackType)) {
			log.info("结算单发放结果通知：{}", data);
			EmployPayNotifyData notify = JsonUtils.deserializer(data, EmployPayNotifyData.class);

			List<EmployPayNotifyDataItem> freelancesPayResult = notify.getFreelancesPayResult();
			if (CollectionUtils.isEmpty(freelancesPayResult)) {
				log.info("结算单发放结果通知异常：{}{}", "结算明细为空:",data);
				return response;
			}

			String statementNo = notify.getStatementNo();

			WmScorePackageSettleNote queryParam = new WmScorePackageSettleNote();
			queryParam.setSettleNo(statementNo);

			//查询结算单  statementNo
			List<WmScorePackageSettleNote> noteList = noteService.list(Wrappers.query(queryParam));

			if(CollectionUtils.isEmpty(noteList)){
				log.info("结算单发放结果通知异常：{}{}", "结算单号未匹配:",statementNo);
				return response;
			}

			if(noteList.size() != 1){
				log.info("结算单发放结果通知异常：{}{}", "结算单号匹配异常:",statementNo);
				return response;
			}

			WmScorePackageSettleNote note = noteList.get(0);
			WmScorePackageSettleNote updateNote = new WmScorePackageSettleNote();
			updateNote.setId(note.getId());

			for (EmployPayNotifyDataItem item : freelancesPayResult) {
				updateNote.setSettleNoteStatus(item.getSettlementStatus());
				updateNote.setRemark(item.getRemark());
				updateNote.setNotifyTime(LocalDateTime.now());
			}
			noteService.updateById(updateNote);


			/**
			 * 更新结算单状态
			 */
			WmScorePackage wmScorePackage = packageService.getById(note.getPackageId());
			/**
			 * @Modify: start
			 * @Version: v2021.4.16
			 * @Author: ryz
			 * @Date: 2021/4/28
			 *  只更新定量 定额 通用包  证据链不需要更新
			*/
			if("1".equals(wmScorePackage.getPackageType2())){
				WmScorePackage updatePackage = new WmScorePackage();
				updatePackage.setId(wmScorePackage.getId());
				SettleNoteStatusOutput output = noteService.selectSettleNoteStatus(wmScorePackage.getId());
				updatePackage.setSettleStatus(output.toSettleStatus());
				packageService.updateById(updatePackage);
			}


			log.info("结算解锁settleNoteId：{}", note.getId());
			redisTemplate.delete(CacheConstants.SETTLE_PACKAGE_KEY + note.getId());

		}

		//账户到账通知
		if (NotifyType.ACCOUNT_RECEIVE.getCode().equals(callbackType)) {
			log.info("账户到账通知：{}", data);
			EmployRemitNotifyData notify = JsonUtils.deserializer(data, EmployRemitNotifyData.class);
			EmployRemitNotifyDataInfo accountInfo = notify.getAccountInfo();

			WmSettleAccountReceive receive = new WmSettleAccountReceive();
			receive.setAccountName(accountInfo.getAccountName());
			receive.setAccountNo(accountInfo.getAccountNo());
			receive.setAmount(accountInfo.getAmount());
			receive.setBankSerialNo(accountInfo.getBankSerialNo());
			receive.setOpType(accountInfo.getOpType());

			receiveMapper.insert(receive);
		}

		return NotifyResponse.success();
	}
}
