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

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrder;
import com.sifang.modules.supply.warehouse.service.CrmSupplyAllocationOrderService;
import com.sifang.modules.supply.warehouse.service.WarehouseExportService;
import com.sifang.modules.supply.warehouse.vo.AddAllocationDetailVo;
import com.sifang.modules.supply.warehouse.vo.AddAllocationOrderVo;
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.entity.Ascription;
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.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}/allocation")
public class CrmSupplyAllocationOrderController extends BaseExceptionController {

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

    @Autowired
    private CrmSupplyAllocationOrderService allocationOrderService;

    @Autowired
    WarehouseExportService warehouseExportService;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    CrmSupplyWarehouseSettingService warehouseSettingService;

    @RequestMapping(value = "allocationPage")
    public String allocationPage(Model model) {
        User user = UserUtils.getUser();
        model.addAttribute("userType", CrmUtils.getCurrentUserType(user));
        List<Record> list=MaterialUtils.getWarehouseList();
        model.addAttribute("warehouses",list);
        Ascription ascription=CrmUtils.getAscription();
        model.addAttribute("ascription",ascription);
        model.addAttribute("formId", FormUtils.TRANSFER_ORDER_APPLICATION);
        return "modules/supply/warehouse/allocation/allocationPage";
    }

    @ResponseBody
    @RequestMapping(value = "allocationOrderList")
    public Object allocationOrderList(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        User user = UserUtils.getUser();
        String userType = CrmUtils.getCurrentUserType(user);
        if(!"1".equals(userType)){
            Ascription ascription=CrmUtils.getAscription();
            map.put("ascriptionId",ascription.getAscriptionId());
        }
        allocationOrderService.allocationOrderList(page, map,user);
        return page.renderJson();
    }

    @RequestMapping(value = "addAllocationOrderPage")
    public String addAllocationOrderPage(HttpServletRequest request,Model model){
        List<Record> list=MaterialUtils.findMaterialWarehouse("1","");
        model.addAttribute("warehouses",list);
        model.addAttribute("model",request.getParameter("model"));
        String id=request.getParameter("id");
        if(StringUtil.isNotBlank(id)){
            CrmSupplyAllocationOrder order=allocationOrderService.getOrderDetail(id);
            List<Record> details=allocationOrderService.getMaterialList(id);
            model.addAttribute("details",details);
            model.addAttribute("order",order);
            CrmSupplyWarehouse warehouse = warehouseSettingService.getWarehouseDetail(order.getInWarehouseId());
            model.addAttribute("warehouse",warehouse);
        }
        model.addAttribute("id",id);
        return "modules/supply/warehouse/allocation/addAllocationOrderPage";
    }

    @RequestMapping(value = "examineAllocationOrderPage")
    public String examineAllocationOrderPage(HttpServletRequest request,Model model){
        String from=request.getParameter("from");
        List<Record> list=MaterialUtils.getWarehouseList();
        model.addAttribute("warehouses",list);
        model.addAttribute("model",request.getParameter("model"));
        String id=request.getParameter("id");
        if(StringUtil.isNotBlank(id)){
            CrmSupplyAllocationOrder order=allocationOrderService.getOrderDetail(id);
            List<Record> details=allocationOrderService.getMaterialList(id);
            model.addAttribute("details",details);
            model.addAttribute("order",order);
            CrmSupplyWarehouse warehouse = warehouseSettingService.getWarehouseDetail(order.getInWarehouseId());
            model.addAttribute("warehouse",warehouse);
            if("look".equals(from)){
                flowableService.readApplication(order.getProcessInstanceId(),FormUtils.TRANSFER_ORDER_APPLICATION,id,UserUtils.getUser());
            }
        }
        model.addAttribute("id",id);
        model.addAttribute("msgs", allocationOrderService.getMsgs(id));
        return "modules/supply/warehouse/allocation/examineAllocationOrderPage";
    }

    @ResponseBody
    @RequestMapping(value="getWarehouseStock")
    public Result getWarehouseStock(@Valid @RequestBody List<AddAllocationDetailVo> detailVos,HttpServletRequest request){
        String warehouseId=request.getParameter("warehouseId");
        logger.info(">>>>>>>>>>>getWarehouseStock detailvo:{}",detailVos);
        allocationOrderService.getWarehouseStock(detailVos,warehouseId);
        Result result=new Result();
        result.setCode("200");
        result.setData(detailVos);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "addAllocationOrder")
    public Result addAllocationOrder(@Valid @RequestBody AddAllocationOrderVo addAllocationOrderVo, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(">>>>>>>>>>>>> into addAllocationOrder addAllocationOrderVo={}", addAllocationOrderVo);
        allocationOrderService.addAllocationOrder(addAllocationOrderVo);
        return Result.ok();
    }

    @RequestMapping(value = "allcoationOrderDetail")
    public String  allcoationOrderDetail(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        CrmSupplyAllocationOrder order=allocationOrderService.getOrderDetail(id);
        List<Record> details=allocationOrderService.getMaterialList(id);
        model.addAttribute("details",details);
        model.addAttribute("order",order);
        model.addAttribute("msgs", allocationOrderService.getMsgs(id));
        User user = UserUtils.getUser();
        model.addAttribute("user",user);
        return "modules/supply/warehouse/allocation/allcoationOrderDetail";
    }

    @RequestMapping(value = "allocationMaterialList")
    public String allocationMaterialList(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        List<Record> details=allocationOrderService.getMaterialList(id);
        model.addAttribute("details",details);
        return "modules/supply/warehouse/allocation/allocationMaterialList";
    }

    @RequestMapping(value = "outWarehousePage")
    public String outWarehousePage(HttpServletRequest request,Model model){
        List<Record> deliveryMethods=MaterialUtils.getDeliveryMethod();
        model.addAttribute("deliveryMethods",deliveryMethods);
        String id=request.getParameter("id");
        model.addAttribute("id",id);
        CrmSupplyAllocationOrder order=allocationOrderService.getOrderDetail(id);
        List<Record> details=allocationOrderService.getMaterialList(id);
        model.addAttribute("details",allocationOrderService.getWarehouseStock2(details,order.getWarehouseId()));
        model.addAttribute("order",order);
        return "modules/supply/warehouse/allocation/outWarehousePage";
    }


    @ResponseBody
    @RequestMapping(value="outAllocationOrder")
    public Result outAllocationOrder(@Valid @RequestBody OutAllocationOrderVo allocationOrderVo, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(">>>>>>>>>>>>> into outAllocationOrder allocationOrderVo={}", allocationOrderVo);
        User user = UserUtils.getUser();
        allocationOrderService.outAllocationOrder(allocationOrderVo,user);
        return Result.ok();
    }

    @RequestMapping(value = "inWarehousePage")
    public String inWarehousePage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        model.addAttribute("id",id);
        CrmSupplyAllocationOrder order=allocationOrderService.getOrderDetail(id);
        List<Record> details=allocationOrderService.getMaterialList2(id,order.getInWarehouseId());
        model.addAttribute("details",details);
        return "modules/supply/warehouse/allocation/inWarehousePage";
    }

    @ResponseBody
    @RequestMapping(value="inAllocationOrder")
    public Result inAllocationOrder(@Valid @RequestBody OutAllocationOrderVo allocationOrderVo, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(">>>>>>>>>>>>> into inAllocationOrder allocationOrderVo={}", allocationOrderVo);
        User user = UserUtils.getUser();
        allocationOrderService.inAllocationOrder(allocationOrderVo,user);
        return Result.ok();
    }



    @ResponseBody
    @RequestMapping(value = "deleteAllocationOrder")
    public Result deleteAllocationOrder(HttpServletRequest request){
        String orderIds=request.getParameter("orderIds");
        String type=request.getParameter("type");
        allocationOrderService.deleteAllocationOrder(orderIds,type);
        return Result.ok();
    }

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

    /**
     * 审批 通过 一级审批
     */
    @ResponseBody
    @RequestMapping(value = "firstAudit")
    public Result<Void> firstAudit(String id,String content) {
        logger.info(" into firstAudit, id={}", id);
        allocationOrderService.firstAudit(id,content);
        return Result.ok();
    }

    /**
     * 审批 不通过
     */
    @ResponseBody
    @RequestMapping(value = "reject")
    public Result<Void> reject(String id,String taskId, String reason) {
        logger.info(" into reject, id={}, reason={}", id, reason);
        GuardUtils.notBlank(id, "id不能为空");
        GuardUtils.notBlank(reason, "reason不能为空");
        allocationOrderService.reject(id,taskId, reason);
        return Result.ok();
    }

}
