/*
 *      Copyright (c) 2018-2028, Chill Zhuang 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 dreamlu.net 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: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.guosen.bussinessuserinfo.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.common.constant.SystemConstant;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.guosen.bussiness.entity.Bussiness;
import org.springblade.modules.guosen.bussiness.excel.DebitRequestExcel;
import org.springblade.modules.guosen.bussiness.excel.WithdrawRequestExcel;
import org.springblade.modules.guosen.bussiness.service.IBussinessService;
import org.springblade.modules.guosen.bussinessInfo.entity.BussinessInfo;
import org.springblade.modules.guosen.bussinessInfo.service.IBussinessInfoService;
import org.springblade.modules.guosen.bussinessuserinfo.entity.BussinessUserInfo;
import org.springblade.modules.guosen.bussinessuserinfo.vo.BussinessUserInfoVO;
import org.springblade.modules.guosen.bussinessuserinfo.mapper.BussinessUserInfoMapper;
import org.springblade.modules.guosen.bussinessuserinfo.service.IBussinessUserInfoService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.guosen.debtDaliyStat.entity.BusinessDeptDaliyStat;
import org.springblade.modules.guosen.debtDaliyStat.service.IBusinessDeptDaliyStatService;
import org.springblade.modules.obs.service.ObsService;
import org.springblade.yeePay.entity.WithdrawCardBindDto;
import org.springblade.yeePay.entity.WithdrawCardModifyDto;
import org.springblade.yeePay.service.YeePayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-10-11
 */
@Service
public class BussinessUserInfoServiceImpl extends BaseServiceImpl<BussinessUserInfoMapper, BussinessUserInfo> implements IBussinessUserInfoService {

	@Autowired
	private YeePayService yeePayService;

	@Override
	public IPage<BussinessUserInfoVO> selectBussinessUserInfoPage(IPage<BussinessUserInfoVO> page, BussinessUserInfoVO bussinessUserInfo) {
		return page.setRecords(baseMapper.selectBussinessUserInfoPage(page, bussinessUserInfo));
	}

	@Override
	public R editUserInfo(BussinessUserInfo bussinessUserInfo) {
		Long id = bussinessUserInfo.getId();
		if(id == null){ //新增
			BussinessUserInfo dbUserInfo = this.getByNameCardBank(bussinessUserInfo);
			if(dbUserInfo != null){
				return R.fail("已存在姓名、证件号、银行卡号相同的用户");
			}else{
				boolean save = this.save(bussinessUserInfo);
				return R.status(save);
			}
		}else{ //更新
			BussinessUserInfo dbUserInfo = this.getById(id);
			if(dbUserInfo == null){
				return R.fail("用户不存在");
			}else{
				Integer registerStatus = dbUserInfo.getRegisterStatus();
				if(registerStatus != null &&
						(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()
								|| registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUBMIT_SUCCESS.getValue())
						|| registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_AUDIT.getValue()){
					return R.fail("该用户已完成审核或审核中，请勿修改");
				}
				boolean update = this.updateById(bussinessUserInfo);
				return R.status(true);
			}
		}
	}

	@Override
	public BussinessUserInfo getByNameCardBank(BussinessUserInfo bussinessUserInfo){
		LambdaQueryWrapper<BussinessUserInfo> lambda = new LambdaQueryWrapper<>();
		lambda.eq(StringUtil.isNotBlank(bussinessUserInfo.getUserName()), BussinessUserInfo::getUserName, bussinessUserInfo.getUserName());
		lambda.eq(StringUtil.isNotBlank(bussinessUserInfo.getBankCardNo()), BussinessUserInfo::getBankCardNo, bussinessUserInfo.getBankCardNo());
		lambda.eq(StringUtil.isNotBlank(bussinessUserInfo.getUserLicenceNo()), BussinessUserInfo::getUserLicenceNo, bussinessUserInfo.getUserLicenceNo());
		return baseMapper.selectOne(lambda);
	}

	@Override
	public BussinessUserInfo getByMerchantNo(String merchantNo) {
		LambdaQueryWrapper<BussinessUserInfo> lambda = new LambdaQueryWrapper<>();
		lambda.eq(BussinessUserInfo::getMerchantNo, merchantNo);
		return baseMapper.selectOne(lambda);
	}

	@Override
	public R withdrawCardQuery(Long userInfoId) {
		BussinessUserInfo userInfo = this.getById(userInfoId);
		Assert.notNull(userInfo, "用户不存在");
		Integer registerStatus = userInfo.getRegisterStatus();
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			R result = this.yeePayService.withdrawCardQuery(userInfo.getMerchantNo());
			return R.data(result.getData());
		}else{
			return R.fail("用户未完成进件");
		}
	}

	@Override
	public R withdrawCardBind(BussinessUserInfo userInfo) {
		BussinessUserInfo dbUserInfo = this.getById(userInfo.getId());
		Integer registerStatus = dbUserInfo.getRegisterStatus();
		if(registerStatus.intValue() != SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("用户未完成进件");
		}
		Assert.notEmpty(userInfo.getBankCardNo(), "银行卡号不能为空");
		dbUserInfo.setBankCode(userInfo.getBankCode());
		dbUserInfo.setBankCardNo(userInfo.getBankCardNo());
		this.updateById(dbUserInfo);
		//发起修改提现卡请求
		WithdrawCardBindDto withdrawCardBindDto = WithdrawCardBindDto.builder()
						.bankCardType(userInfo.getBankAccountType())
						.accountNo(dbUserInfo.getBankCardNo())
						.merchantNo(dbUserInfo.getMerchantNo())
						.bankCode(dbUserInfo.getBankCode())
						.build();
		R result = yeePayService.withdrawCardBind(withdrawCardBindDto);
		JSONObject resultData = JSONUtil.parseObj(result.getData());
		String returnCode = resultData.getStr("returnCode");
		String returnMsg = resultData.getStr("returnMsg");
		if(returnCode.equals("UA00000")){
			return R.status(true);
		}else{
			return R.fail(returnMsg);
		}
	}

	@Override
	public R withdrawCardModify(BussinessUserInfo userInfo) {
		BussinessUserInfo dbUserInfo = this.getById(userInfo.getId());
		Integer registerStatus = dbUserInfo.getRegisterStatus();
		if(registerStatus.intValue() != SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("用户未完成进件");
		}
		Assert.notEmpty(userInfo.getBankCardNo(), "银行卡号不能为空");
		Assert.notEmpty(userInfo.getBankCode(), "总行编号不能为空");
		if(userInfo.getBankCardNo().equals(dbUserInfo.getBankCardNo()) && userInfo.getBankCode().equals(dbUserInfo.getBankCode())){
			//这里是处理，上次修改提现卡时候，本地保存成功，但是支付平台修改失败，需要重新发起修改，但此时数据库已经更新为最新的提现卡了，所以只需要对支付平台发起请求即可

		}else{
			dbUserInfo.setBankCardNo(userInfo.getBankCardNo());
			dbUserInfo.setBankCode(userInfo.getBankCode());
			boolean update = this.updateById(dbUserInfo);
			if(!update){
				return R.fail("修改失败");
			}
		}
		//发起修改提现卡请求
		WithdrawCardModifyDto withdrawCardModifyDto = WithdrawCardModifyDto.builder()
						.bankCardOperateType("MODIFY")
						.accountNo(dbUserInfo.getBankCardNo())
						.merchantNo(dbUserInfo.getMerchantNo())
						.bankCode(dbUserInfo.getBankCode())
						.build();
		R result = yeePayService.withdrawCardModify(withdrawCardModifyDto);
		JSONObject resultData = JSONUtil.parseObj(result.getData());
		String returnCode = resultData.getStr("returnCode");
		String returnMsg = resultData.getStr("returnMsg");
		if(returnCode.equals("UA00000")){
			return R.status(true);
		}else{
			return R.fail(returnMsg);
		}
	}

	@Override
	public BussinessUserInfo getByNameLicenceNo(String userName, String licenceNo) {
		LambdaQueryWrapper<BussinessUserInfo> lambda = new LambdaQueryWrapper<>();
		lambda.eq(StringUtil.isNotBlank(userName), BussinessUserInfo::getUserName, userName);
		lambda.eq(StringUtil.isNotBlank(licenceNo), BussinessUserInfo::getUserLicenceNo, licenceNo);
		return baseMapper.selectOne(lambda);
	}

}
