package com.dxhy.extend.service.bb.impl;

import java.text.DecimalFormat;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.extend.dao.ExtBbrzrbcxDao;
import com.dxhy.extend.model.ExtBbrzrbcxRespVO;
import com.dxhy.extend.service.bb.ExtRzrbcxService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 认证日报实现类
 *
 * @author kangzq
 * @date 2019年5月16日
 * @version 1.0
 */
@Service("rzrbcxService")
@Slf4j

public class ExtRzrbcxServiceImpl extends MpBaseServiceImpl<ExtBbrzrbcxDao, ExtBbrzrbcxRespVO>
    implements ExtRzrbcxService {
    @Resource
    private TabulateRedisService tabulateRedisService;

    public static String[] getRzDate(List<ExtBbrzrbcxRespVO> resultList) {
        String[] array = new String[resultList.size()];
        for (int i = 0; i < resultList.size(); i++) {
            array[i] = resultList.get(i).getRzrq();
        }
        return array;
    }

    public static String[] getDayByMonth(int yearParam, int monthParam) {
        List<String> list = new ArrayList<>();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        aCalendar.set(yearParam, monthParam, 0);
        int year = aCalendar.get(Calendar.YEAR);
        int month = aCalendar.get(Calendar.MONTH) + 1;
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            String aDate = null;
            if (month < 10 && i < 10) {
                aDate = year + "-0" + month + "-0" + i;
            }
            if (month < 10 && i >= 10) {
                aDate = year + "-0" + month + "-" + i;
            }
            if (month >= 10 && i < 10) {
                aDate = year + "-" + month + "-0" + i;
            }
            if (month >= 10 && i >= 10) {
                aDate = year + "-" + month + "-" + i;
            }
            list.add(aDate);
        }
        String[] array = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }

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

        try {
            String company = (String)pramsMap.get("company");
            String menuId = (String)pramsMap.get("menuId");
            json = tabulateRedisService.getTabulateMenu(company, menuId);

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjje = "0";
                String hjse = "0";
                String hjsl = "0";
                String hjdkse = "0";
                ExtBbrzrbcxRespVO respVo = super.baseMapper.selectHjxx(pramsMap);
                if (respVo != null) {
                    if (StringUtils.isNotBlank(respVo.getHjje())) {
                        hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(respVo.getHjje()));
                    }
                    if (StringUtils.isNotBlank(respVo.getHjse())) {
                        hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(respVo.getHjse()));
                    }
                    if (StringUtils.isNotBlank(respVo.getHjsl())) {
                        hjsl = AmountFormatUtil.fmtMicrometer(respVo.getHjsl());
                    }
                    if (StringUtils.isNotBlank(respVo.getDkse())) {
                        hjdkse = AmountFormatUtil.fmtMicrometer(respVo.getDkse());
                    }
                }
                json.put("hjje", hjje);
                json.put("hjse", hjse);
                json.put("hjdkse", hjdkse);
                json.put("hjsl", hjsl);
                log.info("发票认证日报-查询首页合计信息耗时:{}",System.currentTimeMillis()-enter);
            }

            PageHelper.startPage(curr, size);
            List<ExtBbrzrbcxRespVO> pageList = super.baseMapper.selectBbycfpbbHj(pramsMap);
            log.info("发票认证日报-查询列表信息耗时:{}",System.currentTimeMillis()-enter);
            PageInfo<ExtBbrzrbcxRespVO> pageInfo = new PageInfo<>(pageList);
            // 用于页面返回list对象
            if (pageList.size() > 0) {
                int start = (int)pageInfo.getStartRow();
                for (int i = 0; i < pageList.size(); i++) {
                    pageList.get(i).setXh(String.valueOf(i + start));
                    pageList.get(i).setHjje(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getHjje())));
                    pageList.get(i).setHjse(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getHjse())));
                    if (StringUtils.isNotBlank(pageList.get(i).getDkse())) {
                        pageList.get(i)
                            .setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getDkse())));
                    } else {
                        pageList.get(i).setDkse(pageList.get(i).getHjse());
                    }
                    pageList.get(i).setRzrqyr(pageList.get(i).getRzrq().substring(5, 10));

                }
            }

            // 设置记录总数
            json.put("gfsh", pramsMap.get("gfsh"));
            json.put("gfmc", pramsMap.get("gfmc"));
            json.put("total", pageInfo.getTotal());

            List<ExtBbrzrbcxRespVO> resultList = pageInfo.getList();
            json.put("datalist", resultList);
            String skssq = (String)pramsMap.get("skssq");
            String[] mouthArray = getRzDate(resultList);
            json = dataChart(json, resultList, mouthArray);
            log.info("发票认证日报-合计耗时:{}",System.currentTimeMillis()-enter);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    public List<ExtBbrzrbcxRespVO> toList(List<ExtBbrzrbcxRespVO> resultList, String skssq, String[] mouthArray) {

        int length = mouthArray.length;

        // 改进版：提高可读性，但是增加内存使用
        ExtBbrzrbcxRespVO[] voArray = new ExtBbrzrbcxRespVO[length];
        for (int i = 0; i < length; i++) {
            ExtBbrzrbcxRespVO vo = new ExtBbrzrbcxRespVO();
            vo.setRzrq(mouthArray[i]);
            vo.setDkse("0");
            vo.setHjsl("0");
            vo.setHjje("0");
            vo.setHjse("0");

            voArray[i] = vo;
        }
        for (ExtBbrzrbcxRespVO currentVo : resultList) {
            voArray[Integer.parseInt(currentVo.getRzDate()) - 1] = currentVo;
        }
        resultList = Arrays.asList(voArray);
        return resultList;

    }

    public JSONObject dataChart(JSONObject json, List<ExtBbrzrbcxRespVO> resultList, String[] mouthArray) {

        try {
            JSONObject object = new JSONObject();
            JSONArray array = new JSONArray();
            String[] sumArray = {"合计金额", "合计税额", "发票数量", "合计抵扣税额"};
            for (int i = 0; i < sumArray.length; i++) {
                JSONObject obj = new JSONObject();
                obj.put("name", sumArray[i]);
                obj.put("type", "bar");
                obj.put("areaStyle", "");
                JSONArray skssqarray = new JSONArray();
                for (ExtBbrzrbcxRespVO vo : resultList) {
                    if (i == 0) {
                        skssqarray.add(new DecimalFormat().parse(vo.getHjje()).doubleValue());
                    } else if (i == 1) {
                        skssqarray.add(new DecimalFormat().parse(vo.getHjse()).doubleValue());
                    } else if (i == 2) {
                        skssqarray.add(new DecimalFormat().parse(vo.getHjsl()).doubleValue());
                    } else {
                        skssqarray.add(new DecimalFormat().parse(vo.getDkse()).doubleValue());
                    }
                }
                obj.put("data", skssqarray);
                array.add(obj);
            }
            object.put("series", array);
            JSONArray arrayAxis = new JSONArray();
            JSONObject objxAxis = new JSONObject();
            objxAxis.put("type", "category");
            objxAxis.put("boundaryGap", false);

            objxAxis.put("data", mouthArray);
            arrayAxis.add(objxAxis);
            object.put("xAxis", arrayAxis);
            JSONObject objlegend = new JSONObject();
            String[] legendArray = {"合计金额", "合计税额", "发票数量", "合计抵扣税额"};
            objlegend.put("legend", legendArray);
            object.put("legend", objlegend);
            json.put("dataChart", object);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;

    }
}
