/*
 *    Copyright (c) 2018-2025, hnqz 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 pig4cloud.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: hnqz
 */
package com.qunzhixinxi.hnqz.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.entity.SysDeptSub;
import com.qunzhixinxi.hnqz.admin.entity.WmDaAgent;
import com.qunzhixinxi.hnqz.admin.entity.WmDaDrugEnt;
import com.qunzhixinxi.hnqz.admin.entity.input.DeptSubLimitAmountInput;
import com.qunzhixinxi.hnqz.admin.entity.input.SettleAmountMonitorInput;
import com.qunzhixinxi.hnqz.admin.entity.output.SettleAmountMonitorOutput;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.EnableEnum;
import com.qunzhixinxi.hnqz.admin.enums.SubjectLocation;
import com.qunzhixinxi.hnqz.admin.enums.SubjectTypeEnum;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptMapper;
import com.qunzhixinxi.hnqz.admin.mapper.SysDeptSubMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaAgentMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmDaDrugEntMapper;
import com.qunzhixinxi.hnqz.admin.service.SysDeptSubService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * 部门管理
 *
 * @author ryz
 * @date 2021-04-19 16:02:30
 */
@Service
@AllArgsConstructor
public class SysDeptSubServiceImpl extends ServiceImpl<SysDeptSubMapper, SysDeptSub> implements SysDeptSubService {


	private final SysDeptSubMapper sysDeptSubMapper;

	private final SysDeptMapper sysDeptMapper;

	private final WmDaAgentMapper wmDaAgentMapper;

	private final WmDaDrugEntMapper wmDaDrugEntMapper;

	@Override
	@Transactional
	public R updateSubLimitAmount(DeptSubLimitAmountInput input) {

		List<SysDeptSub> subInputList = input.getSubList();
		for (SysDeptSub deptSub : subInputList) {
			this.baseMapper.updateById(deptSub);
		}
		return R.ok();
	}

	@Override
	public List<SettleAmountMonitorOutput> getSettleAmountMonitor(List<String> idCards, List<Integer> settleNoteIds, SubjectLocation location) {
		SettleAmountMonitorInput monitorInput = new SettleAmountMonitorInput(idCards, settleNoteIds, location);
		return sysDeptSubMapper.getSettleAmountMonitor(monitorInput);
	}

	@Override
	public List<SettleAmountMonitorOutput> getYaoyiAmountMonitor(List<String> idCards, List<Integer> settleNoteIds, SubjectLocation location) {
		SettleAmountMonitorInput monitorInput = new SettleAmountMonitorInput(idCards, settleNoteIds, location);
		return sysDeptSubMapper.getYaoyiAmountMonitor(monitorInput);
	}

	@Override
	public List<SettleAmountMonitorOutput> getDeptAmountMonitor(Set<Integer> userIds, List<Integer> settleNoteIds, SubjectLocation location) {
		SettleAmountMonitorInput monitorInput = new SettleAmountMonitorInput(userIds, settleNoteIds, location);
		return sysDeptSubMapper.getDeptAmountMonitor(monitorInput);
	}

	/**
	 * 获取税源地的配置信息
	 *
	 * @param deptId   部门id
	 * @param location 税源地
	 * @return 税源地记录
	 */
	@Override
	public SysDeptSub getDeptSub(Integer deptId, SubjectLocation location) {
		// 结算渠道
		SysDeptSub sysDeptSub = this.getOne(Wrappers.<SysDeptSub>lambdaQuery()
				.eq(SysDeptSub::getDeptId, deptId)
				.eq(SysDeptSub::getSubjectLocation, location)
				.eq(SysDeptSub::getEnableFlag,SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode())
		);

		if (null == sysDeptSub || StringUtils.isBlank(sysDeptSub.getAppId())) {
			throw new RuntimeException("企业结算信息不存在");
		}

		return sysDeptSub;
	}

	/**
	 * 结算管理配置
	 *
	 * @param input
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveSettleConfig(DeptSubLimitAmountInput input) {
		// 更新结算主体
		String[] subTypeArr = input.getSubList().stream()
				.map(sysDeptSub -> sysDeptSub.getSubjectLocation().getGigType().name())
				.distinct()
				.toArray(String[]::new);
		SysDept dept = sysDeptMapper.selectById(input.getDeptId());
		if (dept.getLevel() == 2) {
			// 药企
			wmDaDrugEntMapper.update(null, Wrappers.<WmDaDrugEnt>lambdaUpdate()
					.eq(WmDaDrugEnt::getDeptId, String.valueOf(input.getDeptId()))
					.eq(WmDaDrugEnt::getEnableFlag, EnableEnum.ENABLE.val())
					.eq(WmDaDrugEnt::getDelFlag, DelEnum.NOT_DEL.val())
					.set(WmDaDrugEnt::getSubjectType, subTypeArr));
		} else if (dept.getLevel() == 3) {
			// 更新agent
			wmDaAgentMapper.update(null, Wrappers.<WmDaAgent>lambdaUpdate()
					.eq(WmDaAgent::getDeptId, String.valueOf(input.getDeptId()))
					.eq(WmDaAgent::getEnableFlag, EnableEnum.ENABLE.val())
					.eq(WmDaAgent::getDelFlag, DelEnum.NOT_DEL.val())
					.set(WmDaAgent::getSubjectType, subTypeArr));
		}
		// 更新dept
		sysDeptMapper.update(null, Wrappers.<SysDept>lambdaUpdate()
				.eq(SysDept::getDeptId, input.getDeptId())
				.set(SysDept::getSubjectType, subTypeArr));
		// 先设置所有deptSub为无效
		SysDeptSub deptSubWhere = new SysDeptSub();
		deptSubWhere.setDeptId(input.getDeptId());
		sysDeptSubMapper.update(deptSubWhere, Wrappers.<SysDeptSub>lambdaUpdate()
				.eq(SysDeptSub::getDeptId, input.getDeptId())
				.set(SysDeptSub::getEnableFlag, SubjectTypeEnum.ENABLE_FLAG_FALSE.getCode()));

		// 更新/保存deptSub
		input.getSubList().forEach(sysDeptSub -> {
			SysDeptSub queryDeptSub = sysDeptSubMapper.selectOne(Wrappers.<SysDeptSub>lambdaQuery()
					.eq(SysDeptSub::getDeptId, input.getDeptId())
					.eq(SysDeptSub::getSubjectLocation, sysDeptSub.getSubjectLocation()));
			if (queryDeptSub != null) {
				// 更新
				SysDeptSub updateDeptSub = new SysDeptSub();
				updateDeptSub.setSubId(queryDeptSub.getSubId());
				updateDeptSub.setSubjectChannel(sysDeptSub.getSubjectChannel() == null ? 0 : sysDeptSub.getSubjectChannel());
				updateDeptSub.setSubjectLocation(sysDeptSub.getSubjectLocation());
				updateDeptSub.setSubjectInvoiceCategory(sysDeptSub.getSubjectInvoiceCategory());
				updateDeptSub.setLimitAmount(sysDeptSub.getLimitAmount());
				updateDeptSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
				updateDeptSub.setUpdateTime(LocalDateTime.now());
				sysDeptSubMapper.updateById(updateDeptSub);
			} else {
				// 新增
				SysDeptSub insertDeptSub = new SysDeptSub();
				insertDeptSub.setDeptId(input.getDeptId());
				insertDeptSub.setSubjectType(String.valueOf(sysDeptSub.getSubjectLocation().getGigType().getCode()));
				insertDeptSub.setSubjectChannel(sysDeptSub.getSubjectChannel() == null ? 0 : sysDeptSub.getSubjectChannel());
				insertDeptSub.setSubjectLocation(sysDeptSub.getSubjectLocation());
				insertDeptSub.setSubjectInvoiceCategory(sysDeptSub.getSubjectInvoiceCategory());
				insertDeptSub.setLimitAmount(sysDeptSub.getLimitAmount());
				insertDeptSub.setEnableFlag(SubjectTypeEnum.ENABLE_FLAG_TRUE.getCode());
				sysDeptSubMapper.insert(insertDeptSub);
			}
		});
	}
}
