package com.cftech.order.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.invoice.model.Invoice;
import com.cftech.invoice.service.InvoiceService;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.base.org.api.QyMsgUtil;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.service.QyuserService;
import com.cftech.core.util.SystemConfig;
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.order.utils.InvoiceUtil;
import com.cftech.orderdetail.web.OrderDetailsController;
import com.cftech.sys.security.UserUtils;
import com.cftech.sys.service.UserService;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
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;

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private InvoiceUtil invoiceUtil;

    @Autowired
    private MpAccountsService accountsService;

    @Autowired
    private QyuserService qyuserService;

    @Autowired
    private QyMsgUtil qyMsgUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private CodingruleUtils codingruleUtils;

    //列表页面
    @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("/listout")
    public String listout(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "order/orderlistout";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = ORDER_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, String pageType, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Long accountId = UserUtils.getmpaccounts(request);
            MpAccountsEntity mpAccountsEntity = accountsService.getDetail(accountId);

            OrderFromVO orderFromVO = orderService.fetchId(id);//订单信息
            if (!StringUtils.equals(orderFromVO.getStatus(), "0")) {
                String remarks = orderFromVO.getRemarks();
                if (StringUtils.isNoneBlank(remarks) && remarks.contains("prepay_id")) {
                    JSONObject remarkObj = JSONObject.parseObject(remarks);

                    String payUrl = SystemConfig.p.getProperty("MOBILE_MP_DOMAIN_NAME") + "/orderPay?appid=" + mpAccountsEntity.getAppid() + //
                            "&tokenId=1&orderId=" + orderFromVO.getId() + "&prepayId=" + remarkObj.getString("prepay_id");
                    orderFromVO.setPayUrl(payUrl);
                }
            }


            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(orderFromVO));
            model.addAttribute("data", jsonObject);

            List<OrderFromVO> fromVO = orderService.fetchProductId(id);//获取订单产品明细数据
            String jsonArray = JSON.toJSONString(fromVO, DOUBLE_JSON_FILTER, SerializerFeature.WriteMapNullValue);
            model.addAttribute("list", jsonArray);

            Integer i = orderService.isThreeUsers(orderFromVO.getOpenid());
            if (i > 0) {
                model.addAttribute("isThree", "0");//是
            } else {
                model.addAttribute("isThree", "1");//否
            }

            model.addAttribute("isView", StringUtils.equals(pageType, "View") ? true : false);
        }
        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) throws ParseException {
        Long userid = UserUtils.getUser().getUserid();
        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);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:ss");
        Date today = new Date();
        Date passDay = null;
        int i = 0;
        for (Order obj : list){
            if(obj.getStatus().equals("4") && !StringUtils.isEmpty(obj.getAcceptExpressDateStr())){
                passDay = format.parse(obj.getAcceptExpressDateStr());
                i = (int)(today.getTime()-passDay.getTime()) / (1000*3600*24);
                if(i >= 7){
                    obj.setIsExceedSevenDay("0");
                }else {
                    obj.setIsExceedSevenDay("1");
                }
            }
        }
        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("/invoice")
    @ResponseBody
    public JSONObject invoice(String id, HttpServletRequest request,String email){
        JSONObject jsonObject = new JSONObject();
        Long userid = UserUtils.getUser().getUserid();
        Long accountsId = UserUtils.getmpaccounts(request);
        try {
            Conds conds = new Conds();
            conds.in("o.id",id.split(","));
            conds.equal("o.del_flag", Constants.DEL_FLAG_0);
            conds.equal("o.accounts_id", accountsId);
            List<Order> list = orderService.fetchSearchBy(conds, null, 0, 0, userid);
            if(list.size() > 0){
                for (Order order : list){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    order.setCreateTimeStr(format.format(order.getCreateTime()));
                    String str = invoiceUtil.startInvoice(order,String.valueOf(userid),email,"0","1",null);
                    JSONObject json = JSON.parseObject(str);
                    if ( StringUtils.isNotBlank(json.getString("code")) && json.getString("code").equals("E0000")){
                        //开票成功 添加一条开票记录
                        //流水号
                        String invoiceSerialNum = json.getJSONObject("result").getString("invoiceSerialNum");
                        Invoice invoice = new Invoice();
                        //发票抬头
                        invoice.setNumber(codingruleUtils.getNumber(accountsId, Invoice.class.getName()));
                        invoice.setInvoiceTitle(order.getNickName());
                        invoice.setInvoiceContent("商品费用");
                        invoice.setInvoiceType("1");
                        invoice.setInvoiceForm("1");
                        invoice.setClerkId(SystemConfig.p.getProperty("CLERK"));
                        invoice.setOrderId(order.getNumber());
                        invoice.setPushMode("0");
                        invoice.setEmail(email);
                        invoice.setStatus("0");
                        invoice.setInvoiceSerialNum(invoiceSerialNum);
                        invoice.setAccountsId(accountsId);
                        invoice.setOpenId(order.getOpenid());
                        String userName = userService.fetchAuthById(userid).getWxUserName();
                        invoice.setOperator(StringUtils.isEmpty(userName) ? "":userName);
                        invoiceService.save(invoice);

                        //更新是否开票状态
                        order.setConfirm(invoiceSerialNum);
                        orderService.update(order);
                    }else{
                        jsonObject.put("errorNo", 1);
                        jsonObject.put("errorMsg",StringUtils.isEmpty(json.getString("describe")) ? json.getString("message") : json.getString("describe"));
                        return jsonObject;
                    }

                }
                jsonObject.put("errorNo", 0);
            }

        } catch (Exception e) {
            jsonObject.put("errorNo", 1);
        }
        return jsonObject;
    }

    //删除数据
    @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, Order order) {
        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);
        //咨询单编码
        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());
        }
        List<Order> list = orderService.fetchSearchByPage(conds, sort, 0, 0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        LinkedList<OrderVO> orderVOS = new LinkedList<>();
        OrderVO orderVO = null;
        for (Order orderObject : list) {
            orderVO = new OrderVO();
            orderVO.setNumber(orderObject.getNumber());
            orderVO.setConsultCode(orderObject.getConsultCode());
            orderVO.setProductName(orderObject.getProductName());
            orderVO.setOrderAmount(orderObject.getOrderAmount());
            orderVO.setTotalAmount(orderObject.getTotalAmount());
            orderVO.setNickName(orderObject.getNickName());
            orderVO.setOpenid(orderObject.getOpenid());
            orderVO.setCourierNumber(orderObject.getCourierNumber());
            orderVO.setTradeNo(orderObject.getTradeNo());
            orderVO.setConfirm(StringUtils.isNotBlank(orderObject.getConfirm()) ? "是":"否");
            orderVO.setCreateTime(simpleDateFormat.format(orderObject.getCreateTime()));
            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, String orderCancel, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        Integer integer = orderService.updateStatus(id, status, orderCancel);
        //设置已付款
        if (integer > 0){
            //线下付款成功
            if (StringUtils.equals(status, "2")) {
                sendQyWechatMassage(id);
            }
            rtnJson.put("errorNo","0");
            return rtnJson;
        }
        rtnJson.put("errorNo","1");
        return rtnJson;
    }

    @RequestMapping("/setOrderRemind")
    @ResponseBody
    public JSONObject setOrderRemind(Long id, String option, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        if (id != null && StringUtils.isNoneBlank(option)) {
            Integer integer = orderService.updateRemindType(id, option);
            if (integer > 0){
                rtnJson.put("errorNo","0");
                return rtnJson;
            }
        }
        rtnJson.put("errorNo","1");
        return rtnJson;
    }

    /**
     * 推送企业微信消息
     */
    public boolean sendQyWechatMassage(Long orderId) {
        Long accounts = Long.parseLong(SystemConfig.p.getProperty("QY_SEND_APPID"));
        MpAccountsEntity accountsEntity = accountsService.getDetail(accounts);
        Long agenId = Long.parseLong(accountsEntity.getAgentId());

        Conds orderConds = new Conds();
        orderConds.equal("o.del_flag", Constants.DEL_FLAG_0);
        orderConds.equal("o.id", orderId);
        List<Order> orders = orderService.fetchSearchByPage(orderConds, null, 0, 0);
        if (orders == null || orders.size() != 1) {
            return false;
        }

        Conds qyuserConds = new Conds();
        qyuserConds.equal("t.del_flag", Constants.DEL_FLAG_0);
        qyuserConds.equal("t.user_type", "4");//订单员职业
        List<Qyuser> qyusers = qyuserService.fetchSearchByPage(qyuserConds, null, 0, 0);
        if (qyusers == null || qyusers.size() <= 0) {
            return false;
        }

        //推送客服消息
        Order order = orders.get(0);
        String msg = SystemConfig.p.getProperty("QY_SEND_ORDERCLERK_MSG") + order.getNumber();

        qyMsgUtil.sendText(accounts, false, qyusers, null, null, agenId, msg, false);
        return true;
    }
}
