package com.cftech.invoice.service.impl;

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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

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;
    }
}