package com.goafanti.order.controller;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.BaseApiController;
import com.goafanti.common.enums.OrderState;
import com.goafanti.common.model.ConsultOrder;
import com.goafanti.common.service.SysDictService;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.service.ConsultOrderService;

@RestController
@RequestMapping(value = "/api/user/consultorder")
public class UserConsultOrderApiController extends BaseApiController {

	private static final String	CONSULT_PRICE	= "consult_price";

	@Autowired
	SysDictService				sysDictService;
	@Autowired
	ConsultOrderService			consultOrderService;

	/**
	 * 前台生成订单
	 * 
	 * @param toUserId
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result addConsultOrder(String toUserId) {
		String price = sysDictService.getValue(CONSULT_PRICE);
		if (StringUtils.isNotBlank(price) && StringUtils.isNotBlank(toUserId)) {
			return res().data(consultOrderService.insertSelective(toUserId, Double.parseDouble(price)));
		}
		return res().error(buildError(ErrorConstants.PARAM_ERROR, "参数错误", "预约"));
	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/price", method = RequestMethod.GET)
	public Result getPrice() {
		return res().data(sysDictService.getValue(CONSULT_PRICE));
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/del", method = RequestMethod.POST)
	public Result delConsultOrder(Long id) {
		ConsultOrder co = consultOrderService.selectByPrimaryKey(id);
		if (co.getOrderState() != OrderState.UNPAYED.getCode()
				|| !StringUtils.equals(co.getUserId(), TokenManager.getUserId())) {
			return res().data(0);
		}
		ConsultOrder newCo = new ConsultOrder();
		newCo.setId(co.getId());
		newCo.setOrderState(OrderState.CANCELLED.getCode());
		return res().data(consultOrderService.updateByPrimaryKeySelective(newCo));
	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result list(String number, String toNumber, String pageNo, String pageSize, String id, String paymentId,
			String state) {
		Map<String, Object> params = consultOrderService.disposeSearchParams(number, toNumber, id, paymentId, state);
		params.put("uid", TokenManager.getUserId());
		return res().data(consultOrderService.getList(params, getPageNo(pageNo), getPageSize(pageSize)));
	}

}
