package cn.superdesk.uniorder.event.invoiceApplySupplierTrigger;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.enums.login.SysLoginTypeEnum;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.invoice.supplier.InvoiceApplySupplier;
import cn.superdesk.uniorder.service.invoice.supplier.InvoiceApplySupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2021/12/28 上午11:04
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/12/28 上午11:04
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class InvoiceApplySupplierTriggerEventListener {

	@Autowired
	private InvoiceApplySupplierService invoiceApplySupplierService;

	@Async
	@EventListener
	public void handleTailUpdateInvoiceApplySupplierFieldSaleIsExportEvent(TailUpdateInvoiceApplySupplierFieldSaleIsExportEvent event) {


		log.info("handleTailUpdateInvoiceApplySupplierFieldSaleIsExportEvent -> TailUpdateInvoiceApplySupplierFieldSaleIsExportEvent -> {}", JSONUtil.toJsonStr(event));

		LoginSysUser loginSysUser         = event.getLoginSysUser();
		List<Long>   queryInvoiceApplyIds = event.getQueryInvoiceApplyIds();

		if (ObjectUtil.isNotNull(loginSysUser.getSaleId()) && loginSysUser.getOutLogin().compareTo(SysLoginTypeEnum.福利商城_侨城汇.getKey()) == 0) {

			List<InvoiceApplySupplier> processResultList = invoiceApplySupplierService.findByIds(queryInvoiceApplyIds);

			// 数量不会多,先简单实现
			processResultList.forEach(invoiceApplySupplier -> {

				if (ObjectUtil.isNotNull(invoiceApplySupplier.getSaleId()) && loginSysUser.getSaleId().compareTo(invoiceApplySupplier.getSaleId()) == 0) {

					InvoiceApplySupplier forUpdate = new InvoiceApplySupplier();
					forUpdate.setId(invoiceApplySupplier.getId());
					forUpdate.setSaleIsExport(ObjectUtil.isEmpty(invoiceApplySupplier.getSaleIsExport()) ? 1 : (invoiceApplySupplier.getSaleIsExport() + 1));

					invoiceApplySupplierService.updateInvoiceApplySupplierByPrimaryKeySelective(forUpdate);

				} else {
					// TODO 如果不等的情况就是 A供应商|商户 还能看 B供应商|商户
				}
			});
		}


	}
}
