package com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.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.insurances.entity.TBusinessOperate;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsuranceDetail;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsurancePolicy;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TInsurancePolicyMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TBusinessOperateService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsuranceDetailService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsurancePolicyService;
import com.yifu.cloud.plus.v1.yifu.insurances.util.BeanCopyUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.LocalDateUtil;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.InsurancePolicyListEditParam;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.InsurancePolicyListParam;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.TInsurancePolicyDetailVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;


/**
 * @author licancan
 * @description 针对表【t_insurance_policy(保单号对应起止时间表)】的数据库操作Service实现
 * @date 2022-12-07 16:40:16
 */
@Service
public class TInsurancePolicyServiceImpl extends ServiceImpl<TInsurancePolicyMapper, TInsurancePolicy> implements TInsurancePolicyService {
	@Resource
	private TBusinessOperateService tBusinessOperateService;
	@Resource
	@Lazy
	private TInsuranceDetailService tInsuranceDetailService;

	/**
	 * 保单号对应起止保时间分页查询
	 *
	 * @param page            分页对象
	 * @param param 查询参数
	 * @return {@link IPage <TInsurancePolicy>}
	 * @author licancan
	 */
	@Override
	public IPage<TInsurancePolicy> pageDiy(Page page, InsurancePolicyListParam param) {
		IPage<TInsurancePolicy> list = this.baseMapper.getInsurancePolicyListPage(page, param);
		// 购买月数
		if (CollectionUtils.isNotEmpty(list.getRecords())){
			list.getRecords().stream().forEach(e ->{
				e.setBuyMonth(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString()));
			});
		}
		return list;
	}

	/**
	 * 保单号对应起止保时间列表（不分页）
	 *
	 * @param param
	 * @return {@link List<TInsurancePolicy>}
	 * @author licancan
	 */
	@Override
	public List<TInsurancePolicy> getInsurancePolicyList(InsurancePolicyListParam param) {
		List<TInsurancePolicy> list = this.baseMapper.getInsurancePolicyList(param);
		return list;
	}

	/**
	 * 通过id查询详情
	 *
	 * @param id
	 * @return {@link R<TInsurancePolicyDetailVO>}
	 * @author licancan
	 */
	@Override
	public R<TInsurancePolicyDetailVO> getDetailById(String id) {
		if(Common.isEmpty(id)){
			return R.failed("id不能为空");
		}
		TInsurancePolicy byId = getById(id);
		if (!Optional.ofNullable(byId).isPresent()){
			return R.failed("数据不存在");
		}
		TInsurancePolicyDetailVO vo = new TInsurancePolicyDetailVO();
		BeanCopyUtils.copyProperties(byId,vo);
		List<TBusinessOperate> list = tBusinessOperateService.getOperateListByBusinessId(id);
		if (CollectionUtils.isNotEmpty(list)){
			vo.setOperateList(list);
		}
		return R.ok(vo);
	}

	/**
	 * 新增，内部调用的，保证调用方把该传的字段都传了（保单号、起止保时间、保险公司、险种）
	 *
	 * @param policy
	 * @return {@link R}
	 * @author licancan
	 */
	@Override
	public R saveTInsurancePolicy(TInsurancePolicy policy) {
		if (StringUtils.isNotEmpty(policy.getPolicyNo())){
			TInsurancePolicy one = this.getOne(Wrappers.<TInsurancePolicy>query().lambda()
					.eq(TInsurancePolicy::getPolicyNo, policy.getPolicyNo())
					.eq(TInsurancePolicy::getDeleteFlag,CommonConstants.ZERO_INT)
					.last(CommonConstants.LAST_ONE_SQL));
			if (!Optional.ofNullable(one).isPresent()){
				this.save(policy);

				//第一次新增插入变更记录表为insert，前端会将insert渲染为批量导入
				TBusinessOperate operate = new TBusinessOperate();
				operate.setBusinessId(policy.getId());
				operate.setDifferenceInfo("insert");
				tBusinessOperateService.save(operate);
			}
		}
		return R.ok();
	}

	/**
	 * 修改保单号对应起止保时间
	 *
	 * @param param
	 * @return {@link R}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R updateInsurancePolicy(InsurancePolicyListEditParam param) {
		TInsurancePolicy tInsurancePolicy = this.baseMapper.selectById(param.getId());
		if (!Optional.ofNullable(tInsurancePolicy).isPresent()){
			return R.failed("数据不存在");
		}
		if (!param.getPolicyNo().equals(tInsurancePolicy.getPolicyNo())){
			return R.failed("保单号不能修改");
		}
		//操作日志
		tBusinessOperateService.saveModificationRecord(param.getId(),tInsurancePolicy,param,null);
		BeanCopyUtils.copyProperties(param,tInsurancePolicy);
		updateById(tInsurancePolicy);
		return R.ok();
	}

	/**
	 * 删除保单号对应起止保时间
	 *
	 * @param id 主键
	 * @return {@link R}
	 * @author licancan
	 */
	@Override
	public R deleteInsurancePolicy(String id) {
		if(Common.isEmpty(id)){
			return R.failed("id不能为空");
		}
		TInsurancePolicy byId = getById(id);
		if (!Optional.ofNullable(byId).isPresent()){
			return R.failed("数据不存在");
		}
		//检验保单号是否被使用，被使用不能删除
		TInsuranceDetail one = tInsuranceDetailService.getOne(Wrappers.<TInsuranceDetail>query().lambda()
				.eq(TInsuranceDetail::getPolicyNo, byId.getPolicyNo())
				.eq(TInsuranceDetail::getDeleteFlag,CommonConstants.ZERO_INT)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Optional.ofNullable(one).isPresent()){
			return R.failed("存在正常关联的承保信息，禁止删除！");
		}
		LambdaUpdateWrapper<TInsurancePolicy> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TInsurancePolicy::getId,id)
				.set(TInsurancePolicy::getDeleteFlag, CommonConstants.ONE_INT);
		update(updateWrapper);
		return R.ok();
	}
}




