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

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.common.utils.MoneyDesUtil;
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.vo.SimpleBussinessVO;
import org.springblade.modules.guosen.bussiness.wrapper.BussinessWrapper;
import org.springblade.modules.guosen.bussinessInfo.entity.BussinessInfo;
import org.springblade.yeePay.common.YeePayConst;
import org.springframework.util.Assert;
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.bussiness.entity.Bussiness;
import org.springblade.modules.guosen.bussiness.vo.BussinessVO;
import org.springblade.modules.guosen.bussiness.service.IBussinessService;
import org.springblade.core.boot.ctrl.BladeController;

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

/**
 * 控制器
 *
 * @author BladeX
 * @since 2021-07-08
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-guosen/bussiness")
@Api(value = "", tags = "商户管理")
public class BussinessController extends BladeController {

	private final IBussinessService bussinessService;
	private final YeePayConst yeePayConst;


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入bussiness")
	public R<Bussiness> detail(Bussiness bussiness) {
		Bussiness detail = bussinessService.getOne(Condition.getQueryWrapper(bussiness));
		return R.data(BussinessWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入bussiness")
	public R<IPage<BussinessVO>> list(Bussiness bussiness, Query query) {
		BladeUser user = AuthUtil.getUser();
		IPage<Bussiness> pages = null;
		if(Objects.equals(user.getRoleId(), SystemConstant.BUSSINESS_ROLE_ID)){
			pages= bussinessService.page(Condition.getPage(query), Condition.getQueryWrapper(bussiness).lambda()
				.eq(Bussiness::getAccountId,user.getUserId()));
		}else{
			pages = bussinessService.page(Condition.getPage(query), Condition.getQueryWrapper(bussiness));
		}
		return R.data(BussinessWrapper.build().pageVO(pages));
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入bussiness")
	public R<IPage<BussinessVO>> page(BussinessVO bussiness, Query query) {
		BladeUser user = AuthUtil.getUser();
		IPage<Bussiness> pages = null;
		LambdaQueryWrapper<Bussiness> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(StringUtil.isNotBlank(bussiness.getName()), Bussiness::getName, bussiness.getName());
		lambdaQueryWrapper.eq(bussiness.getEnable() != null, Bussiness::getEnable, bussiness.getEnable());
		lambdaQueryWrapper.eq(bussiness.getRegisterStatus() != null, Bussiness::getRegisterStatus, bussiness.getRegisterStatus());
		lambdaQueryWrapper.eq(Bussiness::getAccountId,user.getUserId());
		if(Objects.equals(user.getRoleId(), SystemConstant.BUSSINESS_ROLE_ID)){
			pages= bussinessService.page(Condition.getPage(query), lambdaQueryWrapper);
		}else{
			pages = bussinessService.page(Condition.getPage(query), Condition.getQueryWrapper(bussiness));
		}
		return R.data(BussinessWrapper.build().pageVO(pages));
	}

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

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入bussiness")
	public R submit(@Valid @RequestBody Bussiness bussiness) {
		return R.status(bussinessService.saveOrUpdate(bussiness));
	}

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


	/**
	 * 生成api文档
	 */
	@PostMapping("/generateApi")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "生成api文档", notes = "传入ids")
	public R generateApi(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> bussinessIds = Func.toLongList(ids);
		bussinessIds.forEach(bussinessId ->{
			Bussiness bussiness = this.bussinessService.getById(bussinessId);
			String remoteUrl = this.bussinessService.generateApiByBussiness(bussiness);
			bussiness.setApiFilePath(remoteUrl);
			bussinessService.updateById(bussiness);
		});

		return R.status(true);
	}
	/**
	 * 根据账号获取商户信息
	 */
	@GetMapping("/getByAccount")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "通过账号获取采购商")
	public R<Bussiness> getByAccount() {
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = this.bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
			.eq(Bussiness::getAccountId, user.getUserId()));
		if (bussiness != null){
			bussiness.setRemain(MoneyDesUtil.decrypt(bussiness.getRemain(), MoneyDesUtil.KEY_FOR_UC));
			bussiness.setFreeze(MoneyDesUtil.decrypt(bussiness.getFreeze(), MoneyDesUtil.KEY_FOR_UC));
		}
		return R.data(bussiness);
	}

	/**
	 * 启用禁用采购商
	 * @param bussinessId
	 * @return
	 */
	@GetMapping(value = "/enableBussiness")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "启用禁用采购商", notes = "传入bussinessId，enable")
	public R enableBussiness(@RequestParam(value = "bussinessId") Long bussinessId, @RequestParam(value = "enable") Integer enable){
		return R.status(bussinessService.enable(bussinessId, enable));
	}

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

	/**
	 * 查询商户账户余额
	 */
	@GetMapping("/queryBusinessBalance")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "商户余额查询")
	public R<BigDecimal> queryBalance(@RequestParam(value = "bussinessId", required = false) Long bussinessId) {
		Bussiness bussiness = bussinessService.getById(bussinessId);
		Assert.notNull(bussiness, "商户不存在");
		BladeUser user = AuthUtil.getUser();
		if(user.getRoleName().equals("商户") || user.getRoleName().equals("财务管理") || user.getRoleName().equals("administrator")){ //入驻商查询余额
			if(StringUtil.isNoneBlank(bussiness.getMerchantNo()) && bussiness.getRegisterStatus().intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
				R<BigDecimal> newRemainR = bussinessService.queryBalance(bussiness.getMerchantNo());
				BigDecimal newRemain = newRemainR.getData();
				bussiness.setRemain(MoneyDesUtil.encrypt(newRemain.toString(), MoneyDesUtil.KEY_FOR_UC));
				//修改商户余额信息
				bussinessService.updateById(bussiness);
				return newRemainR;
			}else{
				return R.fail("请先完成商户进件");
			}
		}else{
			return R.fail("暂无权限");
		}
	}

	/**
	 * 查询平台账户余额
	 */
	@GetMapping("/queryPlatformBalance")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "平台余额查询")
	public R<BigDecimal> queryPlatformBalance() {
		BladeUser user = AuthUtil.getUser();
		if(user.getRoleName().equals("财务管理") || user.getRoleName().equals("administrator")){//运营查询平台商余额
			return bussinessService.queryBalance(null);
		}else{
			return R.fail("无权限查看");
		}
	}

	/**
	 * 体验商户新增或修改
	 */
	@PostMapping("/testSubmit")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "体验商户新增或修改", notes = "传入bussiness")
	public R testSubmit(@Valid @RequestBody Bussiness bussiness) {
		return R.status(bussinessService.testSaveOrUpdate(bussiness));
	}

	/**
	 * 体验商户新增或修改
	 */
	@GetMapping("/getByBussinessType")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "根据商户类型获取商户", notes = "传入bussiness")
	public R<List<SimpleBussinessVO>> getByBussinessType(@RequestParam(value = "bussinessType", required = true) Integer bussinessType) {
		List<Bussiness> list = this.bussinessService.getByBussinessType(bussinessType);
		List<SimpleBussinessVO> simpleBussinessVOList = list.stream().map(item -> {
			SimpleBussinessVO vo = new SimpleBussinessVO();
			vo.setId(item.getId());
			vo.setName(item.getName());
			return vo;
		}).collect(Collectors.toList());
		if(simpleBussinessVOList != null && simpleBussinessVOList.size() > 0){
			return R.data(simpleBussinessVOList);
		}else{
			return R.data(new ArrayList<>());
		}
	}

}
