package com.cftech.invoice.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.StringUtils;
import com.cftech.invoice.model.Invoice;
import com.cftech.invoice.dao.InvoiceMapper;
import com.cftech.invoice.model.InvoiceDetail;
import com.cftech.invoice.service.InvoiceService;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.sql.Conds;
import com.cftech.invoice.web.InvoiceHttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 开票信息ServiceImpl
 *
 * @author Buyj
 * @date: 2020-11-25 09:32
 */
@Service("invoiceService")
public class InvoiceServiceImpl extends GenericServiceImpl<Invoice> implements InvoiceService {

    @Autowired
    @Qualifier("invoiceMapper")
    private InvoiceMapper invoiceMapper;

    @Autowired
    private MpAccountsService mpAccountsService;

    @Override
    public GenericDao<Invoice> getGenericMapper() {
        return invoiceMapper;
    }

    @Override
    public JSONObject selectInvoiceDetail(InvoiceDetail invoiceDetail) {
        JSONObject jsonObject = new JSONObject();
        MpAccountsEntity mpAccountsEntity = null;
        if (StringUtils.isNotBlank(invoiceDetail.getAppId())) {
             mpAccountsEntity = mpAccountsService.getMpAccountsAppid(invoiceDetail.getAppId());
        } else {
            jsonObject.put("errorNo","2");
            jsonObject.put("errorMsg","appId不能为空");
            return jsonObject;
        }

        try {
            Map<String, Object> params = new HashMap<String, Object>();
            Conds conds = new Conds();
            conds.equal("o.accounts_id",mpAccountsEntity.getId());
            conds.equal("o.del_flag",0);
            if(StringUtils.isNotBlank(invoiceDetail.getId())){
                conds.equal("o.id",invoiceDetail.getId());
            }
            Sort sort = new Sort("d.create_time", OrderType.DESC);
            params.put("conds", conds);
            params.put("sort", sort);
            List<InvoiceDetail> list = invoiceMapper.selectInvoiceDetail(params);
            jsonObject.put("errorNo","0");
            if(list.size() > 0){
                jsonObject.put("data",list);
            }else{
                jsonObject.put("data",null);
            }
        }catch (Exception e){
            jsonObject.put("errorNo","1");
            jsonObject.put("errorMsg","程序异常");
        }

        return jsonObject;
    }

    @Override
    public JSONObject findFassDefaultEmail(String openid) {
        JSONObject retObj = new JSONObject();
        if (StringUtils.isBlank(openid)) {
            retObj.put("errorNo", 1);
            retObj.put("errorMsg", "Fanss OpenId is not find ");
            return retObj;
        }

        Conds conds = new Conds();
        conds.equal("open_id", openid);
        Sort sort = new Sort("create_time", OrderType.DESC);
        Map<String, Object> params = new HashMap<>();
        params.put("conds", conds);
        params.put("sort", sort);
        List<Invoice> invoices = invoiceMapper.fetchSearchByPage(params);
        if (invoices != null && invoices.size() > 0) {
            retObj.put("errorNo", 0);
            retObj.put("data", invoices.get(0).getEmail());
            return retObj;
        }
        retObj.put("errorNo", 1);
        retObj.put("errorMsg", " data is null ");
        return retObj;
    }

    @Override
    @Transactional
    public JSONObject sendEmail(String appId, String openId, String invoiceId, String email) {
        JSONObject retObj = new JSONObject();
        Invoice invoice = invoiceMapper.fetchById(invoiceId);
        if (invoice == null) {
            retObj.put("errorNo", 1);
            retObj.put("errorMsg", "entity is null");
            return retObj;
        }

        //查询开票详情，存储发票代码以及号码
        if (StringUtils.isBlank(invoice.getInvoiceCode()) || StringUtils.isBlank(invoice.getInvoiceNum())) {
            String result = InvoiceHttpUtil.queryInvoiceResult(invoice);
            if (StringUtils.isNotBlank(result) && result.contains("code")) {
                JSONObject obj = JSONObject.parseObject(result);
                if (obj.getString("code").equals("E0000")) {
                    JSONArray arr = obj.getJSONArray("result");
                    for (int i=0; i<arr.size(); i++) {
                        JSONObject invoiceObj = arr.getJSONObject(i);
                        if (invoice.getInvoiceSerialNum().equals(invoiceObj.getString("serialNo")) && invoiceObj.getString("status").equals("2")) {
                            invoice.setInvoiceCode(invoiceObj.getString("invoiceCode"));
                            invoice.setInvoiceNum(invoiceObj.getString("invoiceNo"));
                            invoice.setDescription(result);
                            invoiceMapper.update(invoice);
                        } else if (invoice.getInvoiceSerialNum().equals(invoiceObj.getString("serialNo")) && !invoiceObj.getString("status").equals("2")) {
                            invoice.setDescription(result);
                            invoiceMapper.update(invoice);
                            retObj.put("errorNo", 1);
                            retObj.put("errorMsg", invoiceObj.getString("statusMsg"));
                            return retObj;
                        }
                    }
                }
            }
        }

        String result = InvoiceHttpUtil.deliveryInvoice(invoice, email);
        JSONObject obj = JSONObject.parseObject(result);
        if (obj.containsKey("code") && obj.getString("code").equals("E0000")) {
            retObj.put("errorNo", 0);
            retObj.put("errorMsg", "推送成功");
            return retObj;
        }

        retObj.put("errorNo", 1);
        retObj.put("errorMsg", obj.getString("describe"));
        return retObj;
    }
}