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.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.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 express
 */
@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) {
        Long userid = UserUtils.getUser().getId();
        Long accountsId = UserUtils.getmpaccounts(request);

        Conds conds = new Conds();
        conds.equal("o.del_flag", Constants.DEL_FLAG_0);
        conds.equal("o.accounts_id", accountsId);
        //咨询单编码
        if (StringUtils.isNoneBlank(order.getConsultCode())) {
            conds.like("cs.consult_id", order.getConsultCode());
        }
        //订单编码
        if (StringUtils.isNoneBlank(order.getNumber())) {
            conds.like("o.number", order.getNumber());
        }
        //产品名称
        if (StringUtils.isNoneBlank(order.getProductNameTmp())) {
            conds.like("t.product_name", order.getProductNameTmp());
        }
        //顺丰运单号
        if (StringUtils.isNoneBlank(order.getCourierNumber())) {
            conds.like("o.courier_number", order.getCourierNumber());
        }
        //订单开始金额
        if (StringUtils.isNoneBlank(order.getStartOrderAmount())) {
            conds.greatEqual("o.order_amount", order.getStartOrderAmount());
        }
        //订单结束金额
        if (StringUtils.isNoneBlank(order.getEndOrderAmount())) {
            conds.lessEqual("o.order_amount", order.getEndOrderAmount());
        }
        //最终开始金额
        if (StringUtils.isNoneBlank(order.getStartPayAmount())) {
            conds.greatEqual("o.total_amount", order.getStartPayAmount());
        }
        //最终结束金额
        if (StringUtils.isNoneBlank(order.getEndPayAmount())) {
            conds.lessEqual("o.total_amount", order.getEndPayAmount());
        }
        //订单状态
        if (StringUtils.isNoneBlank(order.getStatus())) {
            conds.equal("o.status", order.getStatus());
        }
        //是否开票
        if (StringUtils.isNoneBlank(order.getIsBill()) && StringUtils.equals(order.getIsBill(), "1")) {//未开票
            conds.isNull("o.confirm");
        } else if (StringUtils.isNoneBlank(order.getIsBill()) && StringUtils.equals(order.getIsBill(), "0")) {//已开票
            conds.notNull("o.confirm");
        }
        //订单开始时间
        if (StringUtils.isNoneBlank(order.getOrderStartTime())) {
            conds.greatEqual("DATE_FORMAT(o.create_time, '%Y-%m-%d')", order.getOrderStartTime());
        }
        //订单结束时间
        if (StringUtils.isNoneBlank(order.getOrderEndTime())) {
            conds.lessEqual("DATE_FORMAT(o.create_time, '%Y-%m-%d')", order.getOrderEndTime());
        }

        Sort sort = new Sort("o.create_time", OrderType.DESC);
        List<Order> list = orderService.fetchSearchBy(conds, sort, iDisplayStart, iDisplayLength, userid);
        Integer counts = orderService.count(conds, userid);
        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, String status, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        Integer integer = orderService.updateStatus(id, status);
        if (integer>0){
            rtnJson.put("errorNo","0");
            return rtnJson;
        }
        rtnJson.put("errorNo","1");
        return rtnJson;
    }
}
