package com.cftech.order.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cftech.order.model.Order;
import com.cftech.order.model.OrderFromVO;
import com.cftech.order.model.OrderVO;
import com.cftech.order.model.ProductOrder;
import com.cftech.order.service.OrderService;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.order.utils.DoubleJSONFilter;
import com.cftech.orderdetail.model.OrderDetails;
import com.cftech.orderdetail.web.OrderDetailsController;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;


/**
 * 订单管理Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String ORDER_VIEW = "qy:order:view"
 * 查看:public static final String ORDER_EDIT = "qy:order:edit"
 *
 * @author Licc
 * @date: 2020-10-10 14:20
 */
@Slf4j
@Controller
@RequestMapping("/a/order")
public class OrderController {

    public static final String ORDER_VIEW = "qy:order:view";
    public static final String ORDER_EDIT = "qy:order:edit";
    public static final DoubleJSONFilter DOUBLE_JSON_FILTER = new DoubleJSONFilter();
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailsController orderDetailsController;

    //列表页面
    @RequiresPermissions(value = ORDER_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "order/orderlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = ORDER_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            OrderFromVO orderFromVO = orderService.fetchId(id);
            List<OrderFromVO> fromVO = orderService.fetchProductId(id);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(orderFromVO));
            String jsonArray = JSON.toJSONString(fromVO, DOUBLE_JSON_FILTER, SerializerFeature.WriteMapNullValue);
            model.addAttribute("data", jsonObject);
            model.addAttribute("list", jsonArray);
        }
        return "order/orderform";
    }

    //订单出货页面
    @RequiresPermissions(value = ORDER_VIEW)
    @RequestMapping("/sendOut")
    public String sendOut(HttpServletRequest request, String id, Model model) {
        if (StringUtils.isNoneBlank(id)) {
            OrderFromVO orderFromVO = orderService.fetchId(id);
            List<OrderFromVO> fromVO = orderService.fetchProductId(id);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(orderFromVO));
            String jsonArray = JSON.toJSONString(fromVO, DOUBLE_JSON_FILTER, SerializerFeature.WriteMapNullValue);
            model.addAttribute("data", jsonObject);
            model.addAttribute("list", jsonArray);
        }
        return "order/orderSendOut";
    }

    @RequestMapping("/fromProduct")
    @ResponseBody
    public JSONObject fromProduct() {
        List<ProductOrder> orders = orderService.listProduct();
        String jsonArray = JSON.toJSONString(orders, DOUBLE_JSON_FILTER, SerializerFeature.WriteMapNullValue);
        JSONObject object = new JSONObject();
        object.put("data", jsonArray);
        return object;

    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = ORDER_EDIT)
    @PostMapping(value = "/formData", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public JSONObject formData(HttpServletRequest request, String datas) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject jsonObject = orderService.newlyAdded(datas, accountsId);
        return jsonObject;
    }

    //获取列表数据
    @RequiresPermissions(value = ORDER_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Order order, HttpServletRequest request) {
        String id = String.valueOf(UserUtils.getUser().getId());
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("o.del_flag", Constants.DEL_FLAG_0);
        conds.equal("d.del_flag", Constants.DEL_FLAG_0);
        conds.equal("o.accounts_id", accountsId);
        Sort sort = new Sort("o.create_time", OrderType.DESC);
        if (!StringUtils.isEmpty(order.getNumber())) {
            conds.like("o.order_code", order.getNumber());
        }
        if (!StringUtils.isEmpty(order.getProductName())) {
            conds.like("t.product_name", order.getProductName());
        }

        List<Order> list = orderService.fetchSearchBy(conds, sort, iDisplayStart, iDisplayLength, id);
        Integer counts = orderService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = ORDER_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            orderService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = ORDER_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("o.create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("o.del_flag", 0);
        conds.equal("o.accounts_id", accountId);
        List<Order> list = orderService.fetchSearchByPage(conds, sort, 0, 0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        LinkedList<OrderVO> orderVOS = new LinkedList<>();
        for (Order order : list) {
            OrderVO orderVO = new OrderVO();
            orderVO.setProductNumber(order.getProductNumber());
            orderVO.setProductName(order.getProductName());
            orderVO.setOrderAmount(order.getOrderAmount());
            orderVO.setAddress(order.getAddress());
            orderVO.setCourierNumber(order.getCourierNumber());
            orderVO.setTradeNo(order.getTradeNo());
            orderVO.setCreateTime(simpleDateFormat.format(order.getCreateTime()));
            orderVO.setPayStatus(order.getPayStatus().equals("0") ? "待确认" : order.getPayStatus().equals("1") ? "待付款" : order.getPayStatus().equals("2") ? "待发货" :order.getPayStatus().equals("3") ? "待收货":order.getPayStatus().equals("4") ? "已完成" :"已取消");
            orderVOS.add(orderVO);
        }
        ExcelKit.$Export(OrderVO.class, response).toExcel(orderVOS, "订单管理信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = ORDER_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Order.class, response).toExcel(null, "订单管理信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = ORDER_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model);
        }
        // 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().setEmptyCellValue("").readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Order order = new Order();
                    order.setAccountsId(accountId);
                    orderService.save(order);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model);
    }

    @RequestMapping("/findorderDetail")
    public String findorderDetail(HttpServletRequest request, Model model,Long id) {
        model.addAttribute("isDetail",'y');
        return orderDetailsController.list(request,model,id);
    }
    @RequestMapping("/deleteAll")
    @ResponseBody
    public JSONObject deleteAll(Long id) {

        return orderService.deleteAll(id);
    }
    @RequestMapping("/updateStatus")
    @ResponseBody
    public JSONObject updateStatus(Long id,HttpServletRequest request ,Model model) {
        JSONObject rtnJson = new JSONObject();
        Integer integer = orderService.updateStatus(id);
        if (integer>0){
            rtnJson.put("errorNo","0");
            return rtnJson;
        }
        rtnJson.put("errorNo","1");
        return rtnJson;
    }
}
