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

import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bContractAddRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.B2bContractAddResponse;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.CompanyAddRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.CompanyAddResponse;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.CompanyEditRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.CompanyEditResponse;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.CompanyQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.CompanyQueryResponse;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.ConfirmContractAddRequest;
import cn.com.taiji.sdk.model.comm.protocol.eoms.company.ConfirmContractAddResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jkcredit.invoice.mapper.customer.CustomerMapper;
import com.jkcredit.invoice.mapper.customer.CustomerRecMapper;
import com.jkcredit.invoice.mapper.customer.CustomerRechargeMapper;
import com.jkcredit.invoice.model.entity.CustomerRecharge;
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.upservice.CommInterFace;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.MathUtil;
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.transaction.annotation.Transactional;

import static com.jkcredit.invoice.common.CommonConst.REC_STATUS_SUC;
import static com.jkcredit.invoice.common.CommonConst.REC_STATUS_UN;

/**
 * 客户操作接口实现类
 * @author mumuxigua
 */
@Service("customerService")
@Slf4j
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {


    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    CustomerRechargeMapper customerRechargeMapper;

    @Autowired
    CommInterFace commInterFace;

    @Autowired
    CustomerRecMapper customerRecMapper;

    @Autowired
    CustomerService customerService;

    @Override
    public IPage findAllCustomers(Page page, Customer customer) {
        return baseMapper.selectAllByPage(page, customer);
    }

    @Override
    public IPage findAllNomoneyCustomers(Page page, Customer customer) {
        return customerMapper.selectAllByPageForNoMoney(page, customer);
    }


    @Override
    public IPage findAllNomoneyCustomersByZero(Page page, Customer customer) {
        return customerMapper.selectAllByPageForNoMoneyByZero(page, customer);
    }

    @Override
    public Boolean addCustomers(Customer customer) {
        log.info("开始添加客户信息：CustomerServiceImpl.addCustomers{}", customer);
        customer.setFirstSign(DateUtil.getCurrentDateStr());
        if (customerMapper.selectByCustomerName(customer.getCustomerName()) != null) {
            return false;
        }
        return customerMapper.insert(customer) > 0;
    }

    @Override
    public Boolean updateCustomer(Customer customer) {
        Customer customer1 = customerMapper.selectByCustomerName(customer.getCustomerName());
        customer1.setAccstatus(customer.getAccstatus());
        log.info("修改客户状态{}",customer1);
        return customerMapper.updateByPrimaryKeySelective(customer1) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean customRecharge(CustomerRecharge customerRecharge) {
        log.info("开始充值：CustomerServiceImpl.customRecharge{}", customerRecharge);
        if (null == customerRecharge.getRechargeMony() || "".equals(customerRecharge.getRechargeMony())) {
            log.error("充值失败：CustomerServiceImpl.getRechargeMony：" + customerRecharge.getRechargeMony());
            return false;
        }
        Customer customer = customerMapper.selectByCustomerName(customerRecharge.getCustomerName());
        Double currentMoney = MathUtil.add(customer.getAccountBalance(), customerRecharge.getRechargeMony());
        customer.setAccountBalance(currentMoney);
        customerMapper.updateByPrimaryKeySelective(customer);
        customerRecharge.setRechargeTime(DateUtil.getCurrentDateStr());
        customerRecharge.setBeforeMony(customer.getAccountBalance());
        customerRecharge.setCompanyName(customer.getCompany());
        customerRechargeMapper.insert(customerRecharge);
        log.info("充值结束：CustomerServiceImpl.customRecharge{}", customerRecharge);
        return true;
    }

    @Override
    public RespR contractAdd(CustomerRec customerRec) {
        log.info("开始上传协议：CustomerServiceImpl.contractAdd{}", customerRec);
        if (customerRec.getRecStatus().intValue() == REC_STATUS_UN) {
            return new RespR(false, "无法上传协议，未注册");
        }
        B2bContractAddRequest b2bContractAddRequest = new B2bContractAddRequest();
        b2bContractAddRequest.setCompanyNum(customerRec.getCompanyNum());
        b2bContractAddRequest.setServiceStartTime(DateUtil.dateToTime(customerRec.getServiceStartTime()));
        b2bContractAddRequest.setServiceEndTime(DateUtil.dateToTime(customerRec.getServiceEndTime()));
        b2bContractAddRequest.setServiceType(customerRec.getServiceType());
        b2bContractAddRequest.setContractFileName(customerRec.getContractFileName());
        b2bContractAddRequest.setBase64Str(customerRec.getBase64Str());
        RespR<B2bContractAddResponse> responseRespR = commInterFace.b2bContractAdd(b2bContractAddRequest);
        if (responseRespR.getCode() == 1) {
            log.info("协议上传失败：CustomerServiceImpl.contractAdd{}---msg{}", customerRec, responseRespR.getMsg());
            //解决下游客户传递企业注册信息未传递协议信息时，备案文档无法下载问题，可以由业务人员在协议信息中补填协议信息，进行备案文档下载
            customerRecMapper.updateByPrimaryKeySelective(customerRec);
            return new RespR(false,responseRespR.getMsg());
        }else{
            log.info("协议上传成功：CustomerServiceImpl.contractAdd");
            customerRec.setContractSuc(1);
            customerRec.setContrantNum(responseRespR.getData().getContrantNum());
            customerRecMapper.updateByPrimaryKeySelective(customerRec);
            return new RespR("协议上传成功");
        }

    }

    @Override
    public RespR promiseAdd(CustomerRec customerRec) {
        log.info("开始上传承诺协议：CustomerServiceImpl.promiseAdd{}", customerRec);
        if (customerRec.getRecStatus().intValue() == REC_STATUS_UN) {
            return new RespR(false, "无法上传承诺协议，未注册");
        }
        ConfirmContractAddRequest b2bContractAddRequest = new ConfirmContractAddRequest();
        b2bContractAddRequest.setCompanyNum(customerRec.getCompanyNum());
        b2bContractAddRequest.setContractFileName(customerRec.getPromiseFileName());
        b2bContractAddRequest.setBase64Str(customerRec.getPromiseBase64Str());
        RespR<ConfirmContractAddResponse> responseRespR = commInterFace.promiseAdd(b2bContractAddRequest);
        if (responseRespR.getCode() == 1) {
            log.info("传承协议上传失败：CustomerServiceImpl.promiseAdd{}---msg{}", customerRec, responseRespR.getMsg());
            customerRec.setPromiseFileStatus("2");
            customerRecMapper.updatePromiseInfo(customerRec);
            return new RespR(false,responseRespR.getMsg());
        }else{
            log.info("传承协议上传成功：CustomerServiceImpl.promiseAdd");
            customerRec.setPromiseFileStatus("3");
            customerRec.setPromiseNum(responseRespR.getData().getContractNum());
            customerRecMapper.updatePromiseInfo(customerRec);
            return new RespR("传承协议上传成功");
        }
    }

    @Override
    public RespR contractStatusFail(CustomerRec customerRec) {
        log.info("协议上传失败状态确认：CustomerServiceImpl.contractStatusFail{}", customerRec);

        if (customerRec.getRecStatus().intValue() == REC_STATUS_UN) {
            return new RespR(false, "无法更新协议状态，还未注册");
        }
        //协议上传失败状态
        customerRec.setContractStatus(1);
        customerRecMapper.updateContractStatus(customerRec);

        return new RespR("协议上传失败状态操作完成");
    }

    @Override
    public RespR contractStatusProcess(CustomerRec customerRec) {
        log.info("协议上传成功，审批中状态确认：CustomerServiceImpl.contractStatusProcess{}", customerRec);

        if (customerRec.getRecStatus().intValue() == REC_STATUS_UN) {
            return new RespR(false, "无法更新协议状态，还未注册");
        }
        //协议上传成功，审批中状态
        customerRec.setContractStatus(2);
        customerRecMapper.updateContractStatus(customerRec);

        return new RespR("协议上传成功，审批中状态操作完成");
    }

    @Override
    public RespR contractStatusSuccess(CustomerRec customerRec) {
        log.info("备案成功状态确认：CustomerServiceImpl.contractStatusSuccess{}", customerRec);

        if (customerRec.getRecStatus().intValue() == REC_STATUS_UN) {
            return new RespR(false, "无法更新协议状态，还未注册");
        }
        //备案成功状态
        customerRec.setContractStatus(3);
        customerRecMapper.updateContractStatus(customerRec);
        return new RespR("备案成功状态操作完成");
    }

    @Override
    public RespR customerRecEditMail(CustomerRec customerRec) {
        log.info("开始更新备案邮箱：CustomerServiceImpl.customerRecEditMail{}", customerRec);
        CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
        if (customerRec1.getRecStatus().intValue() != REC_STATUS_SUC) {
            return new RespR(false, "无法更新邮箱，未备案成功");
        }
        CompanyEditRequest companyEditRequest = new CompanyEditRequest();
        companyEditRequest.setCompanyNum(customerRec.getCompanyNum());
        companyEditRequest.setInvoiceEmail(customerRec.getInvoiceMail());
        RespR<CompanyEditResponse> responseRespR = commInterFace.editEmail(companyEditRequest);
        if (responseRespR.getCode() == 1) {
            log.info("更新备案邮箱失败：CustomerServiceImpl.customerRecEditMail{}---msg{}", customerRec, responseRespR.getMsg());
            return new RespR(false, responseRespR.getMsg());
        } else {
            log.info("更新备案邮箱成功：CustomerServiceImpl.customerRecEditMail");
            customerRecMapper.updateInvoiceMail(customerRec);
            return new RespR("更新备案邮箱成功");
        }
    }

    @Override
    public RespR contractDownload(String id) {
        CustomerRec customerRec = customerRecMapper.selectByPrimaryKeyHasBase64(Integer.valueOf(id));
        return new RespR(customerRec);
    }


    @Override
    public RespR generateWordDownload(String id) {
        CustomerRec customerRec = customerRecMapper.selectByPrimaryKeyHasNoLocalBase64(Integer.valueOf(id));
        return new RespR(customerRec);
    }

    @Override
    public RespR customeRec(CustomerRec customerRec) {
        log.info("开始客户注册：CustomerServiceImpl.customeRec{}", customerRec);
        CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompanyReference(customerRec);
        if (null != customerRec1) {
            return new RespR(false, "客户已经备案成功，无需备案");
        }
        customerRecMapper.updateByPrimaryKeySelective(customerRec);
        CompanyAddRequest companyAddRequest = buildCompany(customerRec);
        log.info("开始客户上游注册：CustomerServiceImpl.customeRec{}", customerRec);
        //注册企业
        RespR<CompanyAddResponse> respR = commInterFace.addCompany(companyAddRequest);
        if (respR.getCode() == 1) {
            log.info("客户上游注册失败：CustomerServiceImpl.customeRec{}，msg{}", customerRec, respR.getMsg());
            customerRec.setRecStatus(2);
            customerRec.setFileMessage(respR.getMsg());
            customerRecMapper.updateByPrimaryKeySelective(customerRec);
            return new RespR(false, respR.getMsg());
        }
        log.info("客户上游注册成功：CustomerServiceImpl.customeRec{}");
        CompanyAddResponse response = respR.getData();
        //注册协议
        String companyNum = response.getCompanyNum();

        customerRec.setRecStatus(1);
        customerRec.setCompanyNum(companyNum);
        customerRecMapper.updateByCompany(customerRec);
        //contractAdd(customerRec);
        return new RespR(true, respR.getData().toString());
    }

    private CompanyAddRequest buildCompany(CustomerRec customerRec) {
        CompanyAddRequest companyAddRequest = new CompanyAddRequest();
        companyAddRequest.setName(customerRec.getCompanyName());
        companyAddRequest.setTaxpayerCode(customerRec.getCompanyReferencenum());
        companyAddRequest.setCompanyType(customerRec.getCompanyType());
        companyAddRequest.setOperatingRangeType(customerRec.getOperatingRangeType());
        companyAddRequest.setContact(customerRec.getCompanyLeader());
        companyAddRequest.setTel(customerRec.getCompanyLeaderPhone());
        companyAddRequest.setBuyerName(customerRec.getCompanyName());
        companyAddRequest.setBuyerTaxpayerCode(customerRec.getCompanyReferencenum());
        companyAddRequest.setBuyerAddr(customerRec.getCompanyAdress());
        companyAddRequest.setBuyerTel(customerRec.getCompanyPhone());
        companyAddRequest.setBuyerBank(customerRec.getCompanyOpenbank());
        companyAddRequest.setBuyerBankAccount(customerRec.getCompanyOpenbankAcc());
        companyAddRequest.setEmergencyTel(customerRec.getCompanyLeaderPhone());
        companyAddRequest.setEmergencyContact(customerRec.getCompanyLeader());
        companyAddRequest.setCompanyType(customerRec.getCompanyType());
        return companyAddRequest;
    }

    @Override
    public RespR customerRecQuery(CustomerRec customerRec) {
        log.info("查询注册信息：CustomerServiceImpl.customerRecQuery{}", customerRec);
        CompanyQueryRequest companyQueryRequest = new CompanyQueryRequest();
        companyQueryRequest.setCompanyName(customerRec.getCompanyName());
        companyQueryRequest.setTaxpaterCode(customerRec.getCompanyReferencenum());
        RespR<CompanyQueryResponse> responseRespR = commInterFace.companyQuery(companyQueryRequest);
        if (responseRespR.getCode() == 1) {
            return new RespR(false, responseRespR.getMsg());
        } else {
            return new RespR(responseRespR.getData().getItems());
        }
    }

    @Override
    public RespR updateCustomerRecStatus(CustomerRec customerRec) {
        log.info("更新注册信息：CustomerServiceImpl.customerRecQuery{}", customerRec);
        CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
        customerRec1.setRecStatus(customerRec.getRecStatus());
        int i = customerRecMapper.updateByPrimaryKey(customerRec1);
        if (i <= 0) {
            log.info("更新注册信息失败：CustomerServiceImpl.customerRecQuery{}", customerRec);
            return new RespR(false);
        }
        log.info("更新注册信息成功：CustomerServiceImpl.customerRecQuery{}", customerRec);
        return new RespR(true);
    }

    @Override
    public Customer getCustomerByAppKeyAndAppSecret(Customer customer) {
        return customerMapper.selectByAppKeyAndAppSecret(customer.getCustomerName(), customer.getAppSecret());
    }

    /**
     * 余额校验
     *
     * @param customerName
     * @return
     */
    @Override
    public boolean checkMoneyEnough(String customerName) {
        Customer customer = customerMapper.selectByCustomerName(customerName);
        log.info("客户余额查询：CustomerServiceImpl.checkMoneyEnough{}", customer);
        return customer != null && customer.getAccountBalance() > 0;
    }
}
