/*
 *    Copyright (c) 2018-2025, lengleng 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 yifu4cloud.com 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: lengleng (wangiegie@gmail.com)
 */
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.fadada.api.bean.req.account.GetPersonUnionIdUrlReq;
import com.fadada.api.bean.req.account.NoticeReq;
import com.fadada.api.bean.req.account.PersonReq;
import com.fadada.api.bean.req.organization.DelSubEmployeeReq;
import com.fadada.api.bean.req.organization.GetAddEmployeeUrlReq;
import com.fadada.api.bean.rsp.BaseRsp;
import com.fadada.api.bean.rsp.account.GetUnionIdUrlRsp;
import com.fadada.api.bean.rsp.organization.GetAddEmployeeUrlRsp;
import com.fadada.api.client.AccountClient;
import com.fadada.api.client.OrgClient;
import com.fadada.api.exception.ApiException;
import com.yifu.cloud.plus.v1.yifu.archives.config.FddConfigProperties;
import com.yifu.cloud.plus.v1.yifu.archives.entity.FddCompanyInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.FddPersonAccount;
import com.yifu.cloud.plus.v1.yifu.archives.entity.FddSealPersonAuth;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.FddPersonAccountMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddCompanyInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddPersonAccountService;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddReqLogService;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddSealPersonAuthService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.FddUtil;
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 lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 法大大个人实名认证表
 *
 * @author huyc
 * @date 2022-06-28 16:24:12
 */
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(FddConfigProperties.class)
public class FddPersonAccountServiceImpl extends ServiceImpl<FddPersonAccountMapper, FddPersonAccount> implements FddPersonAccountService {

	@Autowired
	private FddCompanyInfoService fddCompanyInfoService;

	@Autowired
	private FddConfigProperties fddConfigProperties;

	@Autowired
	private FddUtil fddUtil;

	@Autowired
	private FddSealPersonAuthService fddSealPersonAuthService;

	@Autowired
	private FddReqLogService reqLogService;

	@Override
	public IPage<FddPersonAccount> getFddPersonAccountPage(Page<FddPersonAccount> page, FddPersonAccount fddPersonAccount) {
		return baseMapper.getFddPersonAccountPage(page, fddPersonAccount);
	}

	@Override
	public R<String> getPersonUnionIdUrl(FddPersonAccount fddPersonAccount) throws ApiException {

		//发送请求
		GetPersonUnionIdUrlReq req = new GetPersonUnionIdUrlReq();
		req.setToken(fddUtil.getToken());
		req.setClientId(fddPersonAccount.getId());
		req.setAuthScheme(CommonConstants.ZERO_INT);
		NoticeReq notice = new NoticeReq();
		//短信发送实名认证链接
		notice.setNotifyWay(CommonConstants.ONE_INT);
		notice.setNotifyAddress(fddPersonAccount.getMoblie());
		req.setNotice(notice);
		//发送人信息
		PersonReq person = new PersonReq();
		person.setIdentNo(fddPersonAccount.getIdCard());
		person.setMobile(fddPersonAccount.getMoblie());
		person.setName(fddPersonAccount.getName());
		req.setPerson(person);
		//实名授权
		req.setAuthScope(CommonConstants.ONE_STRING);
		req.setReRealName(CommonConstants.ONE_INT);
		//是否允许用户在认证页面修改接口所传的个人认证信息
		//跳转链接
		req.setRedirectUrl(fddConfigProperties.getHrmsUrl() + fddConfigProperties.getPersonRedirectUrl());
		//发送请求
		AccountClient accountClient = new AccountClient(fddUtil.getFadadaApiClient());
		BaseRsp<GetUnionIdUrlRsp> rsp = accountClient.getPersonUnionIdUrl(req);
		reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName(), req, rsp);
		//校验参数
		if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
			fddPersonAccount.setRealMessageFlag(CommonConstants.ONE_STRING);
			baseMapper.updateById(fddPersonAccount);
			return new R<>(rsp.getData().getNextUrl());
		} else {
			return R.failed(rsp.getMsg());
		}
	}

	/**
	 * 邀请客服加入组织
	 * @param fddPersonAccountList
	 * @author huyc
	 * @date 2022-06-28 18:52:16
	 */
	@Override
	public R<String> getAddEmployeeUrl(List<FddPersonAccount> fddPersonAccountList) throws ApiException {
		for (FddPersonAccount fddPersonAccount: fddPersonAccountList) {
			if (StringUtils.isEmpty(fddPersonAccount.getCompanyInfoId())) {
				return R.failed("组织id不能为空");
			}

			FddPersonAccount entity = this.getById(fddPersonAccount.getId());
			if (entity == null) {
				return R.failed("未获取到员工相关记录");
			}
			if (null != entity.getCompanyInfoId()) {
				if (entity.getCompanyInfoId().contains(fddPersonAccount.getCompanyInfoId())) {
					return R.failed("员工已加入公司");
				}
			}
			if (StringUtils.isEmpty(entity.getUnionid())) {
				return R.failed("法大大用户唯一标识为空");
			}
			//组织
			FddCompanyInfo fddCompanyInfo = fddCompanyInfoService.getById(fddPersonAccount.getCompanyInfoId());
			if (fddCompanyInfo == null) {
				return R.failed("未获取到组织相关记录");
			}
			//发送请求
			GetAddEmployeeUrlReq req = new GetAddEmployeeUrlReq();
			req.setToken(fddUtil.getToken());
			req.setCompany(fddCompanyInfo.getCompanyUnionId());
			req.setRedirectUrl(fddConfigProperties.getHrmsUrl() + fddConfigProperties.getAddEmployeeRedirectUrl());
			GetAddEmployeeUrlReq.EmployeeInfo employeeInfo = new GetAddEmployeeUrlReq.EmployeeInfo();
			employeeInfo.setUnionId(entity.getUnionid());
			req.setEmployeeInfo(employeeInfo);
			//发送请求
			OrgClient orgClient = new OrgClient(fddUtil.getFadadaApiClient());
			BaseRsp<GetAddEmployeeUrlRsp> rsp = orgClient.getAddEmployeeUrl(req);
			reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName(), req, rsp);
			//校验参数
			if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
				entity.setCompanyInfoId(fddPersonAccount.getCompanyInfoId());
				return new R<>(rsp.getData().getAddGroupEmployeeUrl());
			} else {
				return R.failed(rsp.getMsg());
			}
		}
		return null;
	}
	@Override
	public R<String> delEmployee(String id, List<String> companyUnionIds, String unionIds) throws ApiException {
		FddPersonAccount entity = this.getById(id);
		if (entity == null) {
			return R.failed("未获取到员工相关记录");
		}
		if (StringUtils.isEmpty(entity.getCompanyInfoId())) {
			return R.failed("员工未加入公司");
		}
		//判断是否印章授权了
		long fddSealPersonCount = fddSealPersonAuthService.count(Wrappers.<FddSealPersonAuth>query().lambda().eq(FddSealPersonAuth::getFddPersonAccountId, entity.getId()));
		if (fddSealPersonCount > CommonConstants.ZERO_INT) {
			return R.failed("请先取消客服印章授权");
		}
		for (String unionId : companyUnionIds) {
			//组织
			FddCompanyInfo fddCompanyInfo = fddCompanyInfoService.getById(unionId);
			if (fddCompanyInfo == null) {
				return R.failed("未获取到组织相关记录");
			}
			//发送请求
			DelSubEmployeeReq req = new DelSubEmployeeReq();
			req.setToken(fddUtil.getToken());
			req.setCompany(fddCompanyInfo.getCompanyUnionId());
			DelSubEmployeeReq.EmployeeInfo employeeInfo = new DelSubEmployeeReq.EmployeeInfo();
			employeeInfo.setUnionId(entity.getUnionid());
			req.setEmployeeInfo(employeeInfo);
			//发送请求
			OrgClient orgClient = new OrgClient(fddUtil.getFadadaApiClient());
			BaseRsp rsp = orgClient.delSubEmployee(req);
			reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName(), req, rsp);
			//校验参数
			if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
				baseMapper.delEmployee(entity.getId(),unionIds);
			} else {
				if (!Common.isEmpty(unionIds)) {
					baseMapper.delEmployee(entity.getId(), unionIds.concat(",").concat(unionId));
				}else {
					baseMapper.delEmployee(entity.getId(), unionId);
				}
				return R.failed(rsp.getMsg());
			}
		}
		return R.ok();
	}

	@Override
	public R<String> sendAuthMessage(String id) throws ApiException {
		FddPersonAccount entity = this.getById(id);
		if (entity == null) {
			return R.failed("为获取到员工记录");
		}
		//发送请求
		GetPersonUnionIdUrlReq req = new GetPersonUnionIdUrlReq();
		req.setToken(fddUtil.getToken());
		req.setClientId(entity.getId());
		req.setAuthScheme(CommonConstants.ZERO_INT);
		NoticeReq notice = new NoticeReq();
		//短信发送实名认证链接
		notice.setNotifyWay(CommonConstants.ONE_INT);
		notice.setNotifyAddress(entity.getMoblie());
		req.setNotice(notice);
		//发送人信息
		PersonReq person = new PersonReq();
		person.setIdentNo(entity.getIdCard());
		person.setMobile(entity.getMoblie());
		person.setName(entity.getName());
		req.setPerson(person);
		//实名授权
		req.setAuthScope(CommonConstants.ONE_STRING);
		//是否允许用户在认证页面修改接口所传的个人认证信息
		req.setReRealName(CommonConstants.ONE_INT);
		//跳转链接
		req.setRedirectUrl(fddConfigProperties.getHrmsUrl() + fddConfigProperties.getPersonRedirectUrl());
		//发送请求
		AccountClient accountClient = new AccountClient(fddUtil.getFadadaApiClient());
		BaseRsp<GetUnionIdUrlRsp> rsp = accountClient.getPersonUnionIdUrl(req);
		reqLogService.saveLog(Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getMethodName(), req, rsp);
		//校验参数
		if (StringUtils.equals(rsp.getCode(), FddUtil.SUCCESS)) {
			entity.setRealMessageFlag(CommonConstants.ONE_STRING);
			return new R<>(rsp.getData().getNextUrl());
		} else {
			return R.failed(rsp.getMsg());
		}
	}

	@Override
	public R<List<FddCompanyInfo>> getAllDepart(String id) {
		FddPersonAccount fddPersonAccount = this.getById(id);
		List<String> companyList = Arrays.asList(fddPersonAccount.getCompanyInfoId().split(","));
		List<FddCompanyInfo> fddCompanyInfoList = fddCompanyInfoService.list(Wrappers.<FddCompanyInfo>query().lambda().in(FddCompanyInfo::getId,companyList));
		return new R<>(fddCompanyInfoList);
	}

	@Override
	public R saveInfo(FddPersonAccount fddPersonAccount) {
		long mobileCount = this.count(Wrappers.<FddPersonAccount>query().lambda().eq(FddPersonAccount::getMoblie, fddPersonAccount.getMoblie())
				.eq(FddPersonAccount::getSystemFlag, CommonConstants.ZERO_STRING));
		if(mobileCount>CommonConstants.ZERO_INT){
			return R.failed("手机号已存在");
		}
		long idCardCount = this.count(Wrappers.<FddPersonAccount>query().lambda().eq(FddPersonAccount::getIdCard, fddPersonAccount.getIdCard())
				.eq(FddPersonAccount::getSystemFlag, CommonConstants.ZERO_STRING));
		if(idCardCount>CommonConstants.ZERO_INT){
			return R.failed("身份证号已存在");
		}
		baseMapper.insert(fddPersonAccount);
		return R.ok();
	}

}
