package com.dxhy.core.service.export.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FpqsjgEnum;
import com.dxhy.common.enums.QsfsEnum;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.core.dao.TicketDao;
import com.dxhy.core.entity.TicketInvoiceModel;
import com.dxhy.core.model.InvoiceMainBodyVO;
import com.dxhy.core.model.PlaneTicketVo;
import com.dxhy.core.service.export.TicketService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * @author futianhao
 * @date 2020-08-28 企业票池首页
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "rawtypes", "DuplicatedCode"})
@Service
@Slf4j
public class TicketServiceImpl extends MpBaseServiceImpl<TicketDao, TicketInvoiceModel> implements TicketService {
    @Resource
    private TicketDao extTicketDao;

    @Override
    public String queryList(Map<String, Object> paramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(paramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {
            String[] titlelist = {"序号", "发票类型", "发票代码", "发票号码", "开票日期", "销方名称", "销方税号", "金额", "税额", "有效税额", "认证状态",
                "认真类型", "认证日期", "认证方式", "认证人", "底账库采集时间", "签收方式", "签收状态", "签收日期", "签收人", "入账月份", "入账状态", "凭证号",
                "是否末次摊销", "摊销金额", "剩余金额", "业务单号", "票据来源"};

            String[] titleprop = {"xh", "invoiceType", "invoiceCode", "invoiceNo", "invoiceDate", "xfmc", "xfsh",
                "invoiceAmount", "taxAmount", "yxse", "rzzt", "rzlx", "rzrq", "rzfs", "rzr", "createDate", "qsfs",
                "qszt", "qsrq", "qsr", "inAccountMonth", "inAccountStatus", "voucherNo", "amortizeStatus",
                "amortizeAmount", "remainAmortizeAmount", "amortizeDocumentNumber", "sourceSystem"};
            // 需要设置返回列表标题时调用
            json = super.setTitleList(titlelist, titleprop);
            PageHelper.startPage(curr, size);
            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjje = "0";
                String hjse = "0";
                List<TicketInvoiceModel> hjList = super.baseMapper.queryTotal(paramsMap);
                TicketInvoiceModel hjxx = hjList.get(0);
                hjsl = hjxx.getId();
                if (!"0".equals(hjsl)) {
                    hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getInvoiceAmount()));
                    hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.getTaxAmount()));
                }
                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjse", hjse);
            }
            PageHelper.startPage(curr, size);
            List<TicketInvoiceModel> pageList = super.baseMapper.queryTickets(paramsMap);
            PageInfo<TicketInvoiceModel> pageInfo = new PageInfo(pageList);
            // 用于页面返回list对象
            if (pageList.size() > 0) {

                int start = new Long(pageInfo.getStartRow()).intValue();

                for (int i = 0; i < pageList.size(); i++) {
                    pageList.get(i).setXh(String.valueOf(i + start));
                    pageList.get(i).setInvoiceAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getInvoiceAmount())));
                    pageList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount())));

                    for (FpqsjgEnum e : FpqsjgEnum.values()) {
                        if (e.getQsjgDm().equals(pageList.get(i).getQsStatus())) {
                            pageList.get(i).setQsStatus(e.getQsjgMc(e.getIndex()));
                        }
                    }

                    for (QsfsEnum e : QsfsEnum.values()) {
                        if (e.getQsfsDm().equals(pageList.get(i).getQsType())) {
                            pageList.get(i).setQsType(e.getQsfsMc(e.getIndex()));
                        }
                    }
                    if ("1".equals(pageList.get(i).getLybz())) {
                        pageList.get(i).setLybz("票据签收");
                    }
                    if ("1".equals(pageList.get(i).getIsDeduction())) {
                        pageList.get(i).setIsDeduction("不可抵扣");
                    } else if ("0".equals(pageList.get(i).getIsDeduction())) {
                        pageList.get(i).setIsDeduction("可抵扣");
                    }
                }
            }

            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            List<TicketInvoiceModel> resultList = pageInfo.getList();
            json.put("datalist", resultList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }

    @Override
    public JSONObject selectByPramsMap(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        PageHelper.startPage(curr, size);
        List<TicketInvoiceModel> pageList = super.baseMapper.queryTickets(pramsMap);
        PageInfo<TicketInvoiceModel> pageInfo = new PageInfo(pageList);
        json.put("hasNext", pageInfo.isHasNextPage());
        json.put("nextPage", pageInfo.getNextPage());

        // 用于页面展示
        List<TicketInvoiceModel> resultList = pageInfo.getList();
        List<String[]> returnList = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {

            for (int i = 0; i < resultList.size(); i++) {
                // 页面展示需要信息
                String[] dataArray = new String[28];
                dataArray[0] = String.valueOf((curr - 1) * size + i + 1);
                dataArray[1] = exchangeInvoiceType(resultList.get(i).getInvoiceType());
                dataArray[2] = resultList.get(i).getInvoiceCode();
                dataArray[3] = resultList.get(i).getInvoiceNo();
                if (resultList.get(i).getInvoiceDate() != null) {
                    dataArray[4] = resultList.get(i).getInvoiceDate().substring(0, 10);
                }
                dataArray[5] = resultList.get(i).getXfName();
                dataArray[6] = pageList.get(i).getPassenger();
                dataArray[7] = resultList.get(i).getPassengerSfzh();
                dataArray[8] = resultList.get(i).getTrainNumber();
                dataArray[9] = AmountFormatUtil.fmtMicrometer(resultList.get(i).getInvoiceAmount());
                dataArray[10] = resultList.get(i).getTaxRate();
                dataArray[11] = AmountFormatUtil.fmtMicrometer(resultList.get(i).getTaxAmount());
                if ("1".equals(resultList.get(i).getQsStatus())) {
                    dataArray[12] = "已签收";
                } else if ("0".equals(resultList.get(i).getQsStatus())) {
                    dataArray[12] = "未签收";
                }
                if (resultList.get(i).getQsDate() != null) {
                    dataArray[13] = resultList.get(i).getQsDate().substring(0, 10);
                }
                for (QsfsEnum e : QsfsEnum.values()) {
                    if (e.getQsfsDm().equals(pageList.get(i).getQsType())) {
                        String qsfs = e.getQsfsMc(e.getIndex());
                        if ("接口推送".equals(qsfs)) {
                            dataArray[14] = "接口签收";
                        } else {
                            dataArray[14] = qsfs;
                        }
                    }

                }
                dataArray[15] = resultList.get(i).getQsName();
                if ("1".equals(resultList.get(i).getIsDeduction())) {
                    dataArray[16] = "不可抵扣";

                } else if ("0".equals(resultList.get(i).getIsDeduction())) {
                    dataArray[16] = "可抵扣";
                }
                dataArray[17] = resultList.get(i).getBusinessDocumentNumber();
                if (StringUtils.isNotBlank(pageList.get(i).getCreateDate())) {
                    dataArray[18] = pageList.get(i).getCreateDate().substring(0, 10);
                }
                dataArray[19] = resultList.get(i).getSnVoucherNumber();
                dataArray[20] = resultList.get(i).getPostingTime();
                dataArray[21] = resultList.get(i).getImageId();
                dataArray[22] = resultList.get(i).getAccountPeriod();
                dataArray[23] = resultList.get(i).getBzdh();
                dataArray[24] = resultList.get(i).getBzr();
                if (pageList.get(i).getInAccountStatus() != null && "1".equals(pageList.get(i).getInAccountStatus())){
                    dataArray[25] = "已入账";
                }else {
                    dataArray[25] = "未入账";
                }
                dataArray[26] = resultList.get(i).getCompCode();

                returnList.add(dataArray);
            }
        }

        json.put("datalist", returnList);

        return json;
    }

    private String exchangeInvoiceType(String invoiceType) {
        if ("93".equals(invoiceType)) {
            return "飞机票";
        }
        if ("10".equals(invoiceType)) {
            return "增值税电子普通发票";
        }
        if ("92".equals(invoiceType)) {
            return "火车票";
        }
        if ("90".equals(invoiceType)) {
            return "航空运输客票";
        }
        if ("89".equals(invoiceType)) {
            return "公路运输客票";
        }
        if ("88".equals(invoiceType)) {
            return "水路运输客票";
        }
        if ("87".equals(invoiceType)) {
            return "其他运输客票";
        }
        return "";
    }

    @Override
    public List<InvoiceMainBodyVO> selectPassengerTheme(String selectId, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        List<InvoiceMainBodyVO> list = extTicketDao.selectPassengerTheme(selectId);
        List<InvoiceMainBodyVO> returnList = returnInvoiceList(list);
        return returnThousandList(returnList);
    }

    public static List<InvoiceMainBodyVO> returnInvoiceList(List<InvoiceMainBodyVO> list) {
        List<InvoiceMainBodyVO> pageList = new ArrayList<>();
        for (InvoiceMainBodyVO vo : list) {
            if ("01".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("增值税专用发票");
            }
            if ("04".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("增值税普通发票");
            }
            if ("10".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("增值税普通发票（电子）");
            }
            if ("11".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("增值税普通发票（卷式）");
            }
            if ("03".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("机动车销售统一发票");
            }
            if ("02".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("货运运输业增值税专用发票");
            }
            if ("91".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("出租车票");
            }
            if ("92".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("火车票");
            }
            if ("93".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("飞机票");
            }
            if ("94".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("汽车票");
            }
            if ("95".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("定额发票");
            }
            if ("96".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("长途汽车票");
            }
            if ("00".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("其他");
            }
            if ("97".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("通用机打发票");
            }
            if ("98".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("政府非税收收入一般缴款书");
            }
            if ("14".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("增值税电子普通发票（通行费）");
            }
            if ("90".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("航空运输客票");
            }
            if ("89".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("公路运输客票");
            }
            if ("88".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("水路运输客票");
            }
            if ("87".equals(vo.getInvoiceType())) {
                vo.setInvoiceString("其他运输客票");
            }
            if ("0".equals(vo.getQszt())) {
                vo.setQszt("未签收");
            }
            if ("1".equals(vo.getQszt())) {
                vo.setQszt("已签收");
            }
            if ("0".equals(vo.getInvoiceStatus())) {
                vo.setInvoiceStatus("正常");
            }
            if ("1".equals(vo.getInvoiceStatus())) {
                vo.setInvoiceStatus("失控");
            }
            if ("2".equals(vo.getInvoiceStatus())) {
                vo.setInvoiceStatus("作废");
            }
            if ("3".equals(vo.getInvoiceStatus())) {
                vo.setInvoiceStatus("红冲");
            }
            if ("4".equals(vo.getInvoiceStatus())) {
                vo.setInvoiceStatus("异常");
            }
            if ("0".equals(vo.getRzhYesorno())) {
                vo.setRzhYesorno("未认证");
            }
            if ("1".equals(vo.getRzhYesorno())) {
                vo.setRzhYesorno("已认证");
            }
            if ("0".equals(vo.getSourceSystem())) {
                vo.setSourceSystem("票据采集");
            }
            if ("1".equals(vo.getSourceSystem())) {
                vo.setSourceSystem("票据签收");
            }
            if ("2".equals(vo.getSourceSystem())) {
                vo.setSourceSystem("票据采集");
            }
            if ("2".equals(vo.getReimbursementStatus())) {
                vo.setReimbursementStatus("报销中");
            }
            if ("3".equals(vo.getReimbursementStatus())) {
                vo.setReimbursementStatus("已报销");
            }
            if ("0".equals(vo.getQsType())) {
                vo.setQsType("扫码签收");
            }
            if ("1".equals(vo.getQsType())) {
                vo.setQsType("扫描仪签收");
            }
            if ("2".equals(vo.getQsType())) {
                vo.setQsType("app签收");
            }
            if ("3".equals(vo.getQsType())) {
                vo.setQsType("导入签收");
            }
            if ("4".equals(vo.getQsType())) {
                vo.setQsType("手工签收");
            }
            if ("5".equals(vo.getQsType())) {
                vo.setQsType("pdf上传签收");
            }
            if ("1".equals(vo.getRzhType())) {
                vo.setRzhType("勾选认证");
            }
            if ("2".equals(vo.getRzhType())) {
                vo.setRzhType("扫描认证");
            }
            if ("0".equals(vo.getIsDeduction())) {
                vo.setIsDeduction("可抵扣");
            }
            if ("1".equals(vo.getIsDeduction())) {
                vo.setIsDeduction("不可抵扣");
            }
            if (!"".equals(vo.getInvoiceDate()) && vo.getInvoiceDate() != null) {
                String s = vo.getInvoiceDate().substring(0, 11);
                vo.setInvoiceDate(s);
            }
            if (!"".equals(vo.getCreateDate()) && vo.getCreateDate() != null) {
                String s = vo.getCreateDate().substring(0, 11);
                vo.setCreateDate(s);
            }
            if (!"".equals(vo.getQsDate()) && vo.getQsDate() != null) {
                String s = vo.getQsDate().substring(0, 11);
                vo.setQsDate(s);
            }
            if (!"".equals(vo.getReimbursementTime()) && vo.getReimbursementTime() != null) {
                String s = vo.getReimbursementTime().substring(0, 11);
                vo.setReimbursementTime(s);
            }
            pageList.add(vo);
        }
        return pageList;
    }

    public static List<InvoiceMainBodyVO> returnThousandList(List<InvoiceMainBodyVO> list) {
        List<InvoiceMainBodyVO> pageList = new ArrayList<>();
        for (InvoiceMainBodyVO vo : list) {
            if (vo.getInvoiceAmount() != null) {
                vo.setInvoiceAmount(AmountFormatUtil.fmtMicrometer(vo.getInvoiceAmount()));
            }
            if (vo.getTaxAmount() != null) {
                vo.setTaxAmount(AmountFormatUtil.fmtMicrometer(vo.getTaxAmount()));
            }
            if (vo.getTotalAmount() != null) {
                vo.setTotalAmount(AmountFormatUtil.fmtMicrometer(vo.getTotalAmount()));
            }
            pageList.add(vo);
        }
        return pageList;
    }

    @Override
    public List<InvoiceMainBodyVO> selectInvoiceMainBody(String invoiceNo, String invoiceCode, String dbName) {
        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        List<InvoiceMainBodyVO> list = extTicketDao.selectInvoiceMainBody(invoiceNo, invoiceCode);
        return returnInvoiceList(list);
    }

    @Override
    public PlaneTicketVo exchangePlane(InvoiceMainBodyVO entity) {
        PlaneTicketVo vo = new PlaneTicketVo();
        BeanUtils.copyProperties(entity, vo);
        if ("90".equals(entity.getInvoiceType())) {
            vo.setInvoiceType("93");
        }
        vo.setIdentityNumber(entity.getPassengerSfzh());
        vo.setDepartCity(entity.getDepartureCity());
        vo.setArriveCity(entity.getReachingCity());
        vo.setFlightNumber(entity.getTrainNumber());
        vo.setStartDate(entity.getTicketDepartureTime());
        vo.setEndDate(entity.getTicketArrivalTime());
        vo.setElectronicTicketNumber(entity.getTicketNumber());
        if ("88".equals(entity.getInvoiceType()) || "87".equals(entity.getInvoiceType())
            || "89".equals(entity.getInvoiceType())) {
            vo.setAmount(entity.getInvoiceAmount());
            vo.setInvoiceTypeCode(entity.getInvoiceType());
            vo.setElectronicTicketNumber(entity.getInvoiceNo());
        }else if("92".equals(entity.getInvoiceType())){
           if(StringUtils.isNotBlank(entity.getInvoiceAmount()) && StringUtils.isNotBlank(entity.getTaxAmount())){
               String mount = MathUtil.add(entity.getTaxAmount(), entity.getInvoiceAmount());
               vo.setAmount(mount);
           }
        }
        return vo;
    }
    @Override
    public Object exchangeTrain(InvoiceMainBodyVO entity) {
        PlaneTicketVo vo = new PlaneTicketVo();
        BeanUtils.copyProperties(entity, vo);
        vo.setIdentityNumber(entity.getPassengerSfzh());
        vo.setDepartCity(entity.getDepartureCity());
        vo.setArriveCity(entity.getReachingCity());
        vo.setFlightNumber(entity.getTrainNumber());
        vo.setStartDate(entity.getTicketDepartureTime());
        vo.setEndDate(entity.getTicketArrivalTime());
        vo.setFare(entity.getInvoiceAmount());
        vo.setElectronicTicketNumber(entity.getTicketNumber());
        return vo;
    }

    @Override
    public String getGfName(String gfsh) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return super.baseMapper.getGfName(gfsh);
    }

    @Override
    public String getblocName(String gfsh) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return super.baseMapper.getBlocName(gfsh);
    }
}
