package com.dxhy.jxpt.baseService.sign.service.qsgz.impl;

import com.dxhy.api.model.config.Tax;
import com.dxhy.api.model.config.UserInfo;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.jxpt.baseService.sign.service.qsgz.RulesService;
import com.dxhy.jxpt.baseService.util.CompareNameUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("1003")
public class Rules1003ServiceImpl implements RulesService {

    @Override
    public String validationRules(UserInfo userInfo, String qsType, Map<String, String> pramsMap, TDxRecordInvoice recordInvoice, String invoiceType) {
        if (StringUtils.isBlank(recordInvoice.getGfName())) {
            // 部分公司校验底账购方名称为空
            return "发票无明细比对购方名称失败";
        }
        boolean isBuyerName = this.validBuyerName(userInfo, recordInvoice.getGfName(), recordInvoice.getGfTaxNo());
        if (!isBuyerName) {
            return "购方名称有误!";

        }
        return "";
    }

    @Override
    public String getEdiType() {
        return "1003";
    }

    /**
     * 校验购方名称是否正确
     *
     * @param userInfo  用户信息
     * @param buyerName 购方名称
     * @return 返回结果
     */
    public boolean validBuyerName(UserInfo userInfo, String buyerName, String buyerTaxno) {
        List<Tax> taxList = userInfo.getOrg();
        Map<String, String> map = new HashMap<>();
        for (Tax tax : taxList) {
            tax.setTaxname(CompareNameUtils.changeBrackets(tax.getTaxname().trim()));
            map.put(tax.getTaxno(), tax.getTaxname());
        }
        // List<String> buyerNameList = taxList.stream().map(Tax::getTaxname).collect(Collectors.toList());
        String taxname = map.get(buyerTaxno);
        if (!taxname.equals(CompareNameUtils.changeBrackets(buyerName.trim()))) {
            // 发票上的购方名称不在登录账号能操作的购方税号范围内
            return false;
        }
        return true;
    }
}
