package com.dxhy.manage.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

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.JSONObject;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.R;
import com.dxhy.manage.entity.SysDeptEntity;
import com.dxhy.manage.model.BlocDataModel;
import com.dxhy.manage.service.SellersStatService;
import com.dxhy.manage.service.impl.EasyExcelUtil;
import com.dxhy.manage.thread.BlocHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@RestController
@RequestMapping("/manage/sellersStat")
@Slf4j
public class SellersStatController extends AbstractController {
    @Resource
    private EasyExcelUtil excelUtil;

    @Resource
    private SellersStatService sellersStatService;

    /**
     * 返回集团信息
     */
    @RequestMapping("/blocList")
    public ResponseEntity<?> list() {
        String userId = getUserId();
        List<SysDeptEntity> deptList = sellersStatService.queryList(userId);
        return ResponseEntity.ok(R.ok().put("data", deptList));
    }

    /**
     * 返回税号信息
     */
    @RequestMapping("/taxnoList")
    public ResponseEntity<?> taxnoList(@RequestBody Map<String, Object> params) {
        String deptId = (String)params.get("deptId");
        List<SysDeptEntity> deptList = sellersStatService.queryTaxnoList(deptId);
        return ResponseEntity.ok(R.ok().put("data", deptList));
    }

    /**
     * 查询结果
     *
     * @param params
     * @return
     */
    @RequestMapping("/getStatResult")
    public ResponseEntity<?> getTaxnoManage(@RequestBody Map<String, String> params)
        throws ExecutionException, InterruptedException {
        // 根据页面参数不同返回不同结果内容
        String timeType = params.get("timeType");
        String company = params.get("company");
        if ("99".equals(company)) {
            return blocCountList(params);
        }
        if ("0".equals(timeType)) {
            JSONObject obj = sellersStatService.getTitle();
            PageUtils pageUtils = sellersStatService.queryResultPage(params);
            obj.put("datalist", pageUtils.getList());
            obj.put("total", pageUtils.getTotalCount());
            String jsonString = null;
            if (obj != null) {
                try {
                    jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ResponseEntity.ok(R.ok().put("data", jsonString));
        } else if ("1".equals(timeType)) {
            JSONObject obj = sellersStatService.getYearTitle();
            PageUtils pageUtils = sellersStatService.queryYearPage(params);
            obj.put("datalist", pageUtils.getList());
            obj.put("total", pageUtils.getTotalCount());
            String jsonString = null;
            if (obj != null) {
                try {
                    jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ResponseEntity.ok(R.ok().put("data", jsonString));
        } else if ("2".equals(timeType)) {
            JSONObject obj = sellersStatService.getMonthTitle();
            PageUtils pageUtils = sellersStatService.queryMonthPage(params);
            obj.put("datalist", pageUtils.getList());
            obj.put("total", pageUtils.getTotalCount());
            String jsonString = null;
            if (obj != null) {
                try {
                    jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ResponseEntity.ok(R.ok().put("data", jsonString));
        }
        return ResponseEntity.ok(R.ok().put("data", null));
    }

    /**
     * 查询结果
     *
     * @param params
     * @return
     */
    @RequestMapping("/ExportStatResult")
    public void exportStatResult(@RequestBody Map<String, String> params, HttpServletResponse response) {

        sellersStatService.exportExcel(params, response);
    }

    /**
     * 认证相关查询
     */
    @RequestMapping("/getStatConfirmResult")
    public ResponseEntity<?> getConfirmStat(@RequestBody Map<String, String> params)
        throws ExecutionException, InterruptedException {

        // 根据页面参数不同返回不同结果内容
        String timeType = params.get("timeType");
        String company = params.get("company");
        if ("99".equals(company)) {
            return blocCountList(params);
        }
        if ("0".equals(timeType)) {
            JSONObject obj = sellersStatService.getTitle();
            PageUtils pageUtils = sellersStatService.queryConfirmTotalPage(params);
            obj.put("datalist", pageUtils.getList());
            obj.put("total", pageUtils.getTotalCount());
            String jsonString = null;
            if (obj != null) {
                try {
                    jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ResponseEntity.ok(R.ok().put("data", jsonString));
        } else if ("1".equals(timeType)) {
            JSONObject obj = sellersStatService.getYearTitle();
            PageUtils pageUtils = sellersStatService.queryYearPage(params);
            obj.put("datalist", pageUtils.getList());
            obj.put("total", pageUtils.getTotalCount());
            String jsonString = null;
            if (obj != null) {
                try {
                    jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ResponseEntity.ok(R.ok().put("data", jsonString));
        } else if ("2".equals(timeType)) {
            JSONObject obj = sellersStatService.getMonthTitle();
            PageUtils pageUtils = sellersStatService.queryMonthPage(params);
            obj.put("datalist", pageUtils.getList());
            obj.put("total", pageUtils.getTotalCount());
            String jsonString = null;
            if (obj != null) {
                try {
                    jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return ResponseEntity.ok(R.ok().put("data", jsonString));
        }
        return ResponseEntity.ok(R.ok().put("data", null));
    }

    /**
     * 当查询条件为集团-全部的时候调用该方法
     */
    @RequestMapping("/blocCountList")
    public ResponseEntity<?> blocCountList(@RequestBody Map<String, String> params)
        throws ExecutionException, InterruptedException {
        String userId = getUserId();
        List<SysDeptEntity> deptList = sellersStatService.queryList(userId);
        List<SysDeptEntity> pageDeptList = setPageList(deptList, params);
        // 设置请求线程池
        ThreadPoolExecutor producerThreadPool = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(deptList.size()), new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "采集定时-" + r.hashCode());
                }
            });
        // 存储线程的返回值
        List<Future<BlocDataModel>> results = new LinkedList<>();
        List<BlocDataModel> finalResult = new LinkedList<>();
        for (SysDeptEntity entity : pageDeptList) {
            Future<BlocDataModel> result = producerThreadPool.submit(new BlocHandler(entity, params));
            results.add(result);
        }
        int i = 1;
        producerThreadPool.shutdown();
        producerThreadPool.awaitTermination(120, TimeUnit.SECONDS);
        for (Future<BlocDataModel> list : results) {
            if (list.get() != null) {
                BlocDataModel model = list.get();
                log.info(model.getCompany() + "-" + model.getTaxname() + "-" + model.getTaxnoCount() + "-"
                    + model.getCount());
                model.setOrder(i + "");
                finalResult.add(model);
                i++;
            }
        }
        PageUtils pageUtils = new PageUtils(finalResult, deptList.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
        JSONObject obj = sellersStatService.getBlocTitle();
        obj.put("datalist", pageUtils.getList());
        obj.put("total", pageUtils.getTotalCount());
        String jsonString = null;
        if (obj != null) {
            try {
                jsonString = Base64.getEncoder().encodeToString(obj.toJSONString().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return ResponseEntity.ok(R.ok().put("data", jsonString));
    }

    /**
     * 设置分页
     *
     * @param years
     * @param params
     * @return
     */
    private List<SysDeptEntity> setPageList(List<SysDeptEntity> years, Map<String, String> params) {
        int curr = Integer.parseInt(params.get("curr"));
        int size = Integer.parseInt(params.get("size"));
        // 设置每次多少条数据
        int perCount = size;
        int index = (curr - 1) * size;
        int totalSize = perCount * curr;
        perCount = Math.min(totalSize, years.size());
        List<SysDeptEntity> sbList = null;
        if (years.size() >= perCount && years.size() >= index) {
            sbList = years.subList(index, perCount);
        } else {
            if (years.size() != 0) {
                sbList = years.subList(0, years.size());
            }
        }
        return sbList;
    }

    /**
     * 查询结果
     *
     * @param params
     * @return
     */
    @RequestMapping("/blocCountListExport")
    public void blocCountListExport(@RequestBody Map<String, String> params, HttpServletResponse response)
        throws Exception {
        String userId = getUserId();
        List<SysDeptEntity> deptList = sellersStatService.queryList(userId);
        // 设置请求线程池
        ThreadPoolExecutor producerThreadPool = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(deptList.size()), new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "采集定时-" + r.hashCode());
                }
            });
        // 存储线程的返回值
        List<Future<BlocDataModel>> results = new LinkedList<>();
        List<BlocDataModel> finalResult = new LinkedList<>();
        for (SysDeptEntity entity : deptList) {
            Future<BlocDataModel> result = producerThreadPool.submit(new BlocHandler(entity, params));
            results.add(result);
        }
        int i = 1;
        producerThreadPool.shutdown();
        producerThreadPool.awaitTermination(120, TimeUnit.SECONDS);
        for (Future<BlocDataModel> list : results) {
            if (list.get() != null) {
                BlocDataModel model = list.get();
                log.info(model.getCompany() + "-" + model.getTaxname() + "-" + model.getTaxnoCount() + "-"
                    + model.getCount());
                model.setOrder(i + "");
                finalResult.add(model);
                i++;
            }
        }
        PageUtils pageUtils = new PageUtils(finalResult, deptList.size(), Integer.parseInt(params.get("size")),
            Integer.parseInt(params.get("curr")));
        excelUtil.writeExcel(response, pageUtils.getList(), "Stat" + System.currentTimeMillis(), "sheet1",
            BlocDataModel.class);
    }

}
