package com.sifang.modules.supply.order.controller;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.q7link.utils.Q7DataUtil;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.request.AddSupplierOrderReq;
import com.sifang.modules.supply.order.request.ChangeSupplyReq;
import com.sifang.modules.supply.order.service.CrmSupplyMaterialDeliverOrderService;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.order.service.SupplyOrderAuditService;
import com.sifang.modules.supply.order.service.TraderOrderService;
import com.sifang.modules.supply.order.vo.OrderDetailVo;
import com.sifang.modules.supply.setting.service.CrmSupplyDeliveryMethodService;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
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.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 供应商订单
 */
@Controller
@RequestMapping("${adminPath}/material/order")
public class SupplyOrderController extends BaseExceptionController {

    @Autowired
    DeliverOrderService deliverOrderService;

    @Autowired
    TraderOrderService traderOrderService;

    @Autowired
    CrmSupplyWarehouseSettingService warehouseSettingService;

    @Autowired
    CrmSupplyDeliveryMethodService deliveryMethodService;

    @Autowired
    SupplyOrderAuditService supplyOrderService;

    @Autowired
    TraderService traderService;

    @Resource
    private CrmSupplyMaterialDeliverOrderService crmSupplyMaterialDeliverOrderService;

    @RequestMapping("/supplyOrder")
    public String supplyOrder(Model model) {
        List<Record> methods = deliveryMethodService.listDeliverMethods();
        model.addAttribute("deliverMethods", methods);

        //供应商列表
        List<Record> supplyList = warehouseSettingService.getSupplyList();
        model.addAttribute("supplyList", supplyList);
        return "modules/supply/order/supplyOrderList";
    }

    /**
     * 待审批订单_h
     */
    @RequestMapping("/waitAuditOrder")
    public String waitAuditOrder(Model model){
       /* //判断平台员工角色 5.业务人员 6.运管部 7.物资专员 2.项目工程师（工程部）
        User user = UserUtils.getUser();
        String userType = user.getUserType();
        if (UserConstants.TYPE_PLAT_EMP.equals(userType)) {
            model.addAttribute("roleType", traderOrderService.findRoleType(user.getId()));
        }
        model.addAttribute("userType", userType);*/
        User user = UserUtils.getUser();
        model.addAttribute("userId",user.getId());
        model.addAttribute("userType",user.getUserType());
        //代理商列表
        List<Record> traderList = traderService.getAllTopTrader();
        model.addAttribute("traderList", traderList);

        List<Record> qqProjectList= Q7DataUtil.getAllQQProjectCode();
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/waitAuditOrderList";
    }

    /**
     * 待匹配订单
     */
    @RequestMapping("/waitMatchOrder")
    public String waitMatchOrder(Model model){
        return "modules/supply/order/waitMatchOrderList";
    }

    /**
     * 待发货订单--平台发货签收
     */
    @RequestMapping("/waitDeliverOrder")
    public String waitDeliverOrder(HttpServletRequest request, Model model){
        model.addAttribute("warehouses", MaterialUtils.getWarehouseList());
        model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        model.addAttribute("ascriptionId", CrmUtils.getAscription().getAscriptionId());
        List<Record> traders = traderService.getAllTopTrader();
        model.addAttribute("traders", traders);
        model.addAttribute("map", getParams(request));
        model.addAttribute("userType", UserUtils.getUser().getUserType());
        return "modules/supply/order/waitDeliverOrderList";
    }


    /**
     * 采购管理----待发货
     */
    @RequestMapping("/purchaseWaitInStock")
    public String purchase(HttpServletRequest request, Model model){
        //查询仓库信息
        model.addAttribute("warehouses",  MaterialUtils.getWarehouseList().stream().filter(m-> "1".equals(m.get("type"))).collect(Collectors.toList()));
        //发货仓库
        model.addAttribute("ascriptionId", CrmUtils.getAscription().getAscriptionId());
        //代理商列表
        List<Record> traders = warehouseSettingService.getSupplyList();
        model.addAttribute("traders", traders);
        //代理商名称
        model.addAttribute("map", getParams(request));
        //用户类型
        model.addAttribute("userType", UserUtils.getUser().getUserType());
        return "modules/supply/order/purchaseWaitInStock";
    }



    /**
     * 待发货订单--平台发货签收
     */
    @RequestMapping("/waitDeliverOrderEnd")
    public String waitDeliverOrderEnd(HttpServletRequest request, Model model){
        model.addAttribute("warehouses", MaterialUtils.getWarehouseList());
        model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        model.addAttribute("ascriptionId", CrmUtils.getAscription().getAscriptionId());
        List<Record> traders = traderService.getAllTopTrader();
        model.addAttribute("traders", traders);
        model.addAttribute("map", getParams(request));
        model.addAttribute("userType", UserUtils.getUser().getUserType());
        return "modules/supply/order/waitDeliverOrderListEnd";
    }

    /**
     * 采购入库----已发货
     */
    @RequestMapping("/purchaseWaitInStockEnd")
    public String purchaseWaitInStockEnd(HttpServletRequest request, Model model){
        model.addAttribute("warehouses", MaterialUtils.getWarehouseList().stream().filter(m-> "1".equals(m.get("type"))).collect(Collectors.toList()));
        model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        model.addAttribute("ascriptionId", CrmUtils.getAscription().getAscriptionId());
        List<Record> traders = warehouseSettingService.getSupplyList();
        model.addAttribute("traders", traders);
        model.addAttribute("map", getParams(request));
        model.addAttribute("userType", UserUtils.getUser().getUserType());
        return "modules/supply/order/purchaseWaitInStockEnd";
    }


    /**
     * 待收货订单
     */
    @RequestMapping("/waitReceiveOrder")
    public String waitReceiveOrder(Model model){
        List<Record> methods = deliveryMethodService.listDeliverMethods();
        model.addAttribute("deliverMethods", methods);
        User user = UserUtils.getUser();
        //供应链入库或代理商入库
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("inAscriptionId", ascription.getAscriptionId());
        /*if(User.USER_TYPE_YYS.equals(user.getUserType()) || User.USER_TYPE_WXG.equals(user.getUserType())){
            //发货单位
            model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        }*/
        //仓库列表
        List<Record> warehouses = warehouseSettingService.findWarehouseByAscriptionId(ascription.getAscriptionId());
        model.addAttribute("traderList", traderService.getAllTopTrader());
        model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        model.addAttribute("user", user);
        model.addAttribute("warehouses", warehouses);
        return "modules/supply/order/waitReceiveOrderList";
    }

    /**
     * 订单查询页面
     */
    @RequestMapping("/allOrderList")
    public String allOrderList(HttpServletRequest request, Model model) {
        List<Record> methods = deliveryMethodService.listDeliverMethods();
        model.addAttribute("deliverMethods", methods);
        User user = UserUtils.getUser();
        String ascriptionId = CrmUtils.getAscription().getAscriptionId();
        if (StringUtil.endsWithAny(user.getUserType(), User.USER_TYPE_KJ, User.USER_TYPE_ADVISOR)) {
            model.addAttribute("applyTraderId", ascriptionId);
        }
        model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        model.addAttribute("warehouses", MaterialUtils.getWarehouseList());
        model.addAttribute("ascriptionId", ascriptionId);
        model.addAttribute("userType", user.getUserType());
        List<Record> traders = traderService.getAllTrader();
        model.addAttribute("traders", traders);
        model.addAttribute("map", getParams(request));
        return "modules/supply/order/allOrderList";
    }

    @ResponseBody
    @RequestMapping("/ajaxForSupplyOrder")
    public String ajaxForSupplyOrder(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        User user=UserUtils.getUser();
        if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            map.put("userId",user.getId());
        }
        deliverOrderService.deliverOrderListPage(page, map);
        return page.renderJson();
    }

    /**
     * 采购入库待入库列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryQqList")
    public String queryQqList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        crmSupplyMaterialDeliverOrderService.queryQqList(page, map);
        return page.renderJson();
    }

    /**
     * 采购入库已入库列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryInStockList")
    public String queryInStockList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        crmSupplyMaterialDeliverOrderService.queryInStockList(page, map);
        return page.renderJson();
    }

    /**
     * 确认入库页面
     */
    @RequestMapping("toInStockForm")
    public String toInStockForm(String id, Model model,String status) {
        OrderDetailVo vo= crmSupplyMaterialDeliverOrderService.queryOrderById(id,status);
        model.addAttribute("orderDate",vo);
        model.addAttribute("status",status);
        return "modules/supply/order/toInStockFrom";
    }

    @ResponseBody
    @RequestMapping("/orderSubmit")
    public Result orderSubmit(HttpServletRequest request) {
        User user= UserUtils.getUser();
        Map<String, String> map = getParams(request);
        boolean result= crmSupplyMaterialDeliverOrderService.orderSubmit(map,user);
        if(!result){
            return Result.fail("提交失败");
        }
        return Result.ok();
    }


    @ResponseBody
    @RequestMapping("/ajaxForAllOrder")
    public String ajaxForAllOrder(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        deliverOrderService.allOrderListPage(page, map);
        return page.renderJson();
    }

    @ResponseBody
    @RequestMapping("/findDetails")
    public Object findDetails(String id){
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        return JsonKit.toJson(details);
    }

    /**
     * 添加或编辑页面
     */
    @RequestMapping("/toAddSupplyOrder")
    public String toAddSupplyOrder(String id, Model model) {
        if (StrKit.notBlank(id)) {
            CrmSupplyMaterialDeliverOrder order = deliverOrderService.findByOrderId(id);
            List<Record> details = deliverOrderService.findDetailsByOrderId(id);
            model.addAttribute("order", order);
            model.addAttribute("details", details);
            List<Record> outWarehouseList = warehouseSettingService.findWarehouseByAscriptionId(order.getDeliverId());
            model.addAttribute("outWarehouseList", outWarehouseList);
        }
        //供应商列表
        List<Record> supplyList = warehouseSettingService.getSupplyList();
        model.addAttribute("supplyList", supplyList);
        //供应链的仓库列表
        List<Record> warehouseList = warehouseSettingService.supplyChainWarehouses();
        model.addAttribute("inWarehouseList", warehouseList);
        return "modules/supply/order/addSupplyOrder";
    }

    /**
     * 添加或编辑供应商订单
     */
    @ResponseBody
    @RequestMapping("/addSupplyOrder")
    public Result addSupplyOrder(@Valid @RequestBody AddSupplierOrderReq req) {
        deliverOrderService.addSupplyOrder(req, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 撤销订单
     */
    @ResponseBody
    @RequestMapping("/cancelSupplyOrder")
    public Result cancelSupplyOrder(String id, String reason) {
        GuardUtils.notBlank(reason, "撤销原因不能为空");
        deliverOrderService.cancelSupplyOrder(id, reason, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 改派
     */
    @ResponseBody
    @RequestMapping("/changeSupply")
    public Result changeSupply(@Valid ChangeSupplyReq req){
        deliverOrderService.changeSupply(req, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping("/deleteSupplyOrder")
    public Result deleteSupplyOrder(String orderIds){
        GuardUtils.notBlank(orderIds, "orderIds不能为空");
        deliverOrderService.deleteSupplyOrder(orderIds, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }
}
