package com.iamberry.wechat.handles.channel;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.channel.ChannelAdmin;
import com.iamberry.wechat.core.entity.channel.ChannelPrice;
import com.iamberry.wechat.core.entity.channel.ChildChannel;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.receive.ChargerReceive;
import com.iamberry.wechat.face.channel.ChannelAdminService;
import com.iamberry.wechat.face.channel.ChannelPriceService;
import com.iamberry.wechat.face.channel.MainChannelService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.porduct.ProductService;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.StitchAttrUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/wechat/channelAdmin")
public class ChannelAdminHandler {

    private Logger logger = LoggerFactory.getLogger(ChannelAdminHandler.class);

    @Autowired
    private MemberService memberService;

    @Autowired
    private ChannelAdminService channelAdminService;

    @Autowired
    private MainChannelService mainChannelService;

    @Autowired
    private AdminOrderService adminOrderService;

    @Autowired
    private ChannelPriceService channelPriceService;

    @Autowired
    private ProductService productService;

    /**
     * 获取当前渠道管理员下面的代理产品-以产品展示
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getProductList")
    public ResultMsg getProductList(HttpServletRequest request,
                                    @RequestParam(value= "channelType",defaultValue= "0" ,required=false) Integer channelType,
                                    @RequestParam(value= "channelId",defaultValue= "0" ,required=false) Integer channelId
    ) throws Exception {
        ResultMsg msg = ResultMsg.getError();

        if(channelType == 0 || channelId == 0){
            msg.setMessage("网络错误，请重试！");
            return msg;
        }

        ChannelPrice channelPrice = new ChannelPrice();
        channelPrice.setChannelType(channelType);
        channelPrice.setChannelId(channelId);
        List<ChannelPrice> channelPriceList = channelPriceService.getChannelProductList(channelPrice);

        List<Product> productList = new ArrayList<>();
        for (ChannelPrice cp : channelPriceList){
            Product product = productService.selectProductByProductId(cp.getProductId());
            product.setColorId(cp.getColorId());
            product.setProductDiscount(cp.getChannelPriceOffer());
            product.setProductPrice(cp.getChannelOriginalPrice());
            productList.add(product);
        }

        msg = ResultMsg.getSuccess();
        msg.setData(productList);
        return msg;
    }


    /**
     *  获取提货列表
     *  主渠道下面所有的提货
     *  主渠道下面所有子渠道的
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getChannelList")
    public ResultMsg getChannelList(HttpServletRequest request,Order order,
       @RequestParam(value= "pageSize",defaultValue= "10" ,required=false) Integer pageSize,
       @RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO,
       @RequestParam(value = "totalNum", defaultValue = "0", required = false) Integer totalNum
    ) throws Exception {
        ResultMsg msg = ResultMsg.getError();

        Integer status = order.getSalesStatus();

        // 用户信息
        String openId  = WechatUtils.getUserBySession(request).getUserOpenid();

        ChannelAdmin channelAdmin = new ChannelAdmin();
        channelAdmin.setChannelAdminOpenId(openId);
        channelAdmin.setChannelAdminStatus(1);
        channelAdmin.setChannelType(1); //主渠道
        List<ChannelAdmin> channelAdminList = channelAdminService.getChannelAdminList(channelAdmin);

        if(channelAdminList == null || channelAdminList.size() < 1){
            logger.info("====="+openId+"不是主渠道的管理员！");
            msg.setMessage("您还不是主渠道的管理员，请联系上朵！");
            return msg;
        }

        List<Integer> ids = new ArrayList<>();
        for (int i=0;i<channelAdminList.size();i++){
            ids.add(channelAdminList.get(i).getChannelId());
        }
        order.setChannelIds(ids);

        if(order.getSalesStatus() == 99){
            order.setSalesStatus(null);
            order.setSalesTransportationType(null);
        }else{
            order.setSalesTransportationType(2);
        }

        // 封装请求数据
        PageRequest<Order> pageRequest = new PageRequest<>(order, pageNO, pageSize, totalNum == 0);
        // 查询订单列表
        PagedResult<Order> result = channelAdminService.listOrderPage(pageRequest);
        Boolean lastPage = StitchAttrUtil.getSa().getLastPage(result);

        List<Order> orderList = result.getDataList();
        for (Order or :orderList) {
            if(status == 99 && or.getSalesTransportationType() == 1){
                String name = or.getSalesAddressName();
                name = name.substring(0,1) + "**";
                String tel = or.getSalesAddressTel();
                tel = tel.substring(0,3) + "****" + tel.substring(7,11) ;
                or.setSalesAddressName(name);
                or.setSalesAddressTel(tel);
            }
            List<OrderItem>orderItemList = adminOrderService.getShopOrderItemByOrderId(or.getSalesOrderid());
            or.setOrderItemList(orderItemList);
        }

        Order or = new Order();
        or.setChannelIds(ids);
        or.setSalesTransportationType(2);
        or.setSalesStatus(2);
        Integer dfStatus = channelAdminService.listOrderCount(or);
        or.setSalesStatus(5);
        Integer yfStatus = channelAdminService.listOrderCount(or);
        or.setSalesStatus(null);
        or.setSalesTransportationType(null);
        Integer allStatus = channelAdminService.listOrderCount(or);

        Map<String,Object> map = new HashMap<>();
        map.put("orderList",orderList);
        map.put("lastPage",lastPage);
        map.put("dfStatus",dfStatus);
        map.put("yfStatus",yfStatus);
        map.put("allStatus",allStatus);

        msg = ResultMsg.getSuccess();
        msg.setData(map);
        return msg;
    }

    /**
     *  修改订单状态为已提货
     *  订单状态：  已付款 --> 已发货
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus")
    public ResultMsg updateStatus(HttpServletRequest request,String salesOrderid) throws Exception {
        ResultMsg msg = ResultMsg.getError();

        if(salesOrderid == null || "".equals(salesOrderid)){
            msg.setMessage("订单号不能为空");
            return msg;
        }
        Order order = adminOrderService.getShopOrderByOrderId(salesOrderid);
        if(order.getSalesStatus() != 2){
            msg.setMessage("该订单无法修改为已提货");
            return msg;
        }

        order = new Order();
        order.setSalesOrderid(salesOrderid);
        order.setSalesStatus(5);
        order.setOldStatus(2);
        boolean flag = adminOrderService.updateOrderStatusByOrderId(order);

        if(flag){
            msg = ResultMsg.getSuccess();
            return msg;
        }else{
            msg.setMessage("修改订单状态失败！");
            return msg;
        }
    }


}
