package com.bofeng.wx.controller;

import com.bofeng.entity.*;
import com.bofeng.service.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.yvan.ModelOps;
import com.yvan.platform.Conv;
import com.yvan.platform.JsonWapper;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.mp.api.WxMpService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class CustMarketController {

    @Autowired
    private WxMpService mpService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private PlaceService placeService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserPlaceService userPlaceService;

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private TemplateMessageService templateMessageService;

    @GetMapping("/cust/market.html")
    public ModelAndView market(@RequestParam(name = "orderId", required = false, defaultValue = "") String orderId,
                               @RequestParam(name = "userId", required = false, defaultValue = "") String userId,
                               ModelMap model) throws JsonProcessingException {
        ParseCurrentOpenId wxToken = userService.currentWxUser();
        if (wxToken.isError()) return wxToken.getErrorResult();

        model.put("orderCreateAtValue", new DateTime().toString("yyyy-MM-dd'T'HH:mm:ss"));
        UserOpen userOpen = wxToken.getUserOpen();
        model.put("openId", userOpen.getOpenId());

        User user = wxToken.getUser();
        model.put("user", user);

        Room oldRoom = null;

        if (!Strings.isNullOrEmpty(orderId)) {
            Order order = orderService.selectByOrderId(orderId);

            oldRoom = roomService.getByRoomId(order.getRoomId());

            val jwo = new JsonWapper(order);
            model.put("order", jwo.toString(true));

            model.put("orderCreateAtValue",
                    order.getArrivalAt()
                            .toString("yyyy-MM-dd'T'HH:mm:ss"));
            model.put("userId", userId);
        }

        List<Map<String, Object>> placeRoomList = userPlaceService.getCurrentPlacesByUserId(userOpen.getUserId());
        JsonWapper jw = new JsonWapper();
        for (val row : placeRoomList) {
            String tempStr;
            //当前订单的包厢  包厢状态拼接方便前端判断
            if (oldRoom != null && Conv.NL(row.get("room_id")) == oldRoom.getRoomId() && oldRoom.getBeUse().equals("Y")) {
                tempStr = "-已预定";
            } else {
                tempStr = row.get("be_use").equals("N") ? "" : "-不可预定";
            }
            jw.set(row.get("place_name"), row.get("room_name").toString() + "(" + row.get("room_capacity") + "人)" + tempStr, row.get("room_id"));
        }
        model.put("room_json", jw.toString(true));

        return new ModelAndView("/cust/market.ftl", model);
    }

    @PostMapping("/cust/save_order.json")
    public ModelOps saveOrder(JsonWapper jw) {

        val order = new Order();

        order.setOrderId(jw.asLong("orderId"));
        order.setSaleUserId(jw.asLong("userId"));
        order.setRoomId(jw.asLong("roomId"));
        order.setRoomName(jw.asStr("roomName"));
        order.setCustomerName(jw.asStr("customerName"));
        order.setCustomerTel(jw.asStr("customerTel"));
        order.setCustomerNumber(jw.asLong("customerNumber"));
        order.setArrivalAt(new DateTime(jw.asStr("orderCreateAt")));

        val msg = orderService.saveOrder(order);
        if (Strings.isNullOrEmpty(msg)) {
            return ModelOps.newSuccess();
        }
        return ModelOps.newFail(msg);
    }

    /*
    @PostMapping("/cust/reserve_room.json")
    public ModelOps reserveRoom(@RequestBody Map map) {

        Order order = new Order();
        User currentUser = userService.getUserById(Conv.NL(map.get("userId")));
        UserPlace userPlace = userPlaceService.getByUserIdAndPlaceId(currentUser.getUserId(), roomService.getByRoomId(Conv.NL(map.get("roomId"))).getPlaceId());

        if (Consts.USER_TYPE_L2.equals(userPlace.getUserType())) {
//            higherUser = userService.getUserById(currentUser.getHigherId());
            order.setSaleId1(userPlace.getHigherId());
            order.setSaleId2(currentUser.getUserId());
            order.setSaleName1(userService.getUserById(userPlace.getHigherId()).getStaffName());
            order.setSaleName2(currentUser.getStaffName());
        } else {
            order.setSaleId1(currentUser.getUserId());
            order.setSaleName1(currentUser.getStaffName());
        }
        order.setOrderId(IdWorker.getId());
        order.setBeActive(Consts.ACT_ENABLE);
        order.setBePaid(Consts.PAID_NO);
        order.setCustomerName((String) map.get("customerName"));
        order.setCustomerTel((String) map.get("customerTel"));
        order.setCustomerNumber(Conv.NI(map.get("customerNumber")));
        if (!Strings.isNullOrEmpty(Conv.NS(map.get("orderCreateAt")))) {
            order.setOrderCreateAt(Conv.NS(map.get("orderCreateAt")));
        } else {
            order.setOrderCreateAt(new DateTime().toString());
        }
        order.setRoomId(Conv.NL(map.get("roomId")));
        order.setRoomName((String) map.get("roomName"));
        order.setPlaceId(userPlace.getPlaceId());
        val place = placeService.getById(userPlace.getPlaceId());
        order.setPlaceName(place.getPlaceName());
        int result = orderService.creatNewOrder(order);
        if (result>0) {
            templateMessageService.sendNewMarkMessage(userOpenService.getUserByUserId(currentUser.getUserId()).getOpenId(),"",null);
        }
        return ModelOps.newSuccess(result);
    }

    @PostMapping("/cust/update_order.json")
    public ModelOps updateOrder(@RequestBody Map map) {

        Order order = orderService.selectByOrderId(Conv.NS(map.get("orderId")));
        User currentUser = userService.getUserById(Conv.NL(map.get("userId")));
        UserPlace userPlace = userPlaceService.getByUserIdAndPlaceId(currentUser.getUserId(), roomService.getByRoomId(Conv.NL(map.get("roomId"))).getPlaceId());

        if (Consts.USER_TYPE_L2.equals(userPlace.getUserType())) {

            order.setSaleId1(0L);
            order.setSaleId2(currentUser.getUserId());
            order.setSaleName1("");
            order.setSaleName2(currentUser.getStaffName());
        } else {
            order.setSaleId2(0L);
            order.setSaleName2("");
            order.setSaleId1(currentUser.getUserId());
            order.setSaleName1(currentUser.getStaffName());
        }
        order.setBeActive(Consts.ACT_ENABLE);
        order.setBePaid(Consts.PAID_NO);
        order.setCustomerName((String) map.get("customerName"));
        order.setCustomerTel((String) map.get("customerTel"));
        order.setCustomerNumber(Conv.NI(map.get("customerNumber")));
        if (!Strings.isNullOrEmpty(Conv.NS(map.get("orderCreateAt")))) {
            order.setOrderCreateAt(Conv.NS(map.get("orderCreateAt")));
        } else {
            order.setOrderCreateAt(new DateTime().toString());
        }
        order.setRoomId(Conv.NL(map.get("roomId")));
        order.setRoomName((String) map.get("roomName"));
        order.setPlaceId(userPlace.getPlaceId());
        val place = placeService.getById(userPlace.getPlaceId());
        order.setPlaceName(place.getPlaceName());

        return ModelOps.newSuccess(orderService.updateOrder(order));
    }
    */
}
