package com.izouma.awesomeadmin.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import com.izouma.awesomeadmin.util.ExportExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.model.LogisticsInfo;
import com.izouma.awesomeadmin.service.LogisticsInfoService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * controller类
 */
@Controller
@RequestMapping("/logisticsInfo")
@RequiresAuthentication
public class LogisticsInfoController {

    @Autowired
    private LogisticsInfoService logisticsInfoService;

    /**
     * <p>获取全部记录。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Result all(LogisticsInfo record) {
        List<LogisticsInfo> pp = logisticsInfoService.getLogisticsInfoList(record);
        return new Result(true, pp);
    }

    /**
     * <p>根据Id。</p>
     */
    @RequestMapping(value = "/getLogisticsInfo", method = RequestMethod.GET)
    @ResponseBody
    public Result getLogisticsInfo(@RequestParam(required = false, value = "id") String id) {
        LogisticsInfo data = logisticsInfoService.getLogisticsInfoById(id);
        return new Result(true, data);
    }

    /**
     * <p>根据条件获取。</p>
     */
    @RequestMapping(value = "/getOne", method = RequestMethod.GET)
    @ResponseBody
    public Result getOne(LogisticsInfo record) {
        LogisticsInfo data = logisticsInfoService.getLogisticsInfo(record);
        return new Result(true, data);
    }


    /**
     * <p>分页查询。</p>
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Result page(Page page, LogisticsInfo record) {
        Map<String, Object> result = new HashMap<>();

        List<LogisticsInfo> pp = logisticsInfoService.getLogisticsInfoByPage(page, record);

        result.put(AppConstant.PAGE, page);
        result.put("pp", pp);
        return new Result(true, result);
    }


    /**
     * <p>保存。</p>
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(LogisticsInfo record) {
        boolean num = logisticsInfoService.createLogisticsInfo(record);
        if (num) {
            return new Result(true, num);
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>更新信息。</p>
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateLogisticsInfo(LogisticsInfo record) {
        boolean num = logisticsInfoService.updateLogisticsInfo(record);
        if (num) {
            return new Result(true, "保存成功");
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>删除。</p>
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteLogisticsInfo(@RequestParam(required = true, value = "id") String id) {

        boolean num = logisticsInfoService.deleteLogisticsInfo(id);
        if (num) {
            return new Result(true, "删除成功");
        }
        return new Result(false, "删除异常");
    }

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param record
     * @throws Exception
     */
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, LogisticsInfo record) throws Exception {

        List<LogisticsInfo> logisticsInfos = logisticsInfoService.getLogisticsInfoList(record);


        String sheetName = "logistics_info";
        String titleName = "快递公司数据表";
        String fileName = "快递公司表";
        int columnNumber = 2;
        int[] columnWidth = {20, 20};
        String[] columnName = {"物流公司code", "公司名称"};
        String[][] dataList = new String[logisticsInfos.size()][2];

        for (int i = 0; i < logisticsInfos.size(); i++) {

            dataList[i][0] = String.valueOf(logisticsInfos.get(i).getCode());
            dataList[i][1] = String.valueOf(logisticsInfos.get(i).getName());
        }


        ExportExcelUtil.ExportWithResponse(sheetName, titleName, fileName,
                columnNumber, columnWidth, columnName, dataList, response);


    }


    /**
     * 物流api（物流100）
     *
     * @param logisticsCode 快递公司代码
     * @param expressCode   快递单号
     * @return
     */
    @RequestMapping(value = "/logisticsApi", method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String logisticsApi(@RequestParam(required = false, value = "logisticsCode") String logisticsCode, @RequestParam(required = false, value = "expressCode") String expressCode) {

        String logisticsUrl = "https://m.kuaidi100.com/query?type=" + logisticsCode + "&postid=" + expressCode;
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(logisticsUrl);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            return json.toString();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }

        return "";
    }
}

