package com.dxhy.core.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.NumberToCN;
import com.dxhy.common.utils.R;
import com.dxhy.core.job.entity.TDxRecordInvoiceDetail;
import com.dxhy.core.job.entity.TDxVehicleSaleInvoice;
import com.dxhy.core.model.InvoiceDetails;
import com.dxhy.core.model.InvoiceMainBodyVO;
import com.dxhy.core.service.export.TicketService;
import com.dxhy.core.service.invoicedetail.InvoiceDetailService;
import com.dxhy.core.service.singletable.CoreInvoiceQueryService;
import com.dxhy.core.util.GetInvoiceType;

import lombok.extern.slf4j.Slf4j;

/**
 * 发票查验模块接口类
 *
 * @author user
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@RestController
@Slf4j
@RequestMapping("invoiceDetail/companyPoolInvoiceDetail")
public class TicketQueryController extends AbstractController {

    @Resource
    private CoreInvoiceQueryService coreInvoiceQueryService;

    @Resource
    private InvoiceDetailService invoiceDetailService;

    @Resource
    private TicketService ticketService;

    /**
     * 查询客票明细
     *
     * @return
     */
    @RequestMapping("selectPassengerTicketDetails")
    public ResponseEntity<R> selectPassengerTicketDetails(@RequestBody Map<String, Object> paramsMap) {
       log.info("接收到的参数为 {}",paramsMap);
        String invoiceCode = paramsMap.get("invoiceCode") + "";
        String invoiceNo = paramsMap.get("invoiceNo") + "";
        String gfTaxNo = paramsMap.get("gfTaxNo") + "";
        String selectId = paramsMap.get("selectId") + "";
        String flag = paramsMap.get("flag") + "";

        String dbName = getUserInfo().getDbName();
        String invoiceType = "";
        if (!invoiceCode.isEmpty()) {
            invoiceType = GetInvoiceType.getFplx(invoiceCode);
        }
        log.info("invoiceType {}",invoiceType);
        if ("10".equals(invoiceType)) {
            Map<String, Object> map = retrunInvoiceDetilsList(invoiceCode, invoiceNo, gfTaxNo, flag, dbName);
            return ResponseEntity.ok(R.ok().put("data", map));
        } else {
            Map<String, Object> map = new HashMap<>(1);
            List<InvoiceMainBodyVO> invoiceSubjectList = ticketService.selectPassengerTheme(selectId, dbName);
            log.info("invoiceSubjectList {}",invoiceSubjectList);
            if (invoiceSubjectList.size() == 0) {
                map.put("invoiceSubjectList", "");
                return ResponseEntity.ok(R.ok().put("data", map));
            } else {
                InvoiceMainBodyVO entity = invoiceSubjectList.get(0);
                if ("90".equals(entity.getInvoiceType()) || "92".equals(entity.getInvoiceType())
                    || "88".equals(entity.getInvoiceType()) || "89".equals(entity.getInvoiceType())
                    || "87".equals(entity.getInvoiceType())) {
                    map.put("invoiceSubjectList", ticketService.exchangePlane(entity));
                    log.info("返回数据===> {}",map);
                    return ResponseEntity.ok(R.ok().put("data", map));
                } else {
                    log.info("返回数据=====> {}",map);
                    map.put("invoiceSubjectList", entity);
                    return ResponseEntity.ok(R.ok().put("data", map));
                }

            }
        }

    }

    private Map<String, Object> retrunInvoiceDetilsList(String invoiceCode, String invoiceNo, String gfTaxNo,
        String flag, String dbName) {
        Map<String, Object> map = new HashMap<>(2);
        List<InvoiceMainBodyVO> invoiceSubjectList =
            ticketService.selectInvoiceMainBody(invoiceNo, invoiceCode, dbName);
        InvoiceMainBodyVO invoiceMainBody = invoiceSubjectList.get(0);
        map.put("invoiceSubjectList", invoiceMainBody);
        Map<String, Object> params = new HashMap<>(5);
        params.put("invoiceNo", invoiceNo);
        params.put("invoiceCode", invoiceCode);
        params.put("dbName", dbName);
        params.put("invoiceType", invoiceMainBody.getInvoiceType());
        params.put("flag", flag);
        ResponseEntity<R> rResponseEntity = getDetail(params);
        return retrunInvoiceDetailsList(rResponseEntity, map, invoiceMainBody);
    }

    private ResponseEntity<R> getDetail(Map<String, Object> params) {
        String invoiceNo = (String)params.get("invoiceNo");
        String invoiceCode = (String)params.get("invoiceCode");
        String uuid = invoiceCode + invoiceNo;
        String dbName = (String)params.get("dbName");
        Map<String, Object> map = new HashMap<>(1);
        if ("03".equals(params.get("invoiceType"))) {
            List<TDxVehicleSaleInvoice> list = invoiceDetailService.selectVehicleSaleInvoice(uuid, dbName);
            map.put("list", list);
            return ResponseEntity.ok(R.ok().put("data", map));
        } else {
            if ("1".equals(params.get("flag"))) {
                List<InvoiceDetails> list = invoiceDetailService.selectInspectionDetails(uuid, dbName);
                map.put("list", list);
                return ResponseEntity.ok(R.ok().put("data", map));
            }
            List<InvoiceDetails> list = invoiceDetailService.selectInvoiceDetails(invoiceNo, invoiceCode, dbName);
            map.put("list", list);
            return ResponseEntity.ok(R.ok().put("data", map));
        }
    }

    /**
     * 对feign调用结果进行处理
     *
     * @return
     */
    private Map<String, Object> retrunInvoiceDetailsList(ResponseEntity<R> rResponseEntity, Map<String, Object> map,
        InvoiceMainBodyVO invoiceMainBody) {
        R body = rResponseEntity.getBody();
        Map<String, Object> listMap = (Map<String, Object>)body.get("data");
        if ("03".equals(invoiceMainBody.getInvoiceType())) {
            List<TDxVehicleSaleInvoice> list = (List<TDxVehicleSaleInvoice>)listMap.get("list");
            List<TDxVehicleSaleInvoice> tDxVehicleSaleInvoice = new ArrayList<>();
            for (TDxVehicleSaleInvoice dxVehicleSaleInvoice : list) {
                Map<String, Object> listReturnMap = (Map<String, Object>)dxVehicleSaleInvoice;
                String json = JSON.toJSONString(listReturnMap);
                TDxVehicleSaleInvoice tDxRecordInvoiceDetail1 =
                    JSONObject.parseObject(json, TDxVehicleSaleInvoice.class);
                tDxVehicleSaleInvoice.add(tDxRecordInvoiceDetail1);
            }
            map.put("invoiceDetails", tDxVehicleSaleInvoice);
        } else {
//            List<TDxRecordInvoiceDetail> list = (List<TDxRecordInvoiceDetail>)listMap.get("list");
//            List<TDxRecordInvoiceDetail> tDxRecordInvoiceDetList = new ArrayList<>();
//            if (list.size() > 0) {
//                for (TDxRecordInvoiceDetail dxRecordInvoiceDetail : list) {
//                    String json = JSON.toJSONString(dxRecordInvoiceDetail);
//                    TDxRecordInvoiceDetail tDxRecordInvoiceDetail =
//                        JSONObject.parseObject(json, TDxRecordInvoiceDetail.class);
//                    if (StringUtils.isNotBlank(tDxRecordInvoiceDetail.getTaxRate())) {
//                        tDxRecordInvoiceDetail.setTaxRate(tDxRecordInvoiceDetail.getTaxRate() + "%");
//                    }
//                    tDxRecordInvoiceDetList.add(tDxRecordInvoiceDetail);
//                }
//            }
//            map.put("invoiceDetails", tDxRecordInvoiceDetList);

            List<InvoiceDetails> list = (List<InvoiceDetails>)listMap.get("list");
            List<InvoiceDetails> tDxRecordInvoiceDetList = new ArrayList<>();
            if (list.size() > 0) {
                for (InvoiceDetails dxRecordInvoiceDetail : list) {
                    String json = JSON.toJSONString(dxRecordInvoiceDetail);
                    InvoiceDetails tDxRecordInvoiceDetail =
                            JSONObject.parseObject(json, InvoiceDetails.class);
                    if (StringUtils.isNotBlank(tDxRecordInvoiceDetail.getTaxRate())) {
                        tDxRecordInvoiceDetail.setTaxRate(tDxRecordInvoiceDetail.getTaxRate() + "%");
                    }
                    tDxRecordInvoiceDetList.add(tDxRecordInvoiceDetail);
                }
            }
            map.put("invoiceDetails", tDxRecordInvoiceDetList);
        }
        String stringTotalAmount = "";
        if (!"".equals(invoiceMainBody.getTotalAmount()) && invoiceMainBody.getTotalAmount() != null) {
            String totalAmount = invoiceMainBody.getTotalAmount();
            BigDecimal bd = new BigDecimal(totalAmount);
            stringTotalAmount = NumberToCN.number2CNMontrayUnit(bd);
        } else {
            BigDecimal bd = new BigDecimal(0);
            BigDecimal invoiceAmount = new BigDecimal(invoiceMainBody.getInvoiceAmount());
            bd.add(invoiceAmount);
            BigDecimal taxAmount = new BigDecimal(invoiceMainBody.getTaxAmount());
            bd.add(taxAmount);
            stringTotalAmount = NumberToCN.number2CNMontrayUnit(bd);
        }
        map.put("taxAmountSum", AmountFormatUtil.fmtMicrometer(invoiceMainBody.getTaxAmount()));
        map.put("detailAmountSum", AmountFormatUtil.fmtMicrometer(invoiceMainBody.getInvoiceAmount()));
        map.put("detailAmountTotal", AmountFormatUtil.fmtMicrometer(invoiceMainBody.getTotalAmount()));
        map.put("stringTotalAmount", stringTotalAmount);
        return map;
    }
}
