package com.iamberry.wechat.handles.agentInfo;

import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.agentInfo.AgentConfig;
import com.iamberry.wechat.core.entity.agentInfo.AgentOrder;
import com.iamberry.wechat.core.entity.agentInfo.AgentOrderItem;
import com.iamberry.wechat.core.entity.agentInfo.AgentTooth;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.face.agentInfo.AgentInfoService;
import com.iamberry.wechat.face.agentInfo.AgentPurchaseOrderService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResultInfo;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购&订单
 */
@Controller
@RequestMapping("/wechat/agentOrder")
public class AgentOrderHandler {
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private AgentPurchaseOrderService agentPurchaseOrderService;
    @Autowired
    private PayService payService;

    /**
     * 获取采购信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getProduce")
    public ResultMsg getProduce(HttpServletRequest request) {
        ResultMsg rm = new ResultMsg();
        Member member = WechatUtils.getUserBySession(request);
        String agentOpenid = member.getUserOpenid();

        AgentTooth agentTooth = new AgentTooth();
        agentTooth.setAgentOpenid(agentOpenid);
        agentTooth = agentInfoService.getAgentTooth(agentTooth);
        if (agentTooth == null) {
            rm.setStatus(false);
            rm.setMessage("未找到该用户!");
            rm.setResultCode(ResultInfo.ERRORCODE);
            return rm;
        }

        Product product = new Product();
        List<Product> productList = productInfoService.listSelectProduct(product);

        for (Product pd : productList) {
            AgentConfig agentConfig = new AgentConfig();
            agentConfig.setColorId(pd.getColorId());
            agentConfig.setAgentId(agentTooth.getAgentId());
            agentConfig.setConfigStatus(1);
            agentConfig = agentInfoService.getAgentConfig(agentConfig);
            if (agentConfig != null && agentConfig.getConfigAmount() != null && agentConfig.getConfigAmount() != 0) {
                pd.setConfigAmount(agentConfig.getConfigAmount());
            } else {
                pd.setConfigAmount(pd.getProductDiscount());
            }
        }
        rm.setStatus(true);
        rm.setMessage("查询成功!");
        rm.setResultCode("200");
        rm.setData(productList);
        return rm;
    }

    /**
     * 校验订单状态，判断是否支付成功
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkOrderPaySuccess")
    public ResultMsg checkOrderPaySuccess(
            @RequestParam(value = "orderId") String orderId) {
        ResultMsg msg = new ResultMsg();
        msg.setResultCode(ResultInfo.ERRORCODE);
        AgentOrder agentOrder = new AgentOrder();
        List<AgentOrder> agentOrderList = agentPurchaseOrderService.listAgentOrder(agentOrder);
        AgentOrder ao = agentOrderList.get(0);
        Integer orderStatus = ao.getAgentStatus();
        if (orderStatus != null && orderStatus.intValue() == 2) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
            msg.setStatus(true);
            return msg;
        }
        msg.setResultCode(ResultInfo.ERRORCODE);
        msg.setMessage(NameUtils.getConfig("ERRORINFO"));
        msg.setStatus(false);

        return msg;
    }

    /**
     * 分页查询代理商采购订单
     * @param request
     * @param pageSize
     * @param pageNO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_agent_order_list")
    public ResultMsg selectAgentOrderList(HttpServletRequest request,
                                          @RequestParam(value= "pageSize",defaultValue= "6" ,required=false) Integer pageSize,
                                          @RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO) throws Exception {
        ResultMsg msg = new ResultMsg();
        Map<String,Object> map = new HashMap<String,Object>();
        Member member = WechatUtils.getUserBySession(request);
        AgentTooth agent = new AgentTooth();
        AgentOrder agentOrder = new AgentOrder();
        String status = request.getParameter("status");
        if (StringUtils.isNotEmpty(status)) {
            agentOrder.setAgentStatus(Integer.parseInt(status));
        }
        agent.setAgentOpenid(member.getUserOpenid());
        //获取代理商信息
        agent = agentInfoService.getAgentTooth(agent);
        if (agent == null) {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("您不是代理商,没有采购订单!");
            return msg;
        }

        agentOrder.setAgentId(agent.getAgentId());
        PageBean page = new PageBean();
        page.setPageNumber(pageNO);
        page.setPageSize(pageSize);
        page.initRecordBegin();
        agentOrder.setPage(page);
        //获取订单集合
        List<AgentOrder> agentOrderList = agentPurchaseOrderService.listAgentOrder(agentOrder);
        map.put("agent",agent);
        map.put("agentOrderList",agentOrderList);
        msg.setData(map);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

    /**
     * 修改订单备注，只能是待支付订单可以修改
     * @param request
     * @param remark
     * @param agentOrderid
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/update_remark")
    public ResultMsg updateRemark(HttpServletRequest request,
                                  @RequestParam(value= "remark",defaultValue= "" ,required=false) String remark,
                                  @RequestParam(value= "agentOrderid",defaultValue= "" ,required=false) String agentOrderid) throws Exception {
        ResultMsg msg = new ResultMsg();
        if (!StringUtils.isNotEmpty(agentOrderid)) {
            msg.setMessage("订单号不能为空!");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }
        AgentOrder order = new AgentOrder();
        order.setAgentOrderid(agentOrderid);
        order.setAgentAdminRemark(remark);
        //根据orderid查询订单信息
        List<AgentOrder> orderList = agentPurchaseOrderService.listSelectAgentOrder(order);

        if (orderList == null || orderList.size() == 0) {
            msg.setMessage("该订单信息不存在!");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }
        AgentOrder agentOrder = orderList.get(0);
        if (agentOrder.getAgentStatus() != 1) {
            msg.setMessage("该订单不是待支付订单，不能修改备注信息!");
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            return msg;
        }

        //修改订单备注信息
        int num = agentPurchaseOrderService.updateRemark(order);
        if (num > 0) {
            msg.setResultCode(ResultInfo.SUCCESSCODE);
            msg.setStatus(true);
            return msg;
        } else {
            msg.setResultCode(ResultInfo.ERRORCODE);
            msg.setStatus(false);
            msg.setMessage("修改订单备注失败!");
            return msg;
        }
    }


}
