package com.dxhy.passengerticket.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.InvoiceUtil;
import com.dxhy.common.util.NumberToCN;
import com.dxhy.common.utils.R;
import com.dxhy.passengerticket.entity.TdxRecordInvoiceDetail;
import com.dxhy.passengerticket.entity.TdxVehicleSaleInvoice;
import com.dxhy.passengerticket.feign.InvoiceDetailService;
import com.dxhy.passengerticket.service.PassengerInvoiceStatisticsService;
import com.dxhy.passengerticket.service.PassengerReimbursementSystemService;
import com.dxhy.passengerticket.service.PassengerTicketService;
import com.dxhy.passengerticket.util.GetInvoiceType;
import com.dxhy.passengerticket.util.MonthTimestamp;
import com.dxhy.passengerticket.vo.InvoiceMainBody;
import com.dxhy.passengerticket.vo.InvoiceTableVo;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * @author xiexuedi
 * @date 2019/05/07 9:51:33
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@RequestMapping("/passengerTicket")
@RestController
@Slf4j
public class PassengerTicketController extends AbstractController {
    @Resource
    private PassengerTicketService passengerTicketService;
    @Resource
    private PassengerReimbursementSystemService passengerReimbursementSystemService;

    @Resource
    private InvoiceDetailService invoiceDetailService;
    @Resource
    private PassengerInvoiceStatisticsService passengerInvoiceStatisticsService;

    /**
     * 查询统计卡片数据
     *
     * @param reportingPeriod
     * @param gfTaxNo
     * @return
     */
    @RequestMapping(value = "selectCard", method = RequestMethod.GET)
    public ResponseEntity<R> selectCard(String reportingPeriod, String gfTaxNo) {
        if ("".equals(reportingPeriod)) {
            return ResponseEntity.ok(R.error("日期不能为空"));
        }
        String dbName = getUserInfo().getDbName();
        Map<String, Object> selectMonthMap = returnSelectMap(reportingPeriod, gfTaxNo);
        // 查询本年的开始时间和结束时间
        String year = reportingPeriod.substring(0, 4);
        Map<String, Object> selectYearMap = new HashMap<>(2);
        selectYearMap.put("year", year);
        selectYearMap.put("gfTaxNo", gfTaxNo);
        // 查询认证发票（卡片）数据
        Map<String, Object> legalizedInvoiceMap =
            passengerInvoiceStatisticsService.selectLegalizedInvoiceCard(selectMonthMap, selectYearMap, dbName);
        Map<String, Object> passengerTicketMap =
            passengerInvoiceStatisticsService.selectpassengerTicketCar(selectMonthMap, selectYearMap, dbName);
        Map<String, Object> otherInvoiceMap =
            passengerInvoiceStatisticsService.selectOtherInvoiceCar(selectMonthMap, selectYearMap, dbName);
        Map<String, Object> map = new HashMap<>(3);
        map.put("legalizedInvoice", legalizedInvoiceMap);
        map.put("passengerTicketMap", passengerTicketMap);
        map.put("otherInvoiceMap", otherInvoiceMap);
        return ResponseEntity.ok(R.ok().put("data", map));
    }

    /**
     * 查询统计表格数据
     *
     * @param reportingPeriod
     * @param gfTaxNo
     * @return
     */
    @RequestMapping(value = "selectTable", method = RequestMethod.GET)
    public ResponseEntity<R> selectTable(String reportingPeriod, String gfTaxNo) {
        if ("".equals(reportingPeriod)) {
            return ResponseEntity.ok(R.error("日期不能为空"));
        }
        String dbName = getUserInfo().getDbName();
        Map<String, Object> selectMonthMap = returnSelectMap(reportingPeriod, gfTaxNo);
        selectMonthMap.put("rzhBelongDate", reportingPeriod.replace("-", ""));
        List<InvoiceTableVo> list = passengerInvoiceStatisticsService.selectTable(selectMonthMap, dbName);
        Map<String, Object> map = new HashMap<>(1);
        map.put("list", list);
        return ResponseEntity.ok(R.ok().put("data", map));
    }

    /**
     * 查询认证发票列表
     *
     * @param params
     * @param curr
     * @param size
     * @return
     */
    @RequestMapping(value = "selectcertifiedInvoiceList", method = RequestMethod.GET)
    public ResponseEntity<R> selectcertifiedInvoiceList(@RequestParam Map<String, Object> params,
        @RequestParam Integer curr, @RequestParam Integer size) {
        String dbName = getUserInfo().getDbName();
        Map<String, Object> map = passengerTicketService.selectcertifiedInvoiceList(params, curr, size, dbName);
        return ResponseEntity.ok(R.ok().put("data", map));
    }

    /**
     * 查询认证发票详情
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selectcertifiedInvoiceDetails", method = RequestMethod.GET)
    public ResponseEntity<R> selectcertifiedInvoiceDetails(String invoiceCode, String invoiceNo, String gfTaxNo,
        String flag) {
        String dbNmae = getUserInfo().getDbName();
        Map<String, Object> map = retrunInvoiceDetilsList(invoiceCode, invoiceNo, gfTaxNo, flag, dbNmae);
        return ResponseEntity.ok(R.ok().put("data", map));

    }

    /**
     * 查询客票列票
     *
     * @param params
     * @param curr
     * @param size
     * @return
     */
    @RequestMapping(value = "selectPassengerTicketList", method = RequestMethod.GET)
    public ResponseEntity<R> selectPassengerTicketList(@RequestParam Map<String, Object> params, Integer curr,
        Integer size) {
        String dbName = getUserInfo().getDbName();
        Map<String, Object> map =
            passengerReimbursementSystemService.selectpassengerTicketList(params, curr, size, dbName);
        return ResponseEntity.ok(R.ok().put("data", map));
    }

    /**
     * 查询客票明细
     *
     * @param invoiceCode
     * @param invoiceNo
     * @return
     */
    @RequestMapping("selectPassengerTicketDetails")
    public ResponseEntity<R> selectPassengerTicketDetails(String invoiceCode, String invoiceNo, String gfTaxNo,
        String selectId, String flag) {

        String dbName = getUserInfo().getDbName();
        String invoiceType = "";
        if (!invoiceCode.isEmpty()) {
            invoiceType = GetInvoiceType.getFplx(invoiceCode);
        }
        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<>(16);
            List<InvoiceMainBody> invoiceSubjectList = passengerTicketService.selectPassengerTheme(selectId, dbName);
            if (invoiceSubjectList.size() == 0) {
                map.put("invoiceSubjectList", "");
            }
            map.put("invoiceSubjectList", invoiceSubjectList.get(0));
            return ResponseEntity.ok(R.ok().put("data", map));
        }

    }

    /**
     * 查询其他发票列表
     *
     * @param params
     * @param curr
     * @param size
     * @return
     */
    @RequestMapping(value = "selectOtherInvoiceList", method = RequestMethod.GET)
    public ResponseEntity<R> selectOtherInvoiceList(@RequestParam Map<String, Object> params, Integer curr,
        Integer size) {
        String dbName = getUserInfo().getDbName();
        Map<String, Object> map = passengerTicketService.selectOtherInvoiceList(params, curr, size, dbName);
        return ResponseEntity.ok(R.ok().put("data", map));
    }

    /**
     * 查询其他发票详情
     *
     * @param invoiceCode
     * @param invoiceNo
     * @param gfTaxNo
     * @return
     */

    @RequestMapping(value = "selectOtherInvoiceDateil", method = RequestMethod.GET)
    public ResponseEntity<R> selectOtherInvoiceDateil(String invoiceCode, String invoiceNo, String gfTaxNo,
        String selectId, String flag) {
        String dbName = getUserInfo().getDbName();
        String invoiceType = "";
        if (StringUtils.isNotBlank(invoiceCode)) {
            InvoiceUtil invoiceUtil = new InvoiceUtil(invoiceCode);
            invoiceType = invoiceUtil.getFplxdm();
        }
        if ("10".equals(invoiceType) || "11".equals(invoiceType) || "04".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<>(16);
            List<InvoiceMainBody> invoiceSubjectList = passengerTicketService.selectPassengerTheme(selectId, dbName);
            if (invoiceSubjectList != null && invoiceSubjectList.size() > 0) {
                map.put("invoiceSubjectList", invoiceSubjectList.get(0));
            }
            return ResponseEntity.ok(R.ok().put("data", map));
        }
    }

    /**
     * 帮助获取参数信息
     *
     * @param reportingPeriod
     * @param gfTaxNo
     * @return
     */
    private static Map<String, Object> returnSelectMap(String reportingPeriod, String gfTaxNo) {
        String monthStart = MonthTimestamp.motnthStart(reportingPeriod);
        String monthEnd = MonthTimestamp.motnthEnd(reportingPeriod);
        // 查询条件月份的开始时间跟结束时间
        Map<String, Object> selectMonthMap = new HashMap<>(3);
        selectMonthMap.put("monthStart", monthStart);
        selectMonthMap.put("monthEnd", monthEnd);
        selectMonthMap.put("gfTaxNo", gfTaxNo);
        return selectMonthMap;
    }

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

    /**
     * 对feign调用结果进行处理
     *
     * @return
     */
    private Map<String, Object> retrunInvoiceDetailsList(ResponseEntity<R> rResponseEntity, Map<String, Object> map,
        InvoiceMainBody invoiceMainBody) {
        R body = rResponseEntity.getBody();
        Map<String, Object> listMap = (Map<String, Object>)body.get("data");
        if ("03".equals(invoiceMainBody.getInvoiceType())) {
            List<TdxVehicleSaleInvoice> list =
                JSON.parseArray((String)listMap.get("list"), TdxVehicleSaleInvoice.class);
            List<TdxVehicleSaleInvoice> tDxVehicleSaleInvoice = new ArrayList<>();
            for (TdxVehicleSaleInvoice tdxVehicleSaleInvoice : list) {
                tDxVehicleSaleInvoice.add(tdxVehicleSaleInvoice);
            }
            map.put("invoiceDetails", tDxVehicleSaleInvoice);
        } else {
            List<TdxRecordInvoiceDetail> list =
                JSON.parseArray((String)listMap.get("list"), TdxRecordInvoiceDetail.class);
            List<TdxRecordInvoiceDetail> tDxRecordInvoiceDetList = new ArrayList<>();
            if (list.size() > 0) {
                for (TdxRecordInvoiceDetail tDxRecordInvoiceDetail : list) {
                    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;
    }

}
