/*
 *      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.bussinessInfo.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.servlet.http.HttpServletResponse;
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.bussiness.vo.SimpleBussinessVO;
import org.springblade.modules.guosen.bussinessContactInfo.service.IBussinessContactInfoService;
import org.springblade.modules.guosen.bussinessInfo.dto.BussinessInfoProductQualDTO;
import org.springblade.modules.guosen.bussinessInfo.vo.SimpleBussinessInfoVO;
import org.springblade.modules.guosen.bussinessuserinfo.entity.BussinessUserInfo;
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.bussinessInfo.entity.BussinessInfo;
import org.springblade.modules.guosen.bussinessInfo.vo.BussinessInfoVO;
import org.springblade.modules.guosen.bussinessInfo.wrapper.BussinessInfoWrapper;
import org.springblade.modules.guosen.bussinessInfo.service.IBussinessInfoService;
import org.springblade.core.boot.ctrl.BladeController;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-09-22
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-bussiness-info/bussinessinfo")
@Api(value = "", tags = "接口")
public class BussinessInfoController extends BladeController {

	private final IBussinessInfoService bussinessInfoService;
	private final IBussinessService bussinessService;
	private final IBussinessContactInfoService bussinessContactInfoService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入bussinessInfo")
	public R<BussinessInfoVO> detail(BussinessInfo bussinessInfo) {
		BussinessInfo detail = bussinessInfoService.getOne(Condition.getQueryWrapper(bussinessInfo));
		return R.data(BussinessInfoWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入bussinessInfo")
	public R<IPage<BussinessInfoVO>> list(BussinessInfo bussinessInfo, Query query) {
		BladeUser user = AuthUtil.getUser();
		if(user.getRoleName().equals("商户") || user.getRoleName().equals("体验商户")){
			Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
					.eq(Bussiness::getAccountId, user.getUserId()));
			Assert.notNull(bussiness, "商户不存在");
			bussinessInfo.setBussinessId(bussiness.getId());
		}
		LambdaQueryWrapper<BussinessInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(StringUtil.isNotBlank(bussinessInfo.getSignName()), BussinessInfo::getSignName, bussinessInfo.getSignName());
		lambdaQueryWrapper.eq(bussinessInfo.getBussinessId() != null, BussinessInfo::getBussinessId, bussinessInfo.getBussinessId());
		lambdaQueryWrapper.eq(bussinessInfo.getRegisterStatus() != null, BussinessInfo::getRegisterStatus, bussinessInfo.getRegisterStatus());
		IPage<BussinessInfo> pages = bussinessInfoService.page(Condition.getPage(query), lambdaQueryWrapper);
		return R.data(BussinessInfoWrapper.build().pageVO(pages));
	}


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

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入bussinessInfo")
	public R save(@Valid @RequestBody BussinessInfo bussinessInfo) {
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
				.eq(Bussiness::getAccountId, user.getUserId()));
		Assert.notNull(bussiness, "当前账号为非采购商，请勿进件");
		BussinessInfo dbInfo = bussinessInfoService.getByBussinessId(bussiness.getId());
		Assert.isNull(dbInfo, "请勿重复创建进件信息");
		BussinessInfo byLicenceNo = bussinessInfoService.getByLicenceNo(bussinessInfo.getLicenceNo());
		Assert.isNull(byLicenceNo, "该商户证件编号已存在，请勿重复添加");
		bussinessInfo.setRegisterStatus(SystemConstant.BussinessRegisterStatus.DOING.getValue());
		bussinessInfo.setBussinessId(bussiness.getId());
		if(StringUtil.isBlank(bussinessInfo.getBusinessRole())){
			bussinessInfo.setBusinessRole("SETTLED_MERCHANT");
		}
		if(bussiness.getParentBussinessId() != null){
			BussinessInfo parentBussinessInfo = this.bussinessInfoService.getByBussinessId(bussiness.getParentBussinessId());
			bussinessInfo.setParentMerchantNo(parentBussinessInfo.getMerchantNo());
		}
		boolean save = bussinessInfoService.save(bussinessInfo);
		if(!save){
			return R.fail("保存失败");
		}
		return R.data(bussinessInfo);
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入bussinessInfo")
	public R update(@Valid @RequestBody BussinessInfo bussinessInfo) {
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
				.eq(Bussiness::getAccountId, user.getUserId()));
		Assert.notNull(bussiness, "当前账号为非采购商，请勿进件");
		bussinessInfo.setBussinessId(bussiness.getId());
		Integer registerStatus = bussinessInfo.getRegisterStatus();
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("商户已进件审核成功，请勿修改");
		}
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_AUDIT.getValue() || registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUBMIT_SUCCESS.getValue()){
			return R.fail("商户进件审核中，请勿修改");
		}
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_SIGNING.getValue()){
			return R.fail("商户待签署协议，请前往签署协议");
		}
		boolean update = bussinessInfoService.updateById(bussinessInfo);
		if(!update){
			return R.fail("保存失败");
		}
		return R.data(bussinessInfo);
	}

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

	
	/**
	 * 删除 
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> bussinessInfoIdList = Func.toLongList(ids);
		for(Long bussinessInfoId : bussinessInfoIdList){
			boolean b = bussinessContactInfoService.deleteByBussinessInfoId(bussinessInfoId);
			if(b){
				bussinessInfoService.removeById(bussinessInfoId);
			}
		}
		return R.status(true);
	}

	/**
	 * 查询平台账户余额
	 */
	@GetMapping("/agreeSign")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "平台余额查询")
	public R<String> agreeSign(HttpServletResponse response) throws IOException {
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
				.eq(Bussiness::getAccountId, user.getUserId()));
		Assert.notNull(bussiness,"当前账户为非采购商账户，不能签署协议");
		if(bussiness.getRegisterStatus() == null || bussiness.getRegisterStatus().intValue() != SystemConstant.BussinessRegisterStatus.WAIT_SIGNING.getValue()){
			return R.fail("暂时未能签署协议");
		}
		BussinessInfo bussinessInfo = bussinessInfoService.getByBussinessId(bussiness.getId());
		Assert.notNull(bussinessInfo, "商户主体信息不存在");
		String agreementSignUrl = bussinessInfo.getAgreementSignUrl();
		return R.data(agreementSignUrl);
	}

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

	/**
	 * 新增
	 */
	@PostMapping("/platformSave")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增", notes = "传入bussinessInfo")
	public R platformSave(@Valid @RequestBody BussinessInfo bussinessInfo) {

		BussinessInfo dbInfo = bussinessInfoService.getByBussinessId(bussinessInfo.getBussinessId());
		Assert.isNull(dbInfo, "请勿重复创建进件信息");
		BussinessInfo byLicenceNo = bussinessInfoService.getByLicenceNo(bussinessInfo.getLicenceNo());
		Assert.isNull(byLicenceNo, "该商户证件编号已存在，请勿重复添加");
		bussinessInfo.setRegisterStatus(SystemConstant.BussinessRegisterStatus.DOING.getValue());
		if(StringUtil.isBlank(bussinessInfo.getBusinessRole())){
			bussinessInfo.setBusinessRole("SETTLED_MERCHANT");
		}
		boolean save = bussinessInfoService.save(bussinessInfo);
		if(!save){
			return R.fail("保存失败");
		}
		return R.data(bussinessInfo);
	}

	/**
	 * 修改
	 */
	@PostMapping("/platformUpdate")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "修改", notes = "传入bussinessInfo")
	public R platformUpdate(@Valid @RequestBody BussinessInfo bussinessInfo) {
		Integer registerStatus = bussinessInfo.getRegisterStatus();
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("商户已进件审核成功，请勿修改");
		}
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_AUDIT.getValue() || registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUBMIT_SUCCESS.getValue()){
			return R.fail("商户进件审核中，请勿修改");
		}
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_SIGNING.getValue()){
			return R.fail("商户待签署协议，请前往签署协议");
		}
		boolean update = bussinessInfoService.updateById(bussinessInfo);
		if(!update){
			return R.fail("保存失败");
		}
		return R.data(bussinessInfo);
	}

	/**
	 * 更新产品资质
	 */
	@PostMapping("/updateProductQual")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "更新产品资质", notes = "传入bussinessInfo")
	public R updateProductQual(@Valid @RequestBody BussinessInfoProductQualDTO bussinessInfoProductQualDTO) {
		BladeUser user = AuthUtil.getUser();
		Bussiness bussiness = bussinessService.getBaseMapper().selectOne(new QueryWrapper<>(new Bussiness()).lambda()
				.eq(Bussiness::getAccountId, user.getUserId()));
		Assert.notNull(bussiness, "当前账号为非采购商，请勿进件");
		BussinessInfo dbBussinessInfo = this.bussinessInfoService.getById(bussinessInfoProductQualDTO.getBussinessInfoId());
		Assert.notNull(dbBussinessInfo, "主体信息不存在");

		Integer registerStatus = dbBussinessInfo.getRegisterStatus();
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUCCESS.getValue()){
			return R.fail("商户已进件审核成功，请勿修改");
		}
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_AUDIT.getValue() || registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.SUBMIT_SUCCESS.getValue()){
			return R.fail("商户进件审核中，请勿修改");
		}
		if(registerStatus.intValue() == SystemConstant.BussinessRegisterStatus.WAIT_SIGNING.getValue()){
			return R.fail("商户待签署协议，请前往签署协议");
		}
		dbBussinessInfo.setAgreementPhotoUrl(bussinessInfoProductQualDTO.getAgreementPhotoUrl());
		dbBussinessInfo.setSystemScreenshotUrl(bussinessInfoProductQualDTO.getSystemScreenshotUrl());
		dbBussinessInfo.setSpecialPermitProcessUrl(bussinessInfoProductQualDTO.getSpecialPermitProcessUrl());
		boolean update = bussinessInfoService.updateById(dbBussinessInfo);
		if(!update){
			return R.fail("保存失败");
		}else{
			return R.success("保存成功");
		}
	}

	
}
