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

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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.finance.dto.InnerComapnySpidDTO;
import org.springblade.finance.dto.InnerComapnySpidVerifyDTO;
import org.springblade.finance.entity.InnerComapnySpid;
import org.springblade.finance.query.InnerComapnySpidQuery;
import org.springblade.finance.service.IInnerComapnySpidService;
import org.springblade.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 内部结算-结算产品表 控制器
 *
 * @author zbc
 * @since 2022-07-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("finance/innerComapnySpid")
@Api(value = "内部结算-结算产品表", tags = "内部结算-结算产品表接口")
@Slf4j
public class InnerComapnySpidController {

	@Autowired
	private IInnerComapnySpidService innerComapnySpidService;

	@Autowired
	private UserClient userService;


	@GetMapping("/page")
	@ApiOperation(value = "结算产品分页")
	public R<IPage<InnerComapnySpid>> page(InnerComapnySpidQuery pageQuery, Query query) {
		if(query.getSize() == null){
			query.setSize(3);
		}
		IPage<InnerComapnySpid> page = Condition.getPage(query);
		LambdaQueryWrapper<InnerComapnySpid> wrapper = new LambdaQueryWrapper<>();
		if(StringUtils.isNotBlank(pageQuery.getCompany())){
			wrapper.eq(InnerComapnySpid::getCompany,pageQuery.getCompany());
		}
		if(StringUtils.isNotBlank(pageQuery.getDealType())){
			wrapper.eq(InnerComapnySpid::getDealType,pageQuery.getDealType());
		}
		wrapper.orderByDesc(InnerComapnySpid::getInputTime);
		IPage<InnerComapnySpid> pages = innerComapnySpidService.page(page, wrapper);
		for (InnerComapnySpid record : pages.getRecords()) {
			record.setInputName(getUserName(record.getInputter()));
			record.setCheckName(getUserName(record.getChecker()));
		}
		return R.data(pages);
	}



	@GetMapping("/companyList")
	@ApiOperation(value = "结算方名称（公司名称）下拉")
	public R companyList() {
		QueryWrapper<InnerComapnySpid> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("DISTINCT COMPANY ").isNotNull("COMPANY");
		List<InnerComapnySpid> list = innerComapnySpidService.list(queryWrapper);
		List<Map<String, Object>> data = list.stream()
			.map(obj -> {
				Map<String, Object> map = new HashMap<>();
				map.put("name", obj.getCompany());
				return map;
			}).collect(Collectors.toList());
		return R.data(data);
	}


	@GetMapping("/dealtypeList")
	@ApiOperation(value = "结算单类型下拉")
	public R dealtypeList() {
		QueryWrapper<InnerComapnySpid> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("DISTINCT DEAL_TYPE").isNotNull("DEAL_TYPE");
		List<InnerComapnySpid> list = innerComapnySpidService.list(queryWrapper);
		List<Map<String, Object>> data = list.stream()
			.map(obj -> {
				Map<String, Object> map = new HashMap<>();
				map.put("name", obj.getDealType());
				return map;
			}).collect(Collectors.toList());
		return R.data(data);
	}



	@PostMapping("/save")
	@ApiOperation(value = "内部结算-结算产品表新增")
	public R save(@RequestBody @Valid InnerComapnySpidDTO dto){
		String userId = SecureUtil.getUserId().toString();
		//结算产品信息
		InnerComapnySpid comapny = new InnerComapnySpid();
		BeanUtils.copyProperties(dto,comapny);
		comapny.setInputter(userId);
		comapny.setInputTime(new Date());
		comapny.setStatus(0);
		comapny.setDataStartdate(new Date());
		return R.status(innerComapnySpidService.save(comapny));
	}



	@PostMapping("/cancel")
	@ApiOperation(value = "驳回")
	public R cancel(@RequestBody @Valid InnerComapnySpidVerifyDTO dto){
		String userId = SecureUtil.getUserId().toString();
		List<InnerComapnySpid> list = innerComapnySpidService.list(new LambdaQueryWrapper<InnerComapnySpid>()
			.eq(InnerComapnySpid::getDealType, dto.getDealType())
			.eq(InnerComapnySpid::getCompany, dto.getCompany())
			.eq(InnerComapnySpid::getIsValid, dto.getIsValid())
			.eq(InnerComapnySpid::getSpid, dto.getSpid())
		);

		if(list == null && list.size() == 0){
			return R.fail("审核数据不存在");
		}

		if(!list.get(0).getChecker().equals(userId)){
			return R.fail("您没有审核权限");
		}

		list.get(0).setStatus(2);
		list.get(0).setCheckTime(new Date());
		boolean res = innerComapnySpidService.update(list.get(0), new LambdaUpdateWrapper<InnerComapnySpid>()
			.eq(InnerComapnySpid::getDealType, dto.getDealType())
			.eq(InnerComapnySpid::getCompany, dto.getCompany())
			.eq(InnerComapnySpid::getIsValid, dto.getIsValid())
			.eq(InnerComapnySpid::getSpid, dto.getSpid())
		);
		return R.status(res);
	}

	@PostMapping("/verify")
	@ApiOperation(value = "渠道产品审核通过")
	public R verify(@RequestBody @Valid InnerComapnySpidVerifyDTO dto){
		String userId = SecureUtil.getUserId().toString();

		List<InnerComapnySpid> list = innerComapnySpidService.list(new LambdaQueryWrapper<InnerComapnySpid>()
			.eq(InnerComapnySpid::getDealType, dto.getDealType())
			.eq(InnerComapnySpid::getCompany, dto.getCompany())
			.eq(InnerComapnySpid::getIsValid, dto.getIsValid())
			.eq(InnerComapnySpid::getSpid, dto.getSpid())
		);

		if(list == null || list.size() == 0){
			return R.fail("审核数据不存在");
		}

		if(!list.get(0).getChecker().equals(userId)){
			return R.fail("您没有审核权限");
		}

		list.get(0).setStatus(1);
		list.get(0).setCheckTime(new Date());
		boolean res = innerComapnySpidService.update(list.get(0), new LambdaUpdateWrapper<InnerComapnySpid>()
			.eq(InnerComapnySpid::getDealType, dto.getDealType())
			.eq(InnerComapnySpid::getCompany, dto.getCompany())
			.eq(InnerComapnySpid::getIsValid, dto.getIsValid())
			.eq(InnerComapnySpid::getSpid, dto.getSpid())
		);
		if(res){
			return R.success("审核成功");
		}
		return R.fail("审核失败");
	}


	@PostMapping("/remove")
	@ApiOperation(value = "删除")
	public R remove(@RequestBody @Valid InnerComapnySpidVerifyDTO dto){
		String userId = SecureUtil.getUserId().toString();

		List<InnerComapnySpid> list = innerComapnySpidService.list(new LambdaQueryWrapper<InnerComapnySpid>()
			.eq(InnerComapnySpid::getDealType, dto.getDealType())
			.eq(InnerComapnySpid::getCompany, dto.getCompany())
			.eq(InnerComapnySpid::getIsValid, dto.getIsValid())
			.eq(InnerComapnySpid::getSpid, dto.getSpid())
		);

		if(list == null && list.size() == 0){
			return R.fail("删除数据不存在");
		}

		if(!list.get(0).getInputter().equals(userId)){
			return R.fail("您没有删除权限");
		}

		boolean res = innerComapnySpidService.remove(new LambdaUpdateWrapper<InnerComapnySpid>()
			.eq(InnerComapnySpid::getDealType, dto.getDealType())
			.eq(InnerComapnySpid::getCompany, dto.getCompany())
			.eq(InnerComapnySpid::getIsValid, dto.getIsValid())
			.eq(InnerComapnySpid::getSpid, dto.getSpid())
			.eq(InnerComapnySpid::getInputter,userId)
			.ne(InnerComapnySpid::getStatus,1)
		);
		return R.status(res);
	}


	private String getUserName(String userId){
		UserModel byId = userService.getById(Long.valueOf(userId));
		if(byId != null){
			return byId.getRealName();
		}
		return null;
	}

}
