package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.abel533.sql.SqlMapper;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TCutsomerDataPermisson;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TCutsomerDataPermissonMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TCutsomerDataPermissonService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TCutsomerDataPermissonVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;


/**
 * 客户数据权限表
 *
 * @author pwang
 * @date 2019-07-19 11:42:58
 */

@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(DaprUpmsProperties.class)
@Slf4j
public class TCutsomerDataPermissonServiceImpl extends ServiceImpl<TCutsomerDataPermissonMapper, TCutsomerDataPermisson> implements TCutsomerDataPermissonService {

	private final DaprUpmsProperties daprUpmsProperties;

	@Autowired
	private SqlSessionFactory sqlSessionFactory;

	/**
	 * 客户数据权限表简单分页查询
	 *
	 * @param tCutsomerDataPermisson 客户数据权限表
	 * @return
	 */
	@Override
	public IPage<TCutsomerDataPermissonVo> getTCutsomerDataPermissonPage(Page<TCutsomerDataPermissonVo> page, TCutsomerDataPermissonVo tCutsomerDataPermisson) {
		long tEmployeeInfoPageCount = baseMapper.getTCutsomerDataPermissonPageCount(tCutsomerDataPermisson);
		page.setTotal(tEmployeeInfoPageCount);
		if (tEmployeeInfoPageCount > 0L) {
			page.setPages((long) Math.ceil(tEmployeeInfoPageCount / page.getSize()));
		}
		if (page.getCurrent() < 1) {
			page.setCurrent(1L);
		}
		if (page.getSize() < 1) {
			page.setSize(10L);
		}
		if (tEmployeeInfoPageCount > ((page.getCurrent() - 1) * page.getSize())) {
			page.setRecords(baseMapper.getTCutsomerDataPermissonPage(tCutsomerDataPermisson, (page.getCurrent() - 1) * page.getSize(), page.getSize()));
		}
		return page;
	}

	@Override
	public String findOwnerIdByIdAndType(String domainId, int type) {
		if (CommonConstants.dingleDigitIntArray[0] == type || CommonConstants.dingleDigitIntArray[1] == type || CommonConstants.dingleDigitIntArray[2] == type) {
			return baseMapper.getOwnerIdByIdAndType(domainId, type);
		}
		return null;
	}

	@Override
	public YifuUser findOwnerByIdAndType(String domainId, int type) {
		if (CommonConstants.dingleDigitIntArray[0] == type || CommonConstants.dingleDigitIntArray[1] == type || CommonConstants.dingleDigitIntArray[2] == type) {
			String userid = baseMapper.getOwnerIdByIdAndType(domainId, type);
			try {
				if (null != userid) {
					R<YifuUser> result = HttpDaprUtil.invokeMethodGet(daprUpmsProperties.getAppUrl(),daprUpmsProperties.getAppId(), "/user/getSimpleUser/"+userid, null, Integer.class);
					return null==result?null:result.getData();
				}
			} catch (Exception e) {
				log.info("findOwnerByIdAndType方法报错:", e);
				return null;
			}
		}
		return null;
	}

	@Override
	public String getCustomerServiceByid(String id) {
		return baseMapper.getCustomerServiceByid(id);
	}

	@Override
	public String getUserByid(String settleId) {
		return baseMapper.getUserByid(settleId);
	}

	@Override
	@Transactional
	public R insertForCopyCutsomerDataPermisson(String[] srcUser, String[] beUser, YifuUser user) {
		if(Common.isEmpty(srcUser)){
			return R.failed("请选择要被复制人！") ;
		}
		if(Common.isEmpty(beUser)){
			return R.failed("请选择被授权的人！") ;
		}
		if(beUser.length > 1){
			return R.failed("为了避免权限混乱，暂时只支持权限复制给某一个人！") ;
		}
		List<TCutsomerDataPermisson> list = baseMapper.selectList(Wrappers.<TCutsomerDataPermisson>lambdaQuery().in(TCutsomerDataPermisson::getBePermissonUser, srcUser));
		Collection<TCutsomerDataPermisson> saveColl = null;
		if(Common.isNotNull(list)){
			LocalDateTime now = LocalDateTime.now();
			for(String userId : beUser){
				saveColl = getSaveDataPermissonList(user, list, now, userId);
				if(Common.isNotNull(saveColl)){
					this.saveBatch(saveColl);
				}
			}
		}else{
			return R.failed("未查到要被复制人的权限表数据，请换个人复制权限") ;
		}
		return  R.ok("操作成功");
	}
	/**
	 * 获取要新增的权限集合
	 * @Author pwang
	 * @Date 2020-09-27 17:24
	 * @param user
	 * @param list
	 * @param now
	 * @param userId
	 * @return
	 **/
	private Collection<TCutsomerDataPermisson> getSaveDataPermissonList(YifuUser user, List<TCutsomerDataPermisson> list, LocalDateTime now, String userId) {
		Collection<TCutsomerDataPermisson> result = new HashSet<>();
		Map<String, TCutsomerDataPermisson> cutsomerDataPermissonMap = new HashMap<>();
		Map<String, TCutsomerDataPermisson> contractIdDataPermissonMap =new HashMap<>();
		Map<String, TCutsomerDataPermisson> settleDomianDataPermissonMap =new HashMap<>();
		List<TCutsomerDataPermisson> oldPermisson = baseMapper.selectList(Wrappers.<TCutsomerDataPermisson>lambdaQuery().in(TCutsomerDataPermisson::getBePermissonUser, userId));
		//被复制的权限去重
		for(TCutsomerDataPermisson cdp : list){
			cdp.setId(null);
			cdp.setBePermissionTime(now);
			cdp.setIsOwner(CommonConstants.IS_OWNER_NO);
			cdp.setBePermissonUser(userId);
			cdp.setIsCustomerService(CommonConstants.ONE_STRING);//非客服
			cdp.setPermissonSrc(user.getNickname() + "批量复制权限");
			cdp.setPermissionUser(String.valueOf(user.getId()));
			cdp.setType(cdp.getType());

			if(CommonConstants.dingleDigitStrArray[0].equals(cdp.getType())){
				cutsomerDataPermissonMap.put(cdp.getCustomerId(),cdp);
			}else if(CommonConstants.dingleDigitStrArray[1].equals(cdp.getType())){
				contractIdDataPermissonMap.put(cdp.getContractId(),cdp);
			}else if(CommonConstants.dingleDigitStrArray[2].equals(cdp.getType())){
				settleDomianDataPermissonMap.put(cdp.getSettleDomainId(),cdp);
			}
		}
		//去除本身有的权限
		for(TCutsomerDataPermisson cdp : oldPermisson){
			if(CommonConstants.dingleDigitStrArray[0].equals(cdp.getType())){
				cutsomerDataPermissonMap.remove(cdp.getCustomerId());
			}else if(CommonConstants.dingleDigitStrArray[1].equals(cdp.getType())){
				contractIdDataPermissonMap.remove(cdp.getCustomerId());
			}else if(CommonConstants.dingleDigitStrArray[2].equals(cdp.getType())){
				settleDomianDataPermissonMap.remove(cdp.getCustomerId());
			}
		}
		if(Common.isNotNull(cutsomerDataPermissonMap.values())){
			result.addAll(cutsomerDataPermissonMap.values());
		}
		if(Common.isNotNull(contractIdDataPermissonMap.values())){
			result.addAll(contractIdDataPermissonMap.values());
		}
		if(Common.isNotNull(settleDomianDataPermissonMap.values())){
			result.addAll(settleDomianDataPermissonMap.values());
		}
		return result;
	}

	/**
	 * 专用方法 不建议调用 存在sql注入风险
	 * @Author pwang
	 * @Date 2020-07-02 19:00
	 * @param sql
	 * @param beUser
	 * @param user
	 * @return
	 **/
	@Override
	public R insertCutsomerDataPermissonBySql(String sql, String beUser, YifuUser user) {
		if(Common.isEmpty(beUser)){
			return R.failed("请选择被授权的人！") ;
		}
		SqlSession session = sqlSessionFactory.openSession();
		SqlMapper sqlMapper = new SqlMapper(session);
		List<String> list = sqlMapper.selectList(sql, String.class);
		TCutsomerDataPermisson cdp = null ;
		List<TCutsomerDataPermisson> saveList = new ArrayList<>();
		if(Common.isNotNull(list)){
			LocalDateTime now = LocalDateTime.now();
			for(String settleDamainId : list){
				cdp = new TCutsomerDataPermisson();
				cdp.setBePermissionTime(now);
				cdp.setSettleDomainId(settleDamainId);
				cdp.setIsOwner(CommonConstants.IS_OWNER_NO);
				cdp.setBePermissonUser(beUser);
				cdp.setIsCustomerService(CommonConstants.ONE_STRING);//非客服
				cdp.setPermissonSrc(user.getNickname() + "sql授权");
				cdp.setPermissionUser(String.valueOf(user.getId()));
				saveList.add(cdp);
			}
			this.saveBatch(saveList);
		}else{
			return R.failed("未查到要被复制人的权限表数据，请换个人复制权限") ;
		}
		return  R.ok("操作成功");
	}

	@Override
	public boolean save(TCutsomerDataPermisson cutsomerDataPermisson){
		if(null != cutsomerDataPermisson.getSettleDomainId()){
			cutsomerDataPermisson.setType(CommonConstants.dingleDigitStrArray[2]);
		}else if(null != cutsomerDataPermisson.getContractId()){
			cutsomerDataPermisson.setType(CommonConstants.dingleDigitStrArray[1]);
		}else if(null != cutsomerDataPermisson.getCustomerId()){
			cutsomerDataPermisson.setType(CommonConstants.dingleDigitStrArray[0]);
		}
		return super.save(cutsomerDataPermisson);
	}
}
