package com.jkcredit.invoice.credit.interserver;

import com.alibaba.fastjson.JSONObject;
import com.jkcredit.invoice.common.DataResult;
import com.jkcredit.invoice.mapper.customer.CustomerMapper;
import com.jkcredit.invoice.mapper.customer.CustomerRecMapper;
import com.jkcredit.invoice.model.entity.customer.Customer;
import com.jkcredit.invoice.model.entity.customer.CustomerCarRec;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.service.customer.CustomerService;
import com.jkcredit.invoice.service.lowerservice.CustomeLowerService;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.RespR;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.jkcredit.invoice.common.CommonConst.COMPUTE;


/**
 * 企业备案接口实现类
 * @author mumuxigua
 */
@Service("customerInterLowerService")
@Slf4j
public class CustomerInterLowerServiceImpl implements CustomerInterLowerService {


    private static final String PDF = "pdf";
    @Autowired
    CustomeLowerService lowerService;
    @Autowired
    CustomerService customerService;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    CustomerRecMapper customerRecMapper;

    /**
     * 无车 自有车 企业注册
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult customeInterRec(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();
        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-CustomerInterLowerServiceImpl.customeInterRec-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);

            /**
             * 0-接口 1-平台 3.手工录入
             */
            Integer interType = 0;
            //公司名称 companyName
            String name = jsonObject.getString("name");
            //企业税号 companyReferencenum
            String taxpayerCode = jsonObject.getString("taxplayerCode");
            //客户名称
            String customerName = appKey;

            Customer cust = customerMapper.selectByCustomerName(customerName);

            /**
             * 所属类型：
             *1-行业用户  2-自营平台 3-合作商户
             */
            Integer companyType = jsonObject.getInteger("companyType");
            /**
             * 运用类型:
             * 1-快递
             2-速运
             3-货运代理
             4-普通货运
             5-专线运输
             6-其他
             * 运营范围
             */
            Integer operatingRangeType = jsonObject.getInteger("operatingRangeType");
            //联系人
            String contact = jsonObject.getString("contact");
            //联系人电话
            String tel = jsonObject.getString("tel");
            //紧急联系人  companyLeader
            String emergencyContact = jsonObject.getString("emergencyContact");
            //紧急联系人电话 companyLeaderPhone
            String emergencyTel = jsonObject.getString("emergencyTel");
            //购方客户名称
            String buyerName = jsonObject.getString("buyerName");
            //购方税号
            String buyerTaxpayerCode = jsonObject.getString("buyerTaxpayerCode");
            //购方单位地址
            String buyerAddr = jsonObject.getString("buyerAddr");
            //购方电话
            String buyerTel = jsonObject.getString("buyerTel");
            String mail = jsonObject.getString("mail"); // 下游添加邮箱字段 必传
            //购方开户行
            String buyerBank = jsonObject.getString("buyerBank");
            //购方银行账号
            String buyerBankAccount = jsonObject.getString("buyerBankAccount");


            if (StringUtils.isEmpty(data) || null == jsonObject
                    || StringUtils.isEmpty(name)
                    || StringUtils.isEmpty(taxpayerCode)
                    || StringUtils.isEmpty(customerName)
                    || null == companyType
                    || null == operatingRangeType
                    || StringUtils.isEmpty(emergencyContact)
                    || StringUtils.isEmpty(emergencyTel)
                    || StringUtils.isEmpty(contact)
                    || StringUtils.isEmpty(tel)
                    || StringUtils.isEmpty(buyerName)
                    || StringUtils.isEmpty(buyerTaxpayerCode)
                    || StringUtils.isEmpty(buyerAddr)
                    || StringUtils.isEmpty(buyerTel)
                    || StringUtils.isEmpty(buyerBank)
                    || StringUtils.isEmpty(buyerBankAccount)
                    || StringUtils.isEmpty(mail)
            ) {
                return result;
            }

            CustomerRec customerRec = getCustomerRec(interType, name, taxpayerCode, customerName, cust, companyType, operatingRangeType, contact, tel, buyerAddr, buyerTel, buyerBank, buyerBankAccount,mail);

            return getDataResult(data, costtimestart, result, customerRec);
        } catch (Exception e) {
            log.error("[-CustomerInterLowerServiceImpl.customeInterRec-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    private DataResult getDataResult(String data, long costtimestart, DataResult result, CustomerRec customerRec) {
        List<CustomerRec> customerRecs = new ArrayList<CustomerRec>();
        customerRecs.add(customerRec);
        RespR rs = lowerService.customeRec(customerRecs);
        long costtimeend = System.currentTimeMillis();
        log.info("[-CustomerInterLowerServiceImpl.customeInterRec-] result is "
                + rs.toString() + ", request is " + data + " ,costtime="
                + (costtimeend - costtimestart));

        //返回成功
        if (null != rs && rs.getCode() == 0) {

            RespR rs1 = customerService.customeRec(customerRec);
            log.info("[-CustomerInterLowerServiceImpl.customeInterRecRc1-] result is "
                    + rs1.toString() + ", request is " + data + " ,costtime="
                    + (System.currentTimeMillis() - costtimestart));


            if (null != rs1 && rs1.getCode() == 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(rs1.getMsg());
                return result;

            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(rs1.getMsg());
                return result;
            }

        } else {
            result.setData(3);
            result.setCode(200);
            result.setMsg("无法认证");
            return result;
        }
    }

    private CustomerRec getCustomerRec(Integer interType, String name, String taxpayerCode, String customerName, Customer cust, Integer companyType, Integer operatingRangeType, String contact, String tel, String buyerAddr, String buyerTel, String buyerBank, String buyerBankAccount,String mail) {
        CustomerRec customerRec = new CustomerRec();
        //客户名称
        customerRec.setCustomerName(customerName);
        //紧急联系人
        customerRec.setCompanyLeader(contact);
        //紧急联系人电话
        customerRec.setCompanyLeaderPhone(tel);
        //企业名称
        customerRec.setCompanyName(name);
        //企业税号
        customerRec.setCompanyReferencenum(taxpayerCode);
        //公司开户行
        customerRec.setCompanyOpenbank(buyerBank);
        //公司开户行电话
        customerRec.setCompanyOpenbankAcc(buyerBankAccount);
        //公司地址
        customerRec.setCompanyAdress(buyerAddr);
        //公司电话
        customerRec.setCompanyPhone(buyerTel);
        customerRec.setInvoiceMail(mail);
        //0-接口 1-平台
        customerRec.setInterType(interType);
        //业务类型 0 -自有车 1-外协车 2-无车
        customerRec.setBussinessType(String.valueOf(cust.getBussinessType()));
        //运用类型
        customerRec.setOperatingRangeType(operatingRangeType);
        //所属类型
        customerRec.setCompanyType(companyType);
        return customerRec;
    }

    /**
     * 无车 自有车企业查询
     *
     * @param appKey
     * @param api
     * @param data
     * @return
     */
    @Override
    public DataResult customeInterRecQuery(String appKey, String api, String data, String requestid) {

        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-CustomerInterLowerServiceImpl.customeInterRecQuery-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //企业名称
            String companyName = jsonObject.getString("companyName");
            //企业税号
            String taxpayerCode = "";
            if (StringUtils.isEmpty(data) || null == jsonObject) {
                return result;
            }

            CustomerCarRec customerCarRec = new CustomerCarRec();
            customerCarRec.setCustomerName(appKey);
            Customer cust = customerMapper.selectByCustomerName(appKey);
            if(null == cust){
                result.setMsg("查询错误");
                result.setCode(9998);
                return result;
            }
            if( 0 == cust.getBussinessType()){
                taxpayerCode = jsonObject.getString("taxpayerCode");
            }else if(2 == cust.getBussinessType()){
                taxpayerCode = jsonObject.getString("taxplayerCode");
            }
            if (StringUtils.isEmpty(companyName) || StringUtils.isEmpty(taxpayerCode)) {

                result.setMsg("查询错误");
                result.setCode(9998);
                return result;
            }

            CustomerRec customerRec = new CustomerRec();
            customerRec.setCompanyName(companyName);
            customerRec.setCompanyReferencenum(taxpayerCode);
            RespR rs = customerService.customerRecQuery(customerRec);
            long costtimeend = System.currentTimeMillis();
            log.info("[-CustomerInterLowerServiceImpl.customeInterRecQuery-] result is "
                    + rs.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != rs && rs.getCode() == 0) {
                result.setData(1);
                result.setCode(200);
                result.setMsg(rs.getData().toString());
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg(rs.getMsg());
                return result;
            }
        } catch (Exception e) {
            log.error("[-CustomerInterLowerServiceImpl.customeInterRecQuery-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }


    /**
     * @Description 协议上传接口
     * @Author mashengyi
     * @Date 2022/3/27 22:51
     * @Param
     * @Return
     * @Exception
     */
    @Override
    public DataResult customeProtocolUpLoad(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();
        DataResult result = new DataResult();
        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");
        try {
            log.info("[-CustomerInterLowerServiceImpl.customeProtocolUpLoad-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //公司编号
            String companyNum = jsonObject.getString("companyNum");
            //服务开始时间
            String serviceStartTime = jsonObject.getString("serviceStartTime");
            //服务结束时间
            String serviceEndTime = jsonObject.getString("serviceEndTime");
            //协议文件名
            String contractFileName = jsonObject.getString("contractFileName");
            //上传文件转换的base64
            String base64Str = jsonObject.getString("base64Str");
            //协议类型
            Integer serviceType = jsonObject.getInteger("serviceType");
            if (StringUtils.isEmpty(data) || null == jsonObject) {
                return result;
            }
            if (StringUtils.isEmpty(companyNum) || StringUtils.isEmpty(serviceStartTime)
                    || StringUtils.isEmpty(serviceEndTime)
                    || StringUtils.isEmpty(contractFileName)
                    || StringUtils.isEmpty(base64Str)
                    || null == serviceType) {
                return result;
            }
            if (!DateUtil.isValidDate(serviceStartTime)) {
                result.setMsg("日期格式有误");
                return result;
            }
            if (!DateUtil.isValidDate(serviceEndTime)) {
                result.setMsg("日期格式有误");
                return result;
            }
            CustomerRec customerRec2 = new CustomerRec();
            customerRec2.setCustomerName(appKey);
            customerRec2.setCompanyNum(companyNum);
            CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompanyNum(customerRec2);
            if (null == customerRec1) {
                result.setMsg("企业还未备案成功！");
                return result;
            }
            if (null != customerRec1 && customerRec1.getRecStatus() != 1) {
                result.setMsg("企业还未备案成功！");
                return result;
            }
            if (null != customerRec1
                    && StringUtils.isNotBlank(customerRec1.getServiceEndTime())
                    //如果协议到期时间超过60天,协议上传成功不允许重新上传协议
                    && DateUtil.daysBetween(customerRec1.getServiceEndTime(), new Date()) > 60
                    && customerRec1.getContractSuc() == 1) {
                result.setMsg("协议已上传成功，审批中，请勿重复上传协议！");
                return result;
            }
            String fileType = contractFileName.substring(contractFileName.lastIndexOf(".") + 1).toLowerCase();
            if (!PDF.equals(fileType)) {
                result.setMsg("必须是pdf文件!");
                return result;
            }
            int base64StrLength = base64Str.length();
            if (COMPUTE < base64StrLength) {
                result.setMsg("pdf不可超过10M!");
                return result;
            }
            return getDataResult(appKey, data, costtimestart, result, companyNum, serviceStartTime, serviceEndTime, contractFileName, base64Str, serviceType);
        } catch (Exception e) {
            log.error("[-CustomerInterLowerServiceImpl.customeProtocolUpLoad-] get httpclient exception is "
                    + e + ", request is " + data);
        }

        return result;
    }

    private DataResult getDataResult(String appKey, String data, long costtimestart, DataResult result, String companyNum, String serviceStartTime, String serviceEndTime, String contractFileName, String base64Str, Integer serviceType) {
        CustomerRec customerRec = new CustomerRec();
        //服务开始时间
        customerRec.setServiceStartTime(DateUtil.getDistanceHoursFormat(serviceStartTime));
        //服务结束时间
        customerRec.setServiceEndTime(DateUtil.getDistanceHoursFormat(serviceEndTime));
        //协议类型
        customerRec.setServiceType(serviceType);
        //协议名称
        customerRec.setLowerFileName(contractFileName);
        //协议base64编码
        customerRec.setLowerBase64Str(base64Str);
        //客户名称
        customerRec.setCustomerName(appKey);
        customerRec.setCompanyNum(companyNum);
        //接口
        customerRec.setInterType(0);
        List<CustomerRec> customerRecs = new ArrayList<CustomerRec>();
        customerRecs.add(customerRec);
        RespR rs = lowerService.customeRecUpload(customerRecs);
        long costtimeend = System.currentTimeMillis();
        log.info("[-CustomerInterLowerServiceImpl.customeProtocolUpLoad-] result is "
                + rs.toString() + ", request is " + data + " ,costtime="
                + (costtimeend - costtimestart));
        if (null != rs && rs.getCode() == 0) {
            result.setData(1);
            result.setCode(200);
            result.setMsg(rs.getMsg());
            return result;
        } else {
            result.setData(3);
            result.setCode(200);
            result.setMsg(rs.getMsg());
            return result;
        }
    }


    /**
     * @Description 自有车 无车、协议上传状态查询
     * @Author mashengyi
     * @Date 2022/3/27 22:51
     * @Param
     * @Return
     * @Exception
     */
    @Override
    public DataResult customeProtocolStatus(String appKey, String api, String data, String requestid) {
        long costtimestart = System.currentTimeMillis();

        DataResult result = new DataResult();

        result.setData(3);
        result.setCode(200);
        result.setRequestid(requestid);
        result.setMsg("无法认证");

        try {
            log.info("[-CustomerInterLowerServiceImpl.customeProtocolStatus-] request appKey=" + appKey + " ,api=" + api + " ,data=" + data + " ,requestid=" + requestid);
            JSONObject jsonObject = JSONObject.parseObject(data);
            //公司编号
            String companyNum = jsonObject.getString("companyNum");

            if (StringUtils.isEmpty(data) || null == jsonObject) {
                return result;
            }
            if (StringUtils.isEmpty(companyNum)) {
                return result;
            }


            CustomerRec customerRec2 = new CustomerRec();
            customerRec2.setCustomerName(appKey);
            customerRec2.setCompanyNum(companyNum);
            CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompanyNum(customerRec2);
            if (null == customerRec1) {
                result.setMsg("企业还未备案成功！");
                return result;
            }

            if (null != customerRec1 && customerRec1.getRecStatus() != 1) {
                result.setMsg("企业还未备案成功！");
                return result;
            }


            CustomerRec customerRec = new CustomerRec();
            //客户名称
            customerRec.setCustomerName(appKey);
            customerRec.setCompanyNum(companyNum);
            //接口
            customerRec.setInterType(0);

            RespR rs = lowerService.customeRecUploadStatus(customerRec);
            long costtimeend = System.currentTimeMillis();
            log.info("[-CustomerInterLowerServiceImpl.customeProtocolStatus-] result is "
                    + rs.toString() + ", request is " + data + " ,costtime="
                    + (costtimeend - costtimestart));
            if (null != rs && rs.getCode() == 0 && 0 == Integer.parseInt(rs.getData().toString())) {
                result.setData(3);
                result.setCode(200);
                result.setMsg("协议上传状态查询失败，请联系管理员处理");
                return result;
            } else if (null != rs && rs.getCode() == 0 && 0 != Integer.parseInt(rs.getData().toString())) {
                result.setData(1);
                result.setCode(200);
                JSONObject jb = new JSONObject();
                jb.put("status", rs.getData().toString());
                result.setMsg(jb.toString());
                return result;
            } else {
                result.setData(3);
                result.setCode(200);
                result.setMsg("无法认证");
                return result;
            }
        } catch (Exception e) {
            log.error("[-CustomerInterLowerServiceImpl.customeProtocolStatus-] get httpclient exception is "
                    + e + ", request is " + data);
        }

        return result;
    }
}
