package com.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.CanUserUpdateRecord;
import com.platform.constant.ConstantExcel;
import com.platform.entity.*;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.oss.OSSFactory;
import com.platform.service.BrandService;
import com.platform.service.OrderGoodsService;
import com.platform.service.OrderService;
import com.platform.service.OrderShippingService;
import com.platform.utils.*;
import com.platform.utils.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController extends AbstractController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderGoodsService orderGoodsService;


    @Autowired
    private OrderShippingService orderShippingService;

    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    
    public Result list(@RequestBody Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        PageUtils pageUtil = new PageUtils(new ArrayList<>(), 0, query.getLimit(), query.getPage());
        ;

        List<Long> roleIdList = getUser().getRoleIdList();
        if (!roleIdList.contains(1L) && !roleIdList.contains(5L)) {
            if (null == getDeptId()) {
                return Result.success(pageUtil);
            }
            Query brandQuery = new Query(params);
            brandQuery.put("deptIdList", getDeptId());
            List<BrandEntity> brandList = brandService.queryList(brandQuery);
            if (!CollectionUtils.isEmpty(brandList)) {
                List<Integer> brandIdList = new ArrayList<>();
                for (BrandEntity brandEntity : brandList) {
                    brandIdList.add(brandEntity.getId().intValue());
                }
                query.put("brandIdList", brandIdList);
               // params.put("brandIdList", brandIdList);
            } else {
                return Result.success(pageUtil);
            }
        }

        List<OrderEntity> orderList = orderService.queryList(query);
        for (OrderEntity orderEntity : orderList) {
            if (orderEntity.getShippingStatus() == null) {
                orderEntity.setShippingStatus(0);
            }
            orderEntity.setNewId(orderEntity.getId() + "" + orderEntity.getBrandId());
        }
       // List<OrderEntity> orderListTotal = orderService.queryList(params);

        pageUtil = new PageUtils(orderList, orderList.size(), query.getLimit(), query.getPage());

        return Result.success(pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    
    public Result info(@RequestParam("id") Integer id, @RequestParam("brandId") Integer brandId) {

        OrderEntity order = orderService.queryObject(id);

        if (order != null) {
            order.setBrandId(brandId);
            Map map = new HashMap();
            map.put("orderId", order.getId());
            map.put("brandId", brandId + "");
            order.setGoodsList(orderGoodsService.queryList(map));

            BrandEntity brandEntity = brandService.queryObject(brandId);
            order.setBrandName(brandEntity.getName());

            List<OrderShippingEntity> list = orderShippingService.queryList(map);
            if (list != null && list.size() > 0) {
                order.setShippingId(list.get(0).getShippingId());
                order.setShippingNo(list.get(0).getShippingNo());
                order.setShippingName(list.get(0).getShippingName());
                order.setShippingStatus(list.get(0).getShippingStatus());
                order.setActualPrice(list.get(0).getTotalPrice());
                order.setOrderPrice(list.get(0).getTotalPrice());
                order.setGoodsPrice(list.get(0).getTotalPrice().subtract(list.get(0).getFreightPrice()));
                order.setFreightPrice(list.get(0).getFreightPrice().intValue());

                if (!StringUtils.isEmpty(list.get(0).getShippingNo())) {
                    JSONObject result = new JSONObject();
                    try {
                        String msg = LogisticsUtil.getDetail(order.getShippingNo(), null, "/kdi");
                        result = JSONObject.parseObject(msg);
                        //status 0:正常查询 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制，错误单号 */
                        String status = result.getString("status");
                        JSONObject data = new JSONObject();
                        if ("201".equals(status)) {
                            data.put("result", "快递单号错误");
                            order.setLogistics(data);
                        } else if ("203".equals(status)) {
                            data.put("result", "快递公司不存在");
                            order.setLogistics(data);
                        } else if ("204".equals(status)) {
                            data.put("result", "快递公司识别失败");
                            order.setLogistics(data);
                        } else if ("205".equals(status)) {
                            data.put("result", "快递单号没有信息");
                            order.setLogistics(data);
                        } else if ("206".equals(status)) {
                            data.put("result", "该单号被限制，错误单号");
                            order.setLogistics(data);
                        } else {
                            data = result.getJSONObject("result");
                            order.setLogistics(data);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        return Result.success(order);
    }

    /**
     * 保存
     */
    @CanUserUpdateRecord
    @RequestMapping("/save")
    
    public Result save(@RequestBody OrderEntity order) {
        orderService.save(order);

        return Result.success();
    }

    /**
     * 修改
     */
    @CanUserUpdateRecord
    @RequestMapping("/update")
    
    public Result update(@RequestBody OrderEntity order) {
        orderService.update(order);

        return Result.success();
    }

    /**
     * 删除
     */
    @CanUserUpdateRecord
    @RequestMapping("/delete")
    
    public Result delete(@RequestBody Integer[] ids) {
        orderService.deleteBatch(ids);

        return Result.success();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public Result queryAll(@RequestBody Map<String, Object> params) {

        List<OrderEntity> list = orderService.queryList(params);

        return Result.success(list);
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public Result queryTotal(@RequestBody Map<String, Object> params) {
        int sum = orderService.queryTotal(params);

        return Result.success( sum);
    }

    /**
     * 确定收货
     *
     * @return
     */
    @CanUserUpdateRecord
    @RequestMapping("/confirm")
    
    public Result confirm(@RequestBody OrderEntity order) {
        orderService.confirm(order.getId(), order.getBrandId());

        return Result.success();
    }

    /**
     * 发货
     *
     * @param order
     * @return
     */
    @CanUserUpdateRecord
    @RequestMapping("/sendGoods")
    
    public Result sendGoods(@RequestBody OrderEntity order) {
        if (StringUtils.isEmpty(order.getShippingNo()) || StringUtils.isEmpty(order.getShippingId())) {
            return Result.failure("快递公司和快递单号不能为空");
        }
        orderService.sendGoods(order);

        return Result.success();
    }

    /**
     * 导出订单数据
     */
    @PostMapping("/export")
    @ResponseBody
    public Result export(@RequestBody Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {

        if(null == params){
            throw new CommonBaseException(ResultCodeEnum.D101 , "缺失参数");
        }
        String orderSnListStr = (String) params.get("orderSnList");
        if(StringUtils.isEmpty(orderSnListStr)){
            return Result.failure("订单号为空");
        }
        List<String> orderSnList = Arrays.asList(orderSnListStr.split(","));

        params.remove("orderSnList");
        params.put("orderSnList" , orderSnList);
        // 查询列表数据
        List<OrderEntity> orderList = orderService.queryList(params);
        List<OrderGoodsEntity> orderGoodsList = new ArrayList<>();
        List<OrderShippingEntity> shippingList = null;
        //导出的数据
        Map<String, String> item = null;
        List<Map<String , String>> dataList = new ArrayList<>();
        int num = 1;
        if (!CollectionUtils.isEmpty(orderList)) {
            for (OrderEntity orderEntity : orderList) {
                if (orderEntity.getBrandId() != null) {
                    Map<String , Object> goodsMap = new HashMap<String, Object>();
                    goodsMap.put("orderId", orderEntity.getId());
                    goodsMap.put("brandId", orderEntity.getBrandId() + "");
                    orderGoodsList = orderGoodsService.queryList(goodsMap);
                    if(CollectionUtils.isEmpty(orderGoodsList)){
                        continue;
                    }
                    item = fillExcel(orderEntity , orderGoodsList , num , goodsMap);
                    dataList.add(item);
                    num++;
                } else {
                    Map<String , Object> goodsMap = new HashMap<String, Object>();
                    goodsMap.put("orderId", orderEntity.getId());
                    orderGoodsList = orderGoodsService.queryList(goodsMap);
                    if(CollectionUtils.isEmpty(orderGoodsList)){
                        continue;
                    }
                    item = fillExcel(orderEntity , orderGoodsList , num , goodsMap);
                    dataList.add(item);
                    num++;
                }

            }
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = "订单数据-" + dateFormat.format(new Date()) + "_" + System.currentTimeMillis();
        String fileName = dateStr + ".xls";
        String localExcelFullPath = ResourceUtil.getConfigByName("filePath") + "excel/" + dateStr + ".xls";
        String ossExcelFullPath = ResourceUtil.getConfigByName("oss.excel.file.path")  + dateStr + ".xls";
        File file = new File(localExcelFullPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }


        ExcelUtil.writeExcel(dataList, ConstantExcel.ORDEREXCELCOLENNAME.length, localExcelFullPath, 1);

        //上传oss，然后返回链接
        String url = "";
        try {
            url = OSSFactory.build().upload(new FileInputStream(file) , ossExcelFullPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);

        return Result.success(map);

         /* response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
      String agent = request.getHeader("User-Agent");
        if (agent != null && (agent.contains("MSIE") || agent.contains("Trident"))) {
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            //非IE浏览器的处理：
            try {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        response.setContentType(request.getServletContext().getMimeType(fileName));
        response.setContentLength((int) file.length());
        output(response, file);*/
    }

    private Map<String ,String> fillExcel(OrderEntity orderEntity , List<OrderGoodsEntity> orderGoodsList , int num , Map<String , Object> goodsMap){
        Map<String , String> item = new HashMap<>();
        String goodsNameAll = "";
        String orderDetail = "";
        int goodsAllNum = 0;
        if(!CollectionUtils.isEmpty(orderGoodsList)){
            for (OrderGoodsEntity orderGoodsEntity : orderGoodsList){
                if(!StringUtils.isEmpty(orderGoodsEntity.getGoodsName())){
                    goodsNameAll += orderGoodsEntity.getGoodsName() + ",";
                }
                if(num != orderGoodsEntity.getNumber()){
                    goodsAllNum += orderGoodsEntity.getNumber();
                }
                orderDetail += orderGoodsEntity.getGoodsName() + "  " + orderGoodsEntity.getRetailPrice() + "*" + orderGoodsEntity.getNumber() + "; ";
            }
            if(goodsNameAll.length() > 0){
                goodsNameAll = goodsNameAll.substring(0 , goodsNameAll.length() - 1);
            }
        }

        //0 序号
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[0], String.valueOf(num));
        //1 订单号
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[1], orderEntity.getOrderSn());
        //2 店铺名称
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[2], orderEntity.getBrandName());
        //3 会员昵称
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[3], orderEntity.getUserName());
        //4 商品名称
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[4], goodsNameAll);
        //5 商品总数

        item.put(ConstantExcel.ORDEREXCELCOLENNAME[5], String.valueOf(goodsAllNum));
        //6 订单类型
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[6], ConstantExcel.getOrderType(orderEntity.getOrderType()));
        //7 订单状态
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[7], ConstantExcel.getOrderStatus(orderEntity.getOrderStatus()));
        List<OrderShippingEntity> shippingList = orderShippingService.queryList(goodsMap);
        if (!CollectionUtils.isEmpty(shippingList)) {
            //8 发货状态
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[8], ConstantExcel.getOrderShippingStatus(shippingList.get(0).getShippingStatus()));
            //10 快递公司
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[10], shippingList.get(0).getShippingName());
            //11 快递单号
            item.put(ConstantExcel.ORDEREXCELCOLENNAME[11], shippingList.get(0).getShippingNo());
        }
        // 9 付款状态
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[9], ConstantExcel.getOrderPayStatus(orderEntity.getPayStatus()));
        //12 订单原价
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[12], orderEntity.getOrderPrice().toString());

        //13 实际支付金额
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[13], orderEntity.getActualPrice().toString());

        //14 运费
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[14], orderEntity.getFreightPrice().toString());
        //15 下单时间
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[15], DateUtils.format(orderEntity.getAddTime(), DateUtils.DATE_TIME_PATTERN));
        //16 收货人
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[16], orderEntity.getConsignee());
        //17 收货地址
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[17], orderEntity.getProvince() + " " +
                orderEntity.getCity() + " " + orderEntity.getDistrict() + " " + orderEntity.getAddress());
        //18 联系电话
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[18], orderEntity.getMobile());

        //10 订单详情
        item.put(ConstantExcel.ORDEREXCELCOLENNAME[19], orderDetail);
        return item;
    }

    private static void output(HttpServletResponse resp, File file) {
        OutputStream os = null;
        BufferedInputStream bis = null;
        byte[] buff = new byte[1024];
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
