package org.springblade.finance.controller;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.finance.dto.ParamPushYksyt;
import org.springblade.finance.entity.ChannelSpidView;
import org.springblade.finance.entity.DealUserAccounts;
import org.springblade.finance.entity.FinVippoolMonthDetail;
import org.springblade.finance.entity.YksytAccount;
import org.springblade.finance.entity.YksytAccountView;
import org.springblade.finance.entity.YksytBackFile;
import org.springblade.finance.entity.YksytChannels;
import org.springblade.finance.entity.YksytFinanceBillAudit;
import org.springblade.finance.entity.YksytFinanceBillAuditUser;
import org.springblade.finance.enums.AuditStatusEnum;
import org.springblade.finance.enums.PartnerInformationEnum;
import org.springblade.finance.service.ChannelSpidViewService;
import org.springblade.finance.service.DealUserAccountsService;
import org.springblade.finance.service.IFinVippoolMonthDetailService;
import org.springblade.finance.service.IYksytAccountService;
import org.springblade.finance.service.IYksytBackFileService;
import org.springblade.finance.service.IYksytChannelsService;
import org.springblade.finance.service.IYksytFinanceBillAuditService;
import org.springblade.finance.service.IYksytFinanceBillAuditUserService;
import org.springblade.finance.util.ChineseYuanUtil;
import org.springblade.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 结算单审核表 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2022-04-07
 */
@RestController
@RequestMapping("finance/yksytBillAudit")
@Api(value = "推送审核表", tags = "推送审核表")
@Slf4j
public class YksytFinanceBillAuditController {


	@Autowired
	private UserClient userService;

	@Autowired
	private IYksytChannelsService yksytChannelsService;

	@Autowired
	private ChannelSpidViewService channelSpidViewService;

	@Autowired
	private IYksytFinanceBillAuditService yksytFinanceBillAuditService;

	@Autowired
	private IYksytFinanceBillAuditUserService yksytFinanceBillAuditUserService;

	@Autowired
	private IYksytBackFileService yksytBackFileService;

	@Autowired
	private IYksytAccountService yksytAccountService;

	@Autowired
	private DealUserAccountsService dealUserAccountsService;

	@Autowired
	private IFinVippoolMonthDetailService finVippoolMonthDetailService;

	/**
	 * 推送结算单
	 * @param paramPush
	 * @return
	 */
	@PostMapping("/add")
	@ApiOperation(value = "推送优酷收银台账单")
	public R<String> add(@RequestBody ParamPushYksyt paramPush){
		LambdaQueryWrapper<YksytFinanceBillAudit> queryWrapper = Wrappers.<YksytFinanceBillAudit>lambdaQuery()
			.eq(YksytFinanceBillAudit::getSid, paramPush.getSid())
			.ne(YksytFinanceBillAudit::getAuditStatus, AuditStatusEnum.fin_cancel.getValue());
		int count = yksytFinanceBillAuditService.count(queryWrapper);
		if(count > 0) {
			return R.fail("结算单已推送，不能重复操作。");
		}

		YksytFinanceBillAudit drat = new YksytFinanceBillAudit();
		drat.setSid(paramPush.getSid());
		drat.setCreateTime(new Date());
		drat.setCreateByUserId(SecureUtil.getUserId());
		drat.setCreateByName(SecureUtil.getNickName());
		if(paramPush.getUserList() != null && !paramPush.getUserList().isEmpty()) {
			drat.setAuditStatus(AuditStatusEnum.wait_check.getValue());
		}else {
			drat.setAuditStatus(AuditStatusEnum.wait_upload.getValue());
		}
		boolean ret = yksytFinanceBillAuditService.save(drat);
		if(ret) {

			List<YksytFinanceBillAuditUser> userList = new ArrayList<YksytFinanceBillAuditUser>();
			userList.add(new YksytFinanceBillAuditUser(drat.getAid(), SecureUtil.getUserId(), SecureUtil.getNickName(), new Date(), 1));
			if(paramPush.getUserList() != null && !paramPush.getUserList().isEmpty()) {
				paramPush.getUserList().forEach(f -> {
					f.setAid(drat.getAid());
					if(f.getUserId() == 1394115436887109634L){
						f.setCheckStatus(1);
						f.setCheckTime(new Date());
					}else {
						f.setCheckStatus(0);
					}
				});
				userList.addAll(paramPush.getUserList());
			}
			List<YksytFinanceBillAuditUser> list = sysUser(userList);
			yksytFinanceBillAuditUserService.saveBatch(list);

			int num = yksytFinanceBillAuditUserService.count(Wrappers.<YksytFinanceBillAuditUser>lambdaQuery().eq(YksytFinanceBillAuditUser::getAid, drat.getAid()).eq(YksytFinanceBillAuditUser::getCheckStatus, 0));
			if(num <= 0) {
				YksytFinanceBillAudit entity = new YksytFinanceBillAudit();
				entity.setAid(Long.valueOf(drat.getAid()));
				entity.setAuditStatus(AuditStatusEnum.wait_upload.getValue());
				yksytFinanceBillAuditService.updateById(entity);
			}

			YksytAccount one = yksytAccountService.getOne(new LambdaQueryWrapper<YksytAccount>()
				.eq(YksytAccount::getSid, paramPush.getSid())
			);
			if(one != null){
				one.setAllowPush(2);
				yksytAccountService.update(one,new LambdaUpdateWrapper<YksytAccount>().eq(YksytAccount::getSid,paramPush.getSid()));
			}
		}
		return R.status(ret);
	}


	/**
	 * 审核排序
	 * @param list
	 * @return
	 */
	private List<YksytFinanceBillAuditUser> sysUser(List<YksytFinanceBillAuditUser> list ){
		for (YksytFinanceBillAuditUser financeBillAuditUser : list) {
			UserModel byId = userService.getById(financeBillAuditUser.getUserId());
			financeBillAuditUser.setPriority(byId.getAuditLevel());
		}
		return list;
	}


//	@ApiOperation(value = "审核人列表查询")
//	@ApiOperationSupport(order = 1)
//	@GetMapping("/checkUserList")
//	public List<UserVO> userList(){
//		//查询前100个用户
//		IPage<User> pageResult = userService.selectUserPage(new Page<User>(1, 100), new User(), Long.parseLong("1515879365306576897"), null);
//		return UserWrapper.build().listVO(pageResult != null && pageResult.getRecords() != null ? pageResult.getRecords() : new ArrayList<User>());
//	}

	@ApiOperation(value = "审核人列表查询")
	@ApiOperationSupport(order = 1)
	@GetMapping("/checkUserList")
	public List<UserModel> userList(String deptId){
		return userService.listByDeptId(Long.parseLong("1515879365306576897"));
	}


	/**
	 * @return
	 */
	@GetMapping("/list")
	@ApiOperation(value = "分页查询")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "dealUserIds", value = "结算用户ID，逗号隔开。全部渠道传空或者不传递", required = false),
		@ApiImplicitParam(name = "queryDate", value = "查询日期(格式：yyyy-MM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "auditStatus", value = "结算单状态", required = false),
		@ApiImplicitParam(name = "checkUserId", value = "审核人员ID", required = false),
		@ApiImplicitParam(name = "checkStatus", value = "审核状态(1-已审核/0-待审核)", required = false)
	})
	public R<IPage<YksytFinanceBillAudit>> list(String[] dealUserIds,
										   String queryDate, Integer auditStatus,
										   Long checkUserId, Integer checkStatus, Query query){
		QueryWrapper<YksytFinanceBillAudit> queryWrapper = Wrappers.<YksytFinanceBillAudit>query();
		queryWrapper.ne("ya.DEAL_TYPE",2);
		if(dealUserIds != null && dealUserIds.length > 0) {
			List<String> strings = Arrays.asList(dealUserIds);
			List<String> collect = null;
			if(strings != null && strings.size() > 0){
				QueryWrapper<DealUserAccounts> dealQueryWrapper = new QueryWrapper<DealUserAccounts>();
				dealQueryWrapper.select("DEAL_ACCOUNT_ID").isNotNull("DEAL_ACCOUNT_ID");
				dealQueryWrapper.in("DEAL_USERID",strings);
				List<DealUserAccounts> dealList = dealUserAccountsService.list(dealQueryWrapper);
				collect = dealList.stream().map(DealUserAccounts::getDealAccountId).collect(Collectors.toList());
			}
			queryWrapper.in("ya.DEAL_ACCOUNT_ID", collect);
		}

		if(!StringUtil.isEmpty(queryDate)) {
			queryWrapper.eq("ya.THEMONTH", queryDate.replace("-", ""));
		}
		if(auditStatus != null) {
			queryWrapper.eq("yfba.AUDITSTATUS", auditStatus);
		}
		if(checkUserId != null) {
			queryWrapper.eq("yfbau.USERID", checkUserId);
		}
		if(checkStatus != null) {
			queryWrapper.eq("yfbau.CHECKSTATUS", checkStatus);
		}
		queryWrapper.orderByDesc("yfba.AID");
		Page<YksytFinanceBillAudit> page = new Page<>(Func.toInt(query.getCurrent(), 1), Func.toInt(query.getSize(), 10));
		//没有查询条件
		List<Long> aidList = yksytFinanceBillAuditService.customAidList(page, queryWrapper);

		IPage<YksytFinanceBillAudit> customPage = new Page<YksytFinanceBillAudit>(Func.toInt(query.getCurrent(), 1), Func.toInt(query.getSize(), 10));
		if(aidList != null && !aidList.isEmpty()) {
			customPage.setTotal(yksytFinanceBillAuditService.customCount(queryWrapper));
			List<YksytFinanceBillAudit> custom = yksytFinanceBillAuditService.customList(Wrappers.<YksytFinanceBillAudit>query().in("yfba.AID", aidList));
			for (YksytFinanceBillAudit yksytFinanceBillAudit : custom) {
				YksytAccountView yksytAccount = yksytFinanceBillAudit.getYksytAccount();
				String convert = "";
				if(yksytAccount.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).compareTo(BigDecimal.ZERO) < 0){
					//负数金额
					convert = "负数"+ChineseYuanUtil.convert(yksytAccount.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(-1)).toString());
				}else {
					convert = ChineseYuanUtil.convert(yksytAccount.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
				}
				yksytAccount.setConvert(convert);
				//回传文件列表
				List<YksytBackFile> backFiles = yksytBackFileService.list(new LambdaQueryWrapper<YksytBackFile>()
					.eq(YksytBackFile::getAid, yksytFinanceBillAudit.getAid())
					.eq(YksytBackFile::getIsDelete, 0)
					.orderByDesc(YksytBackFile::getUploadTime)
				);
				if(backFiles != null && backFiles.size() > 0){
					yksytFinanceBillAudit.setFid(backFiles.get(0).getFid().toString());
					yksytFinanceBillAudit.setUploadFileName(backFiles.get(0).getUploadFileName());
					yksytFinanceBillAudit.setUploadFileUri(backFiles.get(0).getUploadFileUri());
					yksytFinanceBillAudit.setUploadTime(backFiles.get(0).getUploadTime());
				}

				//会员权益列表
				List<FinVippoolMonthDetail> list = null;
				if(yksytAccount != null && StringUtil.isNotBlank(yksytAccount.getChannelName())){
					list = finVippoolMonthDetailService.list(new LambdaQueryWrapper<FinVippoolMonthDetail>()
						.eq(FinVippoolMonthDetail::getCpShortname,yksytAccount.getChannelName())
						.eq(FinVippoolMonthDetail::getThemonth,yksytAccount.getThemonth())
					);
				}

				if(list != null && list.size() > 0){
					yksytAccount.setVipList(list);
				}

				/*if(channel != null) {
					yksytAccount.setChannelName(channel.getChannelname());
					yksytAccount.setCompany(channel.getCompany());
				}*/
				ChannelSpidView spidView = channelSpidViewService.getOne(new LambdaQueryWrapper<ChannelSpidView>()
					.eq(ChannelSpidView::getChannelId, yksytAccount.getChannelId())
					.eq(ChannelSpidView::getSpid, yksytAccount.getSpid())
				);
				if(spidView != null) {
					yksytAccount.setSpName(spidView.getSpname());
				}
			}
			customPage.setRecords(custom);

			if(customPage != null && customPage.getRecords() != null) {
				customPage.getRecords().forEach(f -> {
					StringBuffer userName = new StringBuffer();
					for (YksytFinanceBillAuditUser financeBillAuditUser : f.getUserList()) {
						if(financeBillAuditUser.getUserId() == 1394115436887109634L){
							financeBillAuditUser.setUserName("");
							continue;
						}
						userName.append(financeBillAuditUser.getUserName()).append(",");
					}
					f.setUserNames(userName.deleteCharAt(userName.length()-1).toString());
				});
			}
		}
		return R.data(customPage);
	}


	@GetMapping("/interestList")
	@ApiOperation(value = "推送审核表分页查询-会员权益分类单独数据")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "company", value = "公司名称", required = false),
		@ApiImplicitParam(name = "queryDate", value = "查询日期(格式：yyyy-MM)", dataType = "string", required = false),
		@ApiImplicitParam(name = "auditStatus", value = "结算单状态", required = false),
		@ApiImplicitParam(name = "checkUserId", value = "审核人员ID", required = false),
		@ApiImplicitParam(name = "checkStatus", value = "审核状态(1-已审核/0-待审核)", required = false)
	})
	public R<IPage<YksytFinanceBillAudit>> interestList(String company,
										   String queryDate, Integer auditStatus,
										   Long checkUserId, Integer checkStatus, Query query){
		QueryWrapper<YksytFinanceBillAudit> queryWrapper = Wrappers.<YksytFinanceBillAudit>query();
		queryWrapper.eq("ya.DEAL_TYPE",2);
		if(!StringUtil.isEmpty(company)) {
			List<YksytChannels> companyList = null;
			if(company.contains(",")){
				String[] split = company.split(",");
				companyList = yksytChannelsService.list(new LambdaQueryWrapper<YksytChannels>()
					.in(YksytChannels::getCompany, split)
				);
			}else {
				companyList = yksytChannelsService.list(new LambdaQueryWrapper<YksytChannels>()
					.eq(YksytChannels::getCompany, company)
				);
			}
			if(companyList != null && companyList.size() == 1){
				queryWrapper.eq("ya.CHANNELID", companyList.get(0).getChannelid());
			}else if(companyList != null && companyList.size() > 1){
				List<String> collect = companyList.stream().map(YksytChannels::getChannelid).collect(Collectors.toList());
				String[] channels = collect.stream().toArray(String[]::new);
				queryWrapper.in("ya.CHANNELID", channels);
			}
		}
		if(!StringUtil.isEmpty(queryDate)) {
			queryWrapper.eq("ya.THEMONTH", queryDate.replace("-", ""));
		}
		if(auditStatus != null) {
			queryWrapper.eq("yfba.AUDITSTATUS", auditStatus);
		}
		if(checkUserId != null) {
			queryWrapper.eq("yfbau.USERID", checkUserId);
		}
		if(checkStatus != null) {
			queryWrapper.eq("yfbau.CHECKSTATUS", checkStatus);
		}
		queryWrapper.orderByDesc("yfba.AID");
		Page<YksytFinanceBillAudit> page = new Page<>(Func.toInt(query.getCurrent(), 1), Func.toInt(query.getSize(), 10));
		//没有查询条件
		List<Long> aidList = yksytFinanceBillAuditService.customAidList(page, queryWrapper);

		IPage<YksytFinanceBillAudit> customPage = new Page<YksytFinanceBillAudit>(Func.toInt(query.getCurrent(), 1), Func.toInt(query.getSize(), 10));
		if(aidList != null && !aidList.isEmpty()) {
			customPage.setTotal(yksytFinanceBillAuditService.customCount(queryWrapper));
			List<YksytFinanceBillAudit> custom = yksytFinanceBillAuditService.customList(Wrappers.<YksytFinanceBillAudit>query().in("yfba.AID", aidList));
			for (YksytFinanceBillAudit yksytFinanceBillAudit : custom) {
				YksytAccountView yksytAccount = yksytFinanceBillAudit.getYksytAccount();
				String convert = "";
				if(yksytAccount.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).compareTo(BigDecimal.ZERO) < 0){
					//负数金额
					convert = "负数"+ChineseYuanUtil.convert(yksytAccount.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(-1)).toString());
				}else {
					convert = ChineseYuanUtil.convert(yksytAccount.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
				}
				yksytAccount.setConvert(convert);

				//回传文件列表
				List<YksytBackFile> backFiles = yksytBackFileService.list(new LambdaQueryWrapper<YksytBackFile>()
					.eq(YksytBackFile::getAid, yksytFinanceBillAudit.getAid())
					.eq(YksytBackFile::getIsDelete, 0)
					.orderByDesc(YksytBackFile::getUploadTime)
				);
				if(backFiles != null && backFiles.size() > 0){
					yksytFinanceBillAudit.setFid(backFiles.get(0).getFid().toString());
					yksytFinanceBillAudit.setUploadFileName(backFiles.get(0).getUploadFileName());
					yksytFinanceBillAudit.setUploadFileUri(backFiles.get(0).getUploadFileUri());
					yksytFinanceBillAudit.setUploadTime(backFiles.get(0).getUploadTime());
				}

				YksytChannels channel = yksytChannelsService.getOne(new LambdaQueryWrapper<YksytChannels>()
					.eq(YksytChannels::getChannelid, yksytAccount.getChannelId())
				);

				//会员权益列表
				List<FinVippoolMonthDetail> list = null;
				if(StringUtils.isNotBlank(channel.getChannelname())){
					list = finVippoolMonthDetailService.list(new LambdaQueryWrapper<FinVippoolMonthDetail>()
						.eq(FinVippoolMonthDetail::getChannelid,channel.getChannelid())
						.eq(FinVippoolMonthDetail::getThemonth,yksytAccount.getThemonth())
					);
				}

				if(list != null && list.size() > 0){
					yksytAccount.setVipList(list);
				}

				if(channel != null) {
					yksytAccount.setChannelName(channel.getChannelname());
					yksytAccount.setCompany(channel.getCompany());
					PartnerInformationEnum[] values = PartnerInformationEnum.values();
					for (PartnerInformationEnum value : values) {
						if(value.getPartnerName().equals(channel.getCompany())){
							yksytAccount.setBankName(value.getBankName());
							yksytAccount.setBankCode(value.getBankCode());
						}
					}
				}
				ChannelSpidView spidView = channelSpidViewService.getOne(new LambdaQueryWrapper<ChannelSpidView>()
					.eq(ChannelSpidView::getChannelId, yksytAccount.getChannelId())
					.eq(ChannelSpidView::getSpid, yksytAccount.getSpid())
				);
				if(spidView != null) {
					yksytAccount.setSpName(spidView.getSpname());
				}
			}
			customPage.setRecords(custom);

			if(customPage != null && customPage.getRecords() != null) {
				customPage.getRecords().forEach(f -> {
					StringBuffer userName = new StringBuffer();
					for (YksytFinanceBillAuditUser financeBillAuditUser : f.getUserList()) {
						if(financeBillAuditUser.getUserId() == 1394115436887109634L){
							financeBillAuditUser.setUserName("");
							continue;
						}
						userName.append(financeBillAuditUser.getUserName()).append(",");
					}
					f.setUserNames(userName.deleteCharAt(userName.length()-1).toString());
				});
			}
		}
		return R.data(customPage);
	}

	/**
	 * 数量查询
	 * @return
	 */
	@GetMapping("/dataCount")
	@ApiOperation(value = "数量查询")
	@ApiOperationSupport(order = 3)
	public R<JSONObject> dateCount(){
		JSONObject result = new JSONObject();
		int uploadCount = yksytFinanceBillAuditService.count(Wrappers.<YksytFinanceBillAudit>lambdaQuery().eq(YksytFinanceBillAudit::getAuditStatus, AuditStatusEnum.fin_upload.getValue()));
		int rejectCount = yksytFinanceBillAuditService.count(Wrappers.<YksytFinanceBillAudit>lambdaQuery().eq(YksytFinanceBillAudit::getAuditStatus, AuditStatusEnum.fin_reject.getValue()));
		int waitMeCount = yksytFinanceBillAuditUserService.count(Wrappers.<YksytFinanceBillAuditUser>lambdaQuery().eq(YksytFinanceBillAuditUser::getUserId, SecureUtil.getUserId()).eq(YksytFinanceBillAuditUser::getCheckStatus, 0));
		result.put("uploadCount", uploadCount);
		result.put("rejectCount", rejectCount);
		result.put("waitMeCount", waitMeCount);
		return R.data(result);
	}


	@PostMapping("/reject")
	@ApiOperation(value = "驳回接口")
	public R<String> reject(@RequestParam Long aid, String rejectReason){
		YksytFinanceBillAudit entity = new YksytFinanceBillAudit();
		entity.setAid(Long.valueOf(aid));
		entity.setRejectReason(rejectReason);
		entity.setAuditStatus(AuditStatusEnum.fin_reject.getValue());
		if(yksytFinanceBillAuditService.updateById(entity)){
			YksytAccount one = yksytAccountService.getOne(new LambdaQueryWrapper<YksytAccount>()
				.eq(YksytAccount::getSid, entity.getSid())
			);
			if(one != null){
				one.setAllowPush(1);
				yksytAccountService.update(one,new LambdaUpdateWrapper<YksytAccount>().eq(YksytAccount::getSid,entity.getSid()));
			}
			return R.status(true);
		}
		return R.status(false);
	}

	@PostMapping("/cancel")
	@ApiOperation(value = "作废接口")
	@ApiOperationSupport(order = 6)
	public R<String> cancel(@RequestParam Long aid){
		YksytFinanceBillAudit financeBillAudit = yksytFinanceBillAuditService.getById(aid);
		if(financeBillAudit == null || financeBillAudit.getCreateByUserId() != SecureUtil.getUserId().longValue()) {
			return R.fail("只有推送者才能作废");
		}
		YksytFinanceBillAudit entity = new YksytFinanceBillAudit();
		entity.setAid(Long.valueOf(aid));
		entity.setAuditStatus(AuditStatusEnum.fin_cancel.getValue());
		boolean uptRet = yksytFinanceBillAuditService.updateById(entity);
		if(uptRet) { //作废后，设置全部为审核状态。
			LambdaUpdateWrapper<YksytFinanceBillAuditUser> updateWrapper = Wrappers.<YksytFinanceBillAuditUser>lambdaUpdate()
				.set(YksytFinanceBillAuditUser::getCheckStatus, 1).eq(YksytFinanceBillAuditUser::getAid, aid);
			yksytFinanceBillAuditUserService.update(updateWrapper);
		}

		YksytAccount one = yksytAccountService.getOne(new LambdaQueryWrapper<YksytAccount>()
			.eq(YksytAccount::getSid, financeBillAudit.getSid())
		);
		if(one != null){
			one.setAllowPush(1);
			yksytAccountService.update(one,new LambdaUpdateWrapper<YksytAccount>().eq(YksytAccount::getSid,financeBillAudit.getSid()));
		}
		return R.status(uptRet);
	}


	@PostMapping("/verify")
	@ApiOperation(value = "审核接口")
	public R<String> verify(@RequestParam Long aid){
		List<YksytFinanceBillAuditUser> userList = yksytFinanceBillAuditUserService.list(Wrappers.<YksytFinanceBillAuditUser>lambdaQuery().eq(YksytFinanceBillAuditUser::getAid, aid));
		if(!userList.stream().anyMatch(f -> f.getUserId().longValue() == SecureUtil.getUserId())) {
			return R.fail("您没有审核权限");
		}
		if(userList.stream().anyMatch(f -> f.getUserId().longValue() == SecureUtil.getUserId() && f.getCheckStatus() == 1)){
			return R.fail("您已经审核通过");
		}

		List<YksytFinanceBillAuditUser> collect = userList.stream()
			.filter(item -> item.getPriority() != 0 && item.getCheckStatus() == 0).collect(Collectors.toList())
			.stream()
			.sorted(Comparator.comparing(YksytFinanceBillAuditUser::getPriority)).collect(Collectors.toList());

		log.info("审核人员列表 = {}",collect.toString());

		List<YksytFinanceBillAuditUser> filterList = collect.stream().filter(item -> item.getUserId().equals(SecureUtil.getUserId())).collect(Collectors.toList());
		log.info("除该人员外，其他同等级审核人需要去除 = {}",collect.toString());

		collect.removeIf(obj -> !obj.getUserId().equals(SecureUtil.getUserId()) && filterList.get(0).getPriority() == obj.getPriority());
		log.info("过滤后审核人员列表 = {}",collect.toString());

		if(collect.size() > 1){
			for (int i = 0; i < collect.size(); i++) {
				if(collect.get(i).getUserId().equals(SecureUtil.getUserId())){
					log.info("当前审核用户 = {}",collect.get(i).getUserId());
					if(collect.get(i).getPriority() == 1){
						log.info("第一审核人，无需判断");
						break;
					}
					if(i >= 1){
						if(collect.get(i).getPriority() == collect.get(i-1).getPriority()){
							break;
						}else if(collect.get(i).getPriority().longValue() > collect.get(i-1).getPriority().longValue()){
							if(collect.get(i-1).getCheckStatus() == 1){
								break;
							}else {
								return R.fail("上级审核人" + collect.get(i-1).getUserName()+ "还未审核");
							}
						}
					}
				}
			}
		}

		YksytFinanceBillAuditUser financeBillAuditUser = userList.stream().filter(f -> f.getUserId().longValue() == SecureUtil.getUserId() && f.getCheckStatus() == 0).findAny().get();
		financeBillAuditUser.setCheckStatus(1);
		financeBillAuditUser.setCheckTime(new Date());
		boolean ret = yksytFinanceBillAuditUserService.updateById(financeBillAuditUser);

		//判断是否所有人都已审核完成
		int count = yksytFinanceBillAuditUserService.count(Wrappers.<YksytFinanceBillAuditUser>lambdaQuery().eq(YksytFinanceBillAuditUser::getAid, aid).eq(YksytFinanceBillAuditUser::getCheckStatus, 0));
		if(count <= 0) {
			YksytFinanceBillAudit entity = new YksytFinanceBillAudit();
			entity.setAid(Long.valueOf(aid));
			entity.setAuditStatus(AuditStatusEnum.wait_upload.getValue());
			yksytFinanceBillAuditService.updateById(entity);
		}
		return R.status(ret);
	}


}

