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

import cn.hutool.core.lang.Assert;
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.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.guosen.agenter.dto.AgenterDTO;
import org.springblade.modules.guosen.billRecord.entity.BillRecord;
import org.springblade.modules.guosen.billRecord.service.IBillRecordService;
import org.springblade.modules.guosen.loginUser.entity.LoginUser;
import org.springblade.modules.guosen.loginUser.service.ILoginUserService;
import org.springframework.transaction.annotation.Transactional;
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.agenter.entity.Agenter;
import org.springblade.modules.guosen.agenter.vo.AgenterVO;
import org.springblade.modules.guosen.agenter.wrapper.AgenterWrapper;
import org.springblade.modules.guosen.agenter.service.IAgenterService;
import org.springblade.core.boot.ctrl.BladeController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-06-25
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-guosen/agenter")
@Api(value = "", tags = "接口")
public class AgenterController extends BladeController {

	private final IAgenterService agenterService;

	private final ILoginUserService loginUserService;

	private final IBillRecordService billRecordService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入agenter")
	public R<AgenterVO> detail(Agenter agenter) {
		Agenter detail = agenterService.getOne(Condition.getQueryWrapper(agenter));
		return R.data(AgenterWrapper.build(loginUserService).entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入agenter")
	public R<IPage<AgenterVO>> list(@RequestParam Map<String,Object> agenter, Query query) {

		BladeUser user = AuthUtil.getUser();//判断当前登录身份，如果是代理
		boolean isProxy = ("代理").equals(user.getRoleName());
		Integer enabled = null;
		if(agenter.get("enabled") != null){
			enabled = Integer.valueOf(agenter.get("enabled").toString());
			agenter.remove("enabled");
		}
		IPage<Agenter> pages = agenterService.page(Condition.getPage(query),
			enabled == null ? Condition.getQueryWrapper(agenter,Agenter.class).lambda().eq(isProxy, Agenter::getUserPhone,user.getAccount())
							: Condition.getQueryWrapper(agenter,Agenter.class).lambda().eq(Agenter::getEnabled,enabled).eq(isProxy, Agenter::getUserPhone,user.getAccount()));
		return R.data(AgenterWrapper.build(loginUserService).pageVO(pages));
	}


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

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

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入agenter")
	@Transactional
	public R submit(@Valid @RequestBody AgenterDTO agenterDTO) {
		Agenter agenter = Objects.requireNonNull(BeanUtil.copy(agenterDTO, Agenter.class));
		if(Long.valueOf(agenter.getLevel()) == SystemConstant.AgenterType.CITY_AGENTER.getId()){//如果是独家代理，一个城市只能有一个
			Assert.notNull(agenter.getProvince(),"独家代理省份必填");
			Assert.notNull(agenter.getCity(),"独家代理城市必填");
			List<Agenter> agenters = agenterService.getBaseMapper().selectList(new QueryWrapper<>(new Agenter()).lambda().eq(Agenter::getProvince, agenter.getProvince())
				.eq(Agenter::getCity, agenter.getCity()));
			Assert.isFalse(agenters.size() >0 ,"该城市已经有独家代理");
		}
		Agenter isExist = agenterService.getBaseMapper().selectOne(new QueryWrapper<>(new Agenter()).lambda()
			.eq(Agenter::getUserPhone, agenter.getUserPhone()));
		Assert.isNull(isExist,"该手机号的用户已经是代理");
		Assert.notNull(agenter.getLevel(),"代理类型不能为空");
		Assert.notNull(agenter.getUserPhone(),"用户手机号码不能为空");
		LoginUser loginUser = loginUserService.getBaseMapper().selectOne(new QueryWrapper<>(new LoginUser()).lambda()
			.eq(LoginUser::getPhone,agenter.getUserPhone()));
		Assert.notNull(loginUser,"找不到该用户");
		agenter.setEnabled(agenter.getEnabled() != null ? agenter.getEnabled() : 1);//默认启用
		agenter.setUserId(loginUser.getId());

		BigDecimal price = agenterDTO.getPrice();//代理费
		BillRecord billRecord = new BillRecord();
		billRecord.setOpenId(loginUser.getOpenid());
		billRecord.setPayStatus(SystemConstant.BillRecordPayStatus.PAYED.getValue());
		billRecord.setPrice(price);
		billRecord.setType(SystemConstant.BillRecordType.AGENTER.getValue());//代理费
		billRecord.setUserId(loginUser.getId());
		return R.status(agenterService.saveOrUpdate(agenter)&&billRecordService.save(billRecord));
	}


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


}
