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

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.service.CrmSupplyPurchaseOrderService;
import com.sifang.modules.supply.warehouse.service.WarehouseExportService;
import com.sifang.modules.supply.warehouse.vo.AddPurchaseOrderVo;
import com.sifang.modules.supply.warehouse.vo.ExaminePurchaseOrderVo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlUtils;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/purchaseManage")
public class CrmSupplyPurchaseOrderController extends BaseExceptionController {

    Logger logger = LoggerFactory.getLogger(CrmSupplyPurchaseOrderController.class);
    @Autowired
    private CrmSupplyPurchaseOrderService purchaseOrderService;
    @Autowired
    CrmSupplyWarehouseSettingService crmSupplyWarehouseSettingService;
    @Autowired
    WarehouseExportService warehouseExportService;


    @RequestMapping(value = "purchasePage")
    public String purchasePage(Model model) {
        User user = UserUtils.getUser();
        model.addAttribute("userType", CrmUtils.getCurrentUserType(user));
       /* if(User.USER_TYPE_PTYG.equals(user.getUserType())){  //平台员工
            String userRelId=CrmUtils.getUserRelId(user);  //找出员工绑定的供应商
            String supplierId= Db.queryStr(" SELECT id FROM `crm_supply_supplier` WHERE supervision_id=? AND STATUS='1' AND binding_flag='1' limit 1",userRelId);
            if(StringUtil.isNotBlank(supplierId)){ //员工绑定了供应商的监造员
                model.addAttribute("supplierId",supplierId);
                model.addAttribute("warehouse", MaterialUtils.findMaterialWarehouseByAscriptionId(supplierId));
                return "modules/supply/warehouse/jzyPurchasePage";
            }
        }*/
        List<Record> warehouses=MaterialUtils.findMaterialWarehouse("3",user.getTopTraderId());
        model.addAttribute("warehouse",warehouses);
        return "modules/supply/warehouse/purchasePage";
    }

    @RequestMapping(value = "jzyPurchasePage")
    public String jzyPurchasePage(Model model) {
        User user = UserUtils.getUser();
        model.addAttribute("userType", CrmUtils.getCurrentUserType(user));
        if(User.USER_TYPE_PTYG.equals(user.getUserType())){  //平台员工
            String userRelId=CrmUtils.getUserRelId(user);  //找出员工绑定的供应商
            List<String> supplierId= MaterialUtils.findSupplierIdsList(userRelId);
            if(supplierId.size()>0){ //员工绑定了供应商的监造员
               // model.addAttribute("supplierId", );
                model.addAttribute("warehouse", MaterialUtils.findMaterialWarehouseByAscIds(supplierId));
                return "modules/supply/warehouse/jzyPurchasePage";
            }
        }

        return "modules/supply/warehouse/jzyPurchasePage";
    }
    @ResponseBody
    @RequestMapping(value = "purchaseOrderList")
    public Object purchaseOrderList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        purchaseOrderService.purchaseOrderList(page, map);
        return page.renderJson();
    }

    //监造员页面的采购单
    @ResponseBody
    @RequestMapping(value = "inspectionPurchaseOrderList")
    public Object inspectionPurchaseOrderList(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        purchaseOrderService.inspectionPurchaseOrderList(page, map);
        return page.renderJson();
    }

    @RequestMapping(value = "addPurchaseOrderPage")
    public String addPurchaseOrderPage(Model model, HttpServletRequest request) {
        List<Record> supplyList = crmSupplyWarehouseSettingService.getSupplyList();
        model.addAttribute("supplyList", supplyList);
        String id = request.getParameter("id");
        if (StringUtil.isNotBlank(id)) {
            model.addAttribute("details", purchaseOrderService.orderMaterialList(id));
            model.addAttribute("order", purchaseOrderService.getOrderDetail(id));
        }
        model.addAttribute("model", request.getParameter("model"));
        return "modules/supply/warehouse/addPurchaseOrder";
    }

    @ResponseBody
    @RequestMapping(value = "addPurchaseOrder")
    public Result addPurchaseOrder(@Valid @RequestBody AddPurchaseOrderVo orderVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(" into addPurchaseOrder orderVo={}", orderVo);
        purchaseOrderService.addPurchaseOrder(orderVo);
        return Result.ok();
    }

    @RequestMapping(value = "orderMaterialList")
    public String orderMaterialList(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        model.addAttribute("details", purchaseOrderService.orderMaterialList(id));
        String inspectionId=request.getParameter("inspectionId");
        if(StringUtil.isNotBlank(inspectionId)){   //监造员页面的物料清单
            model.addAttribute("details", purchaseOrderService.getInspectionMaterialList(inspectionId));
        }
        return "modules/supply/warehouse/orderMaterialList";
    }

    @RequestMapping(value = "orderDetail")
    public String orderDetail(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        model.addAttribute("details", purchaseOrderService.orderMaterialList(id));
        model.addAttribute("order", purchaseOrderService.getOrderDetail(id));
        model.addAttribute("msgs", purchaseOrderService.getMsgs(id));
        User user = UserUtils.getUser();
        String userType=user.getUserType();
        String inspectionId=request.getParameter("inspectionId");
        if(StringUtil.isNotBlank(inspectionId)){   //监造员页面的采购详情
            Record inspection=purchaseOrderService.getInspection(inspectionId);
            model.addAttribute("inspection",inspection);
        }
        if(User.USER_TYPE_PTYG.equals(user.getUserType())){  //平台员工
            String userRelId=CrmUtils.getUserRelId(user);  //找出员工绑定的供应商
            String supplierId= Db.queryStr(" SELECT id FROM `crm_supply_supplier` WHERE supervision_id=? AND STATUS='0' AND binding_flag='1' limit 1",userRelId);
            if(StringUtil.isBlank(supplierId)){ //员工不是监造员
               userType="1";
            }
        }
        if(User.USER_TYPE_GYS.equals(user.getUserType())){
          List<Record> inspectionDetails= purchaseOrderService.getInspectionDetail(id);
          model.addAttribute("inspectionDetails",inspectionDetails);

        }
        model.addAttribute("userType", userType);  // 4 平台员工 判段是否是监造员  1 平台（供应链）  8 供应商
        return "modules/supply/warehouse/orderDetail";
    }

    @ResponseBody
    @RequestMapping(value = "cancelPurchaseOrder")
    public Result cancelPurchaseOrder(HttpServletRequest request) {
        String id = request.getParameter("id");
        String remark = request.getParameter("remark");
        purchaseOrderService.cancelPurchaseOrder(id, remark);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "deletePurchaseOrder")
    public Result deletePurchaseOrder(HttpServletRequest request) {
        String orderIds = request.getParameter("orderIds");
        purchaseOrderService.deletePurchaseOrder(orderIds);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "confirmPurchaseOrder")
    public Result confirmPurchaseOrder(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        purchaseOrderService.confirmPurchaseOrder(orderId);
        return Result.ok();
    }

    //报检页面
    @RequestMapping(value = "purchaseOrderInspectionPage")
    public String purchaseOrderInspectionPage(Model model, HttpServletRequest request){
        String id = request.getParameter("id");
        model.addAttribute("id", id);
        model.addAttribute("details", purchaseOrderService.orderMaterialList(id));
        return "modules/supply/warehouse/inspectionPage";
    }

    //检验页面
    @RequestMapping(value = "examinePurchaseOrderPage")
    public String examinePurchaseOrderPage(Model model, HttpServletRequest request) {
        String inspectionId = request.getParameter("id");
        model.addAttribute("id", inspectionId);
        String supplierId=request.getParameter("supplierId");
        List<String> list = Lists.newArrayList();
        list.add(supplierId);
        model.addAttribute("details", purchaseOrderService.getExamineMaterialList(inspectionId));
      /*  Record order = purchaseOrderService.getOrderDetail(id);
        model.addAttribute("order", order);*/
        model.addAttribute("warehouse", MaterialUtils.findMaterialWarehouseByAscIds(list));
        return "modules/supply/warehouse/examinePurchaseOrder";
    }


    @ResponseBody
    @RequestMapping(value = "getLocations")
    public Object getLocations(HttpServletRequest request) {
        String warehouseId=request.getParameter("warehouseId");
        String inspectionId=request.getParameter("inspectionId");
        List<Record> list= purchaseOrderService.getLocations(warehouseId,inspectionId);
        return list;
    }

    // 检验
    @ResponseBody
    @RequestMapping(value = "examinePurchaseOrder")
    public Result examinePurchaseOrder(@Valid @RequestBody ExaminePurchaseOrderVo orderVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(" into examinePurchaseOrder orderVo={}", orderVo);
        purchaseOrderService.examinePurchaseOrder(orderVo);
        return Result.ok();
    }

    // 报检
    @ResponseBody
    @RequestMapping(value = "inspectionPurchaseOrder")
    public Result inspectionPurchaseOrder(@Valid @RequestBody ExaminePurchaseOrderVo orderVo){
        logger.info(" into inspectionPurchaseOrder orderVo={}", orderVo);
        purchaseOrderService.inspectionPurchaseOrder(orderVo);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "exportPurchaseOrder")
    public void exportPurchaseOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> map = getParams(request);
        warehouseExportService.exportPurchaseOrder(map, response);
    }
}
