/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.operation.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.apply.operationSiteApply.pojo.entity.OperationSiteApplyEntity;
import org.springblade.modules.operation.constant.SourceConstants;
import org.springblade.modules.operation.excel.OperationSiteExcel;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.EmpAuthVo;
import org.springblade.modules.operation.pojo.vo.OperationSiteVO;
import org.springblade.modules.operation.excel.EntrySiteExcel;
import org.springblade.modules.operation.mapper.OperationSiteMapper;
import org.springblade.modules.operation.service.IOperationSiteService;
import org.springblade.modules.system.pojo.entity.User;
import org.springblade.modules.system.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 网点基础信息表 服务实现类
 *
 * @author lzp
 * @since 2024-06-13
 */
@Service
public class OperationSiteServiceImpl extends ServiceImpl<OperationSiteMapper, OperationSiteEntity> implements IOperationSiteService {

	@Autowired
	UserServiceImpl userService;
	@Autowired
	OperationSiteEmployeeMapper employeeMapper;

	@Override
	public String getOmProviderId() {
		BladeUser user = AuthUtil.getUser();
		String omProviderId = null;
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = this.baseMapper.findSiteByUserId(user.getUserId());
			omProviderId = site.getId();
		} else if ("5".equals(user.getDeptId())|| "6".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			if(authVo!=null){
				omProviderId =authVo.getSiteId();
			}
		}
		return omProviderId;
	}

	@Override
	public IPage<OperationSiteVO> selectOperationSitePage(IPage<OperationSiteVO> page, OperationSiteVO operationSite) {
		operationSite.setId(getOmProviderId());
		return page.setRecords(baseMapper.selectOperationSitePage(page, operationSite));
	}

	public List<OperationSiteExcel> selectOperationSiteList(OperationSiteVO operationSite){
		operationSite.setId(getOmProviderId());
		return baseMapper.selectOperationSiteList(operationSite);
	}

	@Override
	public IPage<OperationSiteVO> findSiteAmountPage(IPage<OperationSiteVO> page, OperationSiteVO operationSite) {
		operationSite.setId(getOmProviderId());
		return page.setRecords(baseMapper.findSiteAmountPage(page, operationSite));
	}


	@Override
	public List<OperationSiteVO> findSiteList(){
		return baseMapper.findSiteList();
	}


	@Override
	public List<EntrySiteExcel> exportOperationSite(Wrapper<OperationSiteEntity> queryWrapper) {

		List<EntrySiteExcel> operationSiteList = baseMapper.exportOperationSite(queryWrapper);
		//operationSiteList.forEach(operationSite -> {
		//	operationSite.setTypeName(DictCache.getValue(DictEnum.YES_NO, OperationSite.getType()));
		//});

		return operationSiteList;
	}

	public OperationSiteEntity findSiteByUserId(Long userId){
		return baseMapper.findSiteByUserId(userId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String saveSite(OperationSiteApplyEntity operationSite) {
		if(StringUtil.isNotBlank(operationSite.getSiteId())){
			return updateSite(operationSite);
		}

		BladeUser bladeUser = AuthUtil.getUser();
		if(userService.userByAccount(bladeUser.getTenantId(), operationSite.getLoginName()) != null){
			throw new ServiceException("登录账号已存在");
		}
		OperationSiteEntity siteName = baseMapper.selectOne(Wrappers.<OperationSiteEntity>query().lambda().eq(OperationSiteEntity::getName,operationSite.getName()).ne(OperationSiteEntity::getStatus,"1"));
		if(siteName!= null){
			throw new ServiceException("服务商名称已存在");
		}
		OperationSiteEntity site = new OperationSiteEntity();

		User user = new User();
		user.setStatus(Integer.valueOf(operationSite.getSiteStatus()));
		user.setIsDeleted(Integer.valueOf(operationSite.getSiteStatus()));
		user.setUserType(1);
		user.setTenantId("000000");
		user.setName(operationSite.getName());
		user.setAccount(operationSite.getLoginName());
		user.setPassword(operationSite.getPassword());
		user.setRealName(operationSite.getName());
		user.setRoleId("1798170366724702210");
		user.setDeptId("3");
		user.setPostId("1803302359644688386");
		//user.setStatus(0);
		boolean userck = userService.submit(user);
		if(!userck){
			throw new ServiceException("登录账号保存失败");
		}
		site.setUserId(user.getId());
		site.setStatus(operationSite.getSiteStatus());
		site.setCreateBy(bladeUser.getUserId());
		site.setCreateTime(new Date());
		site.setCheckFlag(SourceConstants.ONE);
		site.setName(operationSite.getName());
		site.setContacts(operationSite.getContacts());
		site.setMobile(operationSite.getMobile());
		site.setProvince(operationSite.getProvince());
		site.setCity(operationSite.getCity());
		site.setArea(operationSite.getArea());
		site.setProvinceCode(operationSite.getProvinceCode());
		site.setCityCode(operationSite.getCityCode());
		site.setAreaCode(operationSite.getAreaCode());
		site.setAddress(operationSite.getAddress());
		site.setLicenseImg(operationSite.getLicenseImg());
		site.setTotalWallet(BigDecimal.ZERO);
		site.setWithdrawableCash(BigDecimal.ZERO);
		site.setRefusalCount(0);
		site.setSetType(operationSite.getSetType());
		site.setEarnestMoney(operationSite.getEarnestMoney());
		site.setPayTheDeposit(operationSite.getPayTheDeposit());
		if(!save(site)){
			throw new ServiceException("登录账号保存失败");
		}
		return site.getId();
	}


	@Transactional(rollbackFor = Exception.class)
	public String updateSite(OperationSiteApplyEntity operationSite) {
		BladeUser bladeUser = AuthUtil.getUser();
		OperationSiteEntity site =getById(operationSite.getSiteId());
		if(userService.userByAccountUserId(bladeUser.getTenantId(), operationSite.getLoginName(),site.getUserId()) != null){
			throw new ServiceException("登录账号已存在");
		}
		OperationSiteEntity siteName = baseMapper.selectOne(Wrappers.<OperationSiteEntity>query().lambda().eq(OperationSiteEntity::getName,operationSite.getName()).ne(OperationSiteEntity::getStatus,"1").ne(OperationSiteEntity::getId,operationSite.getSiteId()));
		if(siteName!= null){
			throw new ServiceException("服务商名称已存在");
		}

		User user = userService.userByUserId(site.getUserId());
		user.setAccount(operationSite.getLoginName());
		if(StringUtil.isNotBlank(operationSite.getPassword())){
			user.setPassword(DigestUtil.encrypt(operationSite.getPassword()));
		}
		if("3".equals(operationSite.getSiteStatus())){
			user.setStatus(3);
		}else{
			user.setStatus(0);
		}
		user.setRealName(operationSite.getName());
		user.setName(operationSite.getName());
		boolean userck = userService.updateById(user);
		if(!userck){
			throw new ServiceException("更新保存失败");
		}
		site.setStatus(operationSite.getSiteStatus());
		site.setName(operationSite.getName());
		site.setContacts(operationSite.getContacts());
		site.setMobile(operationSite.getMobile());
		site.setProvince(operationSite.getProvince());
		site.setCity(operationSite.getCity());
		site.setArea(operationSite.getArea());
		site.setProvinceCode(operationSite.getProvinceCode());
		site.setCityCode(operationSite.getCityCode());
		site.setAreaCode(operationSite.getAreaCode());
		site.setAddress(operationSite.getAddress());
		site.setLicenseImg(operationSite.getLicenseImg());
		site.setEarnestMoney(operationSite.getEarnestMoney());
		site.setPayTheDeposit(operationSite.getPayTheDeposit());
		updateById(site);
		return site.getId();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateStatus(String id, String status) {
		//BladeUser user = AuthUtil.getUser();
		OperationSiteEntity site = getBaseMapper().selectById(id);
		site.setStatus(status);
		site.setUpdateTime(new Date());
		LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper
			.eq(User::getId,site.getUserId()).set(User::getStatus,status);
		userService.update(updateWrapper);
		return updateById(site);
	}

	@Override
	public OperationSiteVO getSiteDetail(String siteId) {
		return getBaseMapper().getSiteDetail(siteId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteSite(String id) {

		//employeeService.findEmpCount(id);

		OperationSiteEntity site = getBaseMapper().selectById(id);
		site.setStatus("1");
		site.setUpdateTime(new Date());

		userService.deleteLogic(Func.toLongList(site.getUserId().toString()));
		return updateById(site);
	}

}
