package com.jkcredit.invoice.service.lowerservice.impl;

import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bCompanyModel;
import com.jkcredit.invoice.component.SendMailService;
import com.jkcredit.invoice.mapper.binvoce.BillInvoiceMapper;
import com.jkcredit.invoice.mapper.binvoce.SelfCarInvoiceMapper;
import com.jkcredit.invoice.mapper.calculateinfor.NoCarCalculateInforMapper;
import com.jkcredit.invoice.mapper.calculateinfor.SelfCarCalculateInforMapper;
import com.jkcredit.invoice.mapper.customer.CustomerCarRecMapper;
import com.jkcredit.invoice.mapper.customer.CustomerMapper;
import com.jkcredit.invoice.mapper.customer.CustomerRecMapper;
import com.jkcredit.invoice.mapper.waybill.NoCarWaybillImprtMapper;
import com.jkcredit.invoice.mapper.waybill.NoCarWaybillMapper;
import com.jkcredit.invoice.mapper.waybill.SellCarTradeMapper;
import com.jkcredit.invoice.model.entity.customer.Customer;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.model.vo.CompanyVo;
import com.jkcredit.invoice.service.customer.CustomerService;
import com.jkcredit.invoice.service.lowerservice.CustomeLowerService;
import com.jkcredit.invoice.service.manager.ParamService;
import com.jkcredit.invoice.service.upservice.NoCarInterface;
import com.jkcredit.invoice.service.upservice.SelfCarInterface;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.RespR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.jkcredit.invoice.common.CommonConst.*;
import static com.jkcredit.invoice.common.WarnMessageConst.FILING_INFORMATION_IS_EMPTY_MESSAGE;
import static com.jkcredit.invoice.common.WarnMessageConst.PROTOCOL_UPLOAD_INFO_IS_EMPTY_MESSAGE;

/**
 * 企业注册接口实现类
 * @author mumuxigua
 */
@Service("lowerService")
@Slf4j
public class CustomerLowerServiceImpl implements CustomeLowerService {


    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    CustomerRecMapper customerRecMapper;

    @Autowired
    CustomerCarRecMapper customerCarRecMapper;

    @Autowired
    NoCarInterface noCarInterface;

    @Autowired
    SelfCarInterface selfCarInterface;
    @Autowired
    CustomerService customerService;

    @Autowired
    SendMailService sendMailService;

    @Autowired
    ParamService paramService;

    @Autowired
    SelfCarCalculateInforMapper selfCarCalculateInforMapper;

    @Autowired
    SelfCarInvoiceMapper selfCarInvoiceMapper;

    @Autowired
    SellCarTradeMapper sellCarTradeMapper;
    @Autowired
    BillInvoiceMapper billInvoiceMapper;
    @Autowired
    NoCarCalculateInforMapper noCarCalculateInforMapper;
    @Autowired
    NoCarWaybillMapper noCarWaybillMapper;
    @Autowired
    NoCarWaybillImprtMapper noCarWaybillImprtMapper;

    private String mailTemp = "<style class=\"fox_global_style\">div.fox_html_content { line-height: 1.5; }div.fox_html_content { font-size: 10.5pt; font-family: 'Microsoft YaHei UI'; color: rgb(0, 0, 0); line-height: 1.5; }</style> <div><span id=\"_FoxCURSOR\"></span><br></div> <div>您好</div><div>&nbsp;&nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 当前有客户 ${a},主体 ${b} ,录入了${c}的企业注册信息，请尽快处理</div><div><br></div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 谢谢</div><div><br></div><div><br></div><div><br></div><div><span id=\"_FoxFROMNAME\"><div style=\"MARGIN: 10px; FONT-FAMILY: verdana; FONT-SIZE: 10pt\"><br></div></span></div>";

    private String mailProtocolTemp = "<style class=\"fox_global_style\">div.fox_html_content { line-height: 1.5; }div.fox_html_content { font-size: 10.5pt; font-family: 'Microsoft YaHei UI'; color: rgb(0, 0, 0); line-height: 1.5; }</style> <div><span id=\"_FoxCURSOR\"></span><br></div> <div>您好</div><div>&nbsp;&nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 当前有客户 ${a},主体 ${b} ,录入了${c}的协议文件信息，请尽快处理</div><div><br></div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 谢谢</div><div><br></div><div><br></div><div><br></div><div><span id=\"_FoxFROMNAME\"><div style=\"MARGIN: 10px; FONT-FAMILY: verdana; FONT-SIZE: 10pt\"><br></div></span></div>";


    @Override
    public RespR customeRec(List<CustomerRec> customerRecs) {
        log.info("客户备案信息：CustomerLowerServiceImpl.customeRec{}", customerRecs);
        if (customerRecs == null || customerRecs.size() <= 0) {
            return new RespR(false, FILING_INFORMATION_IS_EMPTY_MESSAGE);
        }
        StringBuffer res = new StringBuffer();
        customerRecs.stream().forEach(customerRec -> {
            Customer customer = customerMapper.selectByCustomerName(customerRec.getCustomerName());
            if (customer == null || customer.getAccstatus() != 0) {
                res.append("#" + customerRec.getCustomerName() + "不存在或已经停用;#");
                return;
            }
            if (!customer.getBussinessType().equals(Integer.parseInt(customerRec.getBussinessType()))) {
                res.append("#" + customerRec.getCompanyName() + "业务类型有误;#");
                return;
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(customerRec.getBase64Str())) {
                int length = customerRec.getBase64Str().length() / 1024 / 1024;
                if (length >= 1) {
                    res.append("#" + customerRec.getCompanyName() + "备案信息协议文件不能大于1M;#");
                    return;
                }
            }
            if (StringUtils.isEmpty(customerRec.getCompanyName()) || StringUtils.isEmpty(customerRec.getCompanyReferencenum())) {
                res.append("企业备案名称或税号为空");
                return;
            }
            if (NO_CAR.equals(customerRec.getBussinessType()) && customerRec.getCompanyType() != REC_STATUS_WAIT) {
                res.append("#无车公司类型必须为合作商户#");
                return;
            }
            if (SELF_CAR.equals(customerRec.getBussinessType()) && customerRec.getCompanyType() != REC_STATUS_SUC) {
                res.append("#自有车公司类型必须为行业用户#");
                return;
            }
            //默认备案状态为备案中 2-失败 1-成功 3-等待协议上传 4-停用 0-备案中
            customerRec.setRecStatus(0);
            //主动查询上游接口，如果已经备案则更新
            RespR respR = customerService.customerRecQuery(customerRec);
            if (respR.getCode() == 0) {
                List<B2bCompanyModel> b2bCompanyModels = (List<B2bCompanyModel>) respR.getData();
                if (b2bCompanyModels.size() >= 1) {
                    b2bCompanyModels.forEach(b2bCompanyModel -> {
                        if (b2bCompanyModel.getCompanyType().equals(customerRec.getCompanyType())) {
                            customerRec.setCompanyNum(b2bCompanyModel.getCompanyNum());
                            customerRec.setCompanyType(b2bCompanyModel.getCompanyType());
                            customerRec.setCompanyName(b2bCompanyModel.getCompanyName());
                            customerRec.setRecStatus(1);
                        }
                    });
                } else {
                    log.info("AAAAAAAAAAA" + customerRec.getCompanyName() + b2bCompanyModels.size());
                }
            }
            customerRecInsertOrUpdate(customerRec, customer);
            try {
                String mail = paramService.getParamsByParamName("MAILTO").getParamValue();
                sendMailService.sendMail(mail,
                        mailTemp.replace("${a}", customer.getCustomerName())
                                .replace("${b}", customer.getCompany())
                                .replace("${c}", customerRec.getCompanyName()), customerRec.getCompanyName());
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        if (StringUtils.isEmpty(res.toString())) {
            log.info("客户备案成功：CustomerLowerServiceImpl.customeRec{}", customerRecs);
            return new RespR(true, "成功");
        } else {
            log.info("客户备案失败信息：CustomerLowerServiceImpl.customeRec{},msg{}", customerRecs, res.toString());
            return new RespR(false, res.toString());
        }

    }

    private void customerRecInsertOrUpdate(CustomerRec customerRec, Customer customer) {
        //客户备案信息入表
        CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompanyReferenceAll(customerRec);
        customerRec.setCreatetime(DateUtil.getCurrentDateStr());
        customerRec.setCompanyBelongName(customer.getCompany());
        if (customerRec1 == null) {
            customerRecMapper.insert(customerRec);
        } else {
            if (customerRec1.getCompanyName() != null && !customerRec1.getCompanyName().equals(customerRec.getCompanyName())) {
                CompanyVo companyVo = new CompanyVo();
                companyVo.setNewCompanyName(customerRec.getCompanyName());
                companyVo.setOldCompanyName(customerRec1.getCompanyName());
                if (SELF_CAR.equals(customerRec.getBussinessType())) {
                    //自有车需要更新 各个表的企业名称
                    selfCarCalculateInforMapper.upDateCompany(companyVo);
                    selfCarInvoiceMapper.upDateCompany(companyVo);
                    sellCarTradeMapper.upDateCompany(companyVo);
                    customerCarRecMapper.upDateCompanySelf(companyVo);
                } else if (NO_CAR.equals(customerRec.getBussinessType())) {
                    //无车需要跟新各个表的企业名称
                    customerCarRecMapper.upDateCompanyNo(companyVo);
                    billInvoiceMapper.upDateCompany(companyVo);
                    noCarCalculateInforMapper.upDateCompany(companyVo);
                    noCarWaybillMapper.upDateCompany(companyVo);
                    noCarWaybillImprtMapper.upDateCompany(companyVo);
                }
            }
            customerRec.setId(customerRec1.getId());
            customerRec.setContractSuc(customerRec1.getContractSuc());
            customerRec.setContrantNum(customerRec1.getContrantNum());
            customerRec.setContractFileName(customerRec.getContractFileName() == null ? customerRec1.getContractFileName() : customerRec.getContractFileName());
            customerRec.setBase64Str(customerRec.getBase64Str() == null ? customerRec1.getBase64Str() : customerRec.getBase64Str());
            customerRecMapper.updateByPrimaryKey(customerRec);
        }
    }

    @Override
    public RespR customeRecQueryList(CustomerRec customerRec) {

        return new RespR(customerRecMapper.selectByCustomerNameCpAll(customerRec));
    }

    @Override
    public RespR customeRecQuery(CustomerRec customerRec) {

        return new RespR(customerRecMapper.selectByCustomerNameAndCompany(customerRec));
    }


    @Override
    public RespR customeRecUploadStatus(CustomerRec customerRec) {

        return new RespR(customerRecMapper.selectContractStatusByCustomerNameAndCompanyNum(customerRec));
    }


    @Override
    public RespR customeRecUpload(List<CustomerRec> customerRecs) {
        log.info("客户协议上传信息：CustomerLowerServiceImpl.customeRecUpload{}", customerRecs);
        if (customerRecs == null || customerRecs.size() <= 0) {
            return new RespR(false, PROTOCOL_UPLOAD_INFO_IS_EMPTY_MESSAGE);
        }
        StringBuffer res = new StringBuffer();
        customerRecs.stream().forEach(customerRec -> {
            Customer customer = customerMapper.selectByCustomerName(customerRec.getCustomerName());
            if (customer == null || customer.getAccstatus() != 0) {
                res.append("#" + customerRec.getCustomerName() + "不存在或已经停用;#");
                return;
            }

            //客户备案信息入表
            CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompanyNum(customerRec);
            customerRec.setId(customerRec1.getId());
            customerRecMapper.updateByPrimaryKeySelectiveUpload(customerRec);


            try {
                String mail = paramService.getParamsByParamName("MAILTO").getParamValue();
                sendMailService.sendMail(mail,
                        mailProtocolTemp.replace("${a}", customer.getCustomerName())
                                .replace("${b}", customer.getCompany())
                                .replace("${c}", customerRec1.getCompanyName()), customerRec1.getCompanyName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        if (StringUtils.isEmpty(res.toString())) {
            log.info("客户协议上传成功信息" + "：CustomerLowerServiceImpl.customeRecUpload{}", customerRecs);
            return new RespR(true, "协议上传成功");
        } else {
            log.info("客户协议上传失败信息：CustomerLowerServiceImpl.customeRecUpload{},msg{}", customerRecs, res.toString());
            return new RespR(false, res.toString());
        }

    }
}
