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.CustomerRec;
import com.jkcredit.invoice.service.customer.CustomerService;
import com.jkcredit.invoice.service.lowerservice.CustomeLowerService;
import com.jkcredit.invoice.util.*;
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.List;


@Service("customerInterLowerService")
@Slf4j
public class CustomerInterLowerServiceImpl implements CustomerInterLowerService {



    @Autowired
    CustomeLowerService lowerService;

    @Autowired
    CustomerService customerService;


    @Autowired
    CustomerMapper customerMapper;


    @Autowired
    CustomerRecMapper customerRecMapper;

    private static final String PDF = "pdf";


    /**
     * 无车 自有车 企业注册
     * @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);

            Integer interType =  0;//0-接口 1-平台 3.手工录入

            String  name = jsonObject.getString("name");//公司名称 companyName
            String  taxpayerCode = jsonObject.getString("taxplayerCode");//企业税号 companyReferencenum
            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");//联系人电话
            String  emergencyContact = jsonObject.getString("emergencyContact");//紧急联系人  companyLeader
            String  emergencyTel = jsonObject.getString("emergencyTel");//紧急联系人电话 companyLeaderPhone

            String  buyerName = jsonObject.getString("buyerName");//购方客户名称
            String  buyerTaxpayerCode = jsonObject.getString("buyerTaxpayerCode");//购方税号
            String  buyerAddr = jsonObject.getString("buyerAddr");//购方单位地址
            String  buyerTel = jsonObject.getString("buyerTel");//购方电话
            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)
                    ){
                return  result;
            }

            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.setInterType(interType);////0-接口 1-平台
            customerRec.setBussinessType(String.valueOf(cust.getBussinessType()));//业务类型 0 -自有车 1-外协车 2-无车
            customerRec.setOperatingRangeType(operatingRangeType);//运用类型
            customerRec.setCompanyType(companyType);//所属类型

            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;
            }
        } catch (Exception e) {
            log.error("[-CustomerInterLowerServiceImpl.customeInterRec-] get httpclient exception is "
                    + e + ", request is " + data);
        }
        return result;
    }

    /**
     * 无车 自有车企业查询
     * @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 = jsonObject.getString("taxplayerCode");//企业税号
        if(StringUtils.isEmpty(data)|| null == jsonObject){
            return  result;
        }
        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");//协议文件名
            String base64Str = jsonObject.getString("base64Str");//上传文件转换的base64
            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;
            }




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


            String fileType = contractFileName.substring(contractFileName.lastIndexOf(".") + 1, contractFileName.length()).toLowerCase();
            if(!PDF.equals(fileType)){
                result.setMsg("必须是pdf文件!");
                return  result;
            }

            int base64StrLength = base64Str.length();
            if(10 * 1024 * 1024 < base64StrLength){
                result.setMsg("pdf不可超过10M!");
                return  result;
            }

            CustomerRec customerRec = new CustomerRec();
            customerRec.setServiceStartTime(DateUtil.getDistanceHoursFormat(serviceStartTime));//服务开始时间
            customerRec.setServiceEndTime(DateUtil.getDistanceHoursFormat(serviceEndTime));//服务结束时间
            customerRec.setServiceType(serviceType);//协议类型
            customerRec.setLowerFileName(contractFileName);//协议名称
            customerRec.setLowerBase64Str(base64Str);//协议base64编码
            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;
            }
        } catch (Exception e) {
            log.error("[-CustomerInterLowerServiceImpl.customeProtocolUpLoad-] get httpclient exception is "
                    + e + ", request is " + data);
        }

        return result;
    }
}
