/*
 *      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.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.common.constant.SystemConstant;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.guosen.bussiness.entity.Bussiness;
import org.springblade.modules.guosen.bussiness.service.IBussinessService;
import org.springblade.modules.guosen.bussinessuserinfo.vo.SimpleBussinessUserInfoVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.guosen.bussinessuserinfo.entity.BussinessUserInfo;
import org.springblade.modules.guosen.bussinessuserinfo.vo.BussinessUserInfoVO;
import org.springblade.modules.guosen.bussinessuserinfo.wrapper.BussinessUserInfoWrapper;
import org.springblade.modules.guosen.bussinessuserinfo.service.IBussinessUserInfoService;
import org.springblade.core.boot.ctrl.BladeController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-10-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-bussiness-user-info/bussinessuserinfo")
@Api(value = "", tags = "接口")
public class BussinessUserInfoController extends BladeController {

	private final IBussinessUserInfoService bussinessUserInfoService;
	private final IBussinessService bussinessService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入bussinessUserInfo")
	public R<BussinessUserInfoVO> detail(BussinessUserInfo bussinessUserInfo) {
		BussinessUserInfo detail = bussinessUserInfoService.getOne(Condition.getQueryWrapper(bussinessUserInfo));
		return R.data(BussinessUserInfoWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入bussinessUserInfo")
	public R<IPage<BussinessUserInfoVO>> list(BussinessUserInfo bussinessUserInfo, Query query) {
		BladeUser user = AuthUtil.getUser();
		IPage<BussinessUserInfo> pages = null;
		if(Objects.equals(user.getRoleId(), SystemConstant.BUSSINESS_ROLE_ID)){
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
					.eq(Bussiness::getAccountId, user.getUserId()));
			Assert.notNull(bussiness, "商户不存在");
			pages = this.bussinessUserInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(bussinessUserInfo).lambda()
					.eq(BussinessUserInfo::getBussinessId, bussiness.getId()));
		}else{
			pages = this.bussinessUserInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(bussinessUserInfo));
		}
		return R.data(BussinessUserInfoWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入bussinessUserInfo")
	public R<IPage<BussinessUserInfoVO>> page(BussinessUserInfoVO bussinessUserInfo, Query query) {
		IPage<BussinessUserInfoVO> pages = bussinessUserInfoService.selectBussinessUserInfoPage(Condition.getPage(query), bussinessUserInfo);
		return R.data(pages);
	}

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入bussinessUserInfo")
	public R save(@Valid @RequestBody BussinessUserInfo bussinessUserInfo) {
		return R.status(bussinessUserInfoService.save(bussinessUserInfo));
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入bussinessUserInfo")
	public R update(@Valid @RequestBody BussinessUserInfo bussinessUserInfo) {
		return R.status(bussinessUserInfoService.updateById(bussinessUserInfo));
	}

	/**
	 * 新增或修改 
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入bussinessUserInfo")
	public R submit(@Valid @RequestBody BussinessUserInfo bussinessUserInfo) {
		String userName = bussinessUserInfo.getUserName();
		Assert.notNull(userName, "用户名称不能为空");
		String bankCardNo = bussinessUserInfo.getBankCardNo();
		Assert.notNull(bankCardNo, "用户银行卡号码不能为空");
		String userIdCard = bussinessUserInfo.getUserLicenceNo();
		Assert.notNull(userIdCard, "用户证件号码不能为空");
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
						.eq(Bussiness::getAccountId, user.getUserId()));
		Assert.notNull(bussiness, "当前账号为非采购商");
		Integer registerStatus = bussiness.getRegisterStatus();
		if(registerStatus.intValue() != SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("请先完成商户进件审核");
		}
		String parentMerchantNo = null;
		if(bussiness.getBussinessType().intValue() == SystemConstant.BussinessType.PLATFORM_MERCHANT.getValue()){
			parentMerchantNo = bussiness.getMerchantNo();
			bussinessUserInfo.setRateStrategyId(bussiness.getMicroRateStrategyId());
		}else{
			Bussiness parentBussiness = bussinessService.getById(bussiness.getParentBussinessId());
			parentMerchantNo = parentBussiness.getMerchantNo();
			bussinessUserInfo.setRateStrategyId(parentBussiness.getMicroRateStrategyId());
		}
		bussinessUserInfo.setBussinessId(bussiness.getId());
		bussinessUserInfo.setUserShortName(bussinessUserInfo.getUserName());
		bussinessUserInfo.setUserLicenceType("ID_CARD");
		bussinessUserInfo.setParentMerchantNo(parentMerchantNo);
		R editResult = bussinessUserInfoService.editUserInfo(bussinessUserInfo);
		return editResult;
	}

	
	/**
	 * 删除 
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(bussinessUserInfoService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 根据条件下拉获取采购商list
	 * @param bussinessUserInfo
	 * @return
	 */
	@GetMapping(value = "/listUserInfo")
	@ApiOperationSupport(order = 8)
	public R<List<SimpleBussinessUserInfoVO>> listBussinessInfo(BussinessUserInfo bussinessUserInfo){
		LambdaQueryWrapper<BussinessUserInfo> lambda = new LambdaQueryWrapper<>();
		if(StringUtil.isNotBlank(bussinessUserInfo.getUserName())){
			lambda.like(BussinessUserInfo::getUserName, bussinessUserInfo.getUserName());
		}
		if(bussinessUserInfo.getRegisterStatus() != null){
			lambda.eq(BussinessUserInfo::getRegisterStatus, bussinessUserInfo.getRegisterStatus());
		}
		if(bussinessUserInfo.getId() != null){
			lambda.eq(BussinessUserInfo::getId, bussinessUserInfo);
		}
		BladeUser user = AuthUtil.getUser();
		if(user.getRoleName().equals("商户")){
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
					.eq(Bussiness::getAccountId, user.getUserId()));
			Assert.notNull(bussiness, "商户不存在");
			lambda.eq(BussinessUserInfo::getBussinessId, bussiness.getId());
		}else{
			lambda.eq(bussinessUserInfo.getBussinessId() != null, BussinessUserInfo::getBussinessId, bussinessUserInfo.getBussinessId());
		}
		List<BussinessUserInfo> list = this.bussinessUserInfoService.list(lambda);
		List<SimpleBussinessUserInfoVO> voList = list.stream()
				.map(item -> {
					SimpleBussinessUserInfoVO vo = new SimpleBussinessUserInfoVO();
					vo.setId(item.getId());
					vo.setUserName(item.getUserName());
					vo.setMerchantNo(item.getMerchantNo());
					return vo;
				}).collect(Collectors.toList());
		return R.data(voList);
	}

	/**
	 * 修改
	 * @param userInfo
	 * @return
	 */
	@GetMapping(value = "/withdrawCardQuery")
	@ApiOperationSupport(order = 9)
	public R withdrawCardQuery(BussinessUserInfo userInfo){
		R result = this.bussinessUserInfoService.withdrawCardQuery(userInfo.getId());
		return result;
	}

	/**
	 * 添加
	 * @param userInfo
	 * @return
	 */
	@PostMapping(value = "/withdrawCardBind")
	@ApiOperationSupport(order = 10)
	public R withdrawCardBind(@RequestBody BussinessUserInfo userInfo){
		R result = this.bussinessUserInfoService.withdrawCardBind(userInfo);
		return result;
	}

	/**
	 * 修改
	 * @param userInfo
	 * @return
	 */
	@PostMapping(value = "/withdrawCardModify")
	@ApiOperationSupport(order = 11)
	public R withdrawCardModify(@RequestBody BussinessUserInfo userInfo){
		R result = this.bussinessUserInfoService.withdrawCardModify(userInfo);
		return result;
	}

	/**
	 * 查询商户账户余额
	 */
	@GetMapping("/queryUserBalance")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "小微商户余额查询")
	public R<BigDecimal> queryBalance(@RequestParam(value = "userInfoId", required = false) Long userInfoId) {
		BussinessUserInfo userInfo = this.bussinessUserInfoService.getById(userInfoId);
		org.springframework.util.Assert.notNull(userInfo, "商户不存在");
		BladeUser user = AuthUtil.getUser();
		if(user.getRoleName().equals("财务管理") || user.getRoleName().equals("administrator")){ //入驻商查询余额
			if(StringUtil.isNoneBlank(userInfo.getMerchantNo()) && userInfo.getRegisterStatus().intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
				R<BigDecimal> newRemainR = bussinessService.queryBalance(userInfo.getMerchantNo());
				return newRemainR;
			}else{
				return R.fail("请先完成商户进件");
			}
		}else{
			return R.fail("暂无权限");
		}
	}

}
