package com.sifang.modules.smallprogram.supply;


import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.supply.order.dao.MaterialApplyDao;
import com.sifang.modules.supply.order.dao.MaterialDeliverDao;
import com.sifang.modules.supply.order.dao.MaterialOutStockOrderDao;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyAllocationOrderDao;
import com.sifang.modules.supply.warehouse.dao.InventoryOrderDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrder;
import com.sifang.modules.supply.warehouse.service.CrmSupplyAllocationOrderService;
import com.sifang.modules.supply.warehouse.vo.OutAllocationOrderVo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping(value = "${adminPath}/main/allocation")
public class SmallProgramAllocationController extends BaseController {

    Logger logger = LoggerFactory.getLogger(SmallProgramAllocationController.class);

    @Autowired
    private CrmSupplyAllocationOrderService allocationOrderService;

    @Autowired
    private CrmSupplyAllocationOrderDao allocationOrderDao;

    @Autowired
    UserDao userDao;

    @Autowired
    MaterialDeliverDao deliverDao;

    @Autowired
    MaterialApplyDao materialApplyDao;

    @Autowired
    MaterialOutStockOrderDao outStockOrderDao;

    private User getUser(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        if (StrKit.isBlank(userId)) {
            throw new BusinessException("userId不能为空");
        }
        User user = userDao.get(userId);
        if (user == null) {
            user = userDao.getById(userId);
        }
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (!"0".equals(user.getStatus())) {
            throw new BusinessException("当前账号已禁用或已删除，不可操作！");
        }

        return user;
    }

    //获取首页各订单数量
    @ResponseBody
    @RequestMapping(value = "getIndexNumber")
    public Result getIndexNumber(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        String userId = request.getParameter("userId");
        Ascription ascription = CrmUtils.getAscription(userDao.getById(userId));
        map.put("applyTraderId", ascription.getAscriptionId());
        //订单查询
        Long ddcx=deliverDao.countAllOrderList(map);
        map.put("ascriptionId", ascription.getAscriptionId());
        map.put("inventoryObjectId", ascription.getAscriptionId());
        //入库单
        map.put("inAscriptionId",ascription.getAscriptionId());
        map.put("inStockOnly", "1");
        Long inCount= deliverDao.countDeliverOrderList(map);
        //出库单
        Long outCount=outStockOrderDao.countOutStockOrder(map);
        //调拨单
        Long dbCount=allocationOrderDao.contOrderList(map);

       Map<String,Long> resultMap=new HashMap<>();
        resultMap.put("inCount",inCount);
        resultMap.put("outCount",outCount);
        resultMap.put("dbCount",dbCount);
        resultMap.put("ddcx",ddcx);
        return new Result().success(resultMap);
    }
    /**
     * 移动端 只有代理商可以登录
     */
    //调拨单列表
    @ResponseBody
    @RequestMapping(value = "allocationList")
    public String allocationList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String userId = request.getParameter("userId");
        Ascription ascription = CrmUtils.getAscription(userDao.getById(userId));
        map.put("ascriptionId", ascription.getAscriptionId());
        LayuiPage page = new LayuiPage(request);
       /* allocationOrderService.allocationOrderList(page, map);*/
        page.setMsg(ascription.getAscriptionId());
        return page.renderJson();
    }

    //调拨单详情
    @ResponseBody
    @RequestMapping(value = "allocationDetail")
    private Result allocationDetail(HttpServletRequest request) {
        String id = request.getParameter("orderId");
        Map<String, Object> map = new HashMap<>();
        CrmSupplyAllocationOrder order = allocationOrderService.getOrderDetail(id);
        List<Record> details = allocationOrderService.getMaterialList(id);
        map.put("details", allocationOrderService.getWarehouseStock2(details, order.getWarehouseId()));
        map.put("order", order);
        Result result = new Result();
        result.setCode("200");
        result.setData(map);
        return result;
    }

    //出库操作
    @ResponseBody
    @RequestMapping(value = "outAllocationOrder")
    public Result outAllocationOrder(@Valid @RequestBody OutAllocationOrderVo allocationOrderVo, HttpServletRequest request) {
        logger.info(">>>>>>>>>>>>> into SmallProgramAllocationController  outAllocationOrder allocationOrderVo={}", allocationOrderVo);
        User user = getUser(request);
        Result result=new Result();
        try{
            allocationOrderService.outAllocationOrder(allocationOrderVo, user);
            result.setCode("200");
        }catch (BusinessException b){
            result.setCode("501");
            result.setErrMsg(b.getMessage());
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>>>>>>>smallProgram outAllocationOrder  Exception:{}",e);
            e.printStackTrace();
            result.setCode("205");
        }

        return result;
    }

    //入库操作
    @ResponseBody
    @RequestMapping(value = "inAllocationOrder")
    public Result inAllocationOrder(@Valid @RequestBody OutAllocationOrderVo allocationOrderVo, HttpServletRequest request) {
        User user = getUser(request);
        logger.info(">>>>>>>>>>>>> into inAllocationOrder allocationOrderVo={}", allocationOrderVo);
        Result result=new Result();
        try{
            allocationOrderService.inAllocationOrder(allocationOrderVo, user);
            result.setCode("200");
        }catch (BusinessException b){
            result.setCode("501");
            result.setErrMsg(b.getMessage());
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>>>>>>>smallProgram inAllocationOrder  Exception:{}",e);
            e.printStackTrace();
            result.setCode("205");
        }

        return result;
    }

    //获取发货方式
    @ResponseBody
    @RequestMapping(value = "getDelivery")
    public Object getDelivery() {
        List<Record> deliveryMethods = MaterialUtils.getDeliveryMethod();
        return deliveryMethods;
    }
}
