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

import com.google.common.collect.Maps;
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.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.dao.InventoryOrderDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyInventoryOrder;
import com.sifang.modules.supply.warehouse.request.InventoryOrderReq;
import com.sifang.modules.supply.warehouse.service.InventoryOrderService;
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 net.sf.json.JSONObject;
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 org.springframework.web.multipart.MultipartFile;

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

@Controller
@RequestMapping(value = "${adminPath}/inventory")
public class InventoryOrderController extends BaseExceptionController {
    Logger logger = LoggerFactory.getLogger(InventoryOrderController.class);

    @Autowired
    private InventoryOrderService inventoryOrderService;
    @Autowired
    private InventoryOrderDao inventoryOrderDao;
    @Autowired
    private CrmSupplyWarehouseSettingService warehouseService;

    @Autowired
    private ProcessFlowableService flowableService;

    /**
     * 盘点单列表页面
     */
    @RequestMapping(value = "toInventoryPage")
    public String toInventoryPage(Model model) {
        User user = UserUtils.getUser();

        String type = "";// 供应链
        String traderId="";
        logger.info(" into toInventoryPage, userType={}", user.getUserType());
        if (User.USER_TYPE_GYS.equals(user.getUserType())) {
            type = "3";// 供应商
        } else if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            type = "2";// 代理商
            traderId = user.getTopTraderId();
        }
        model.addAttribute("type", type);
        model.addAttribute("formId", FormUtils.INVEBNTORY_ORDER_APPLICATION);
        model.addAttribute("warehouseList", MaterialUtils.findMaterialWarehouse(type,traderId));
        model.addAttribute("userType", user.getUserType());
        model.addAttribute("role", CrmUtils.getPlatEmployeRole(user.getId()));
        model.addAttribute("userId",user.getId());
        return "modules/supply/warehouse/inventoryPage";
    }

    /**
     * 盘点单列表数据
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForInventoryOrderData")
    public Object ajaxForInventoryOrderData(HttpServletRequest request) {
        LayuiPage page = new LayuiPage(request);
        Map<String, String> map = getParams(request);
        Ascription ascription = CrmUtils.getAscription();
        map.put("inventoryObjectId", ascription.getAscriptionId());
        inventoryOrderService.getInventoryOrderPage(page, map);
        return page.renderJson();
    }

    /**
     * 编辑盘点单页面
     */
    @RequestMapping(value = "toInventoryOrderDetailForm")
    public String toInventoryOrderDetailForm(HttpServletRequest request, Model model) {
        String id = request.getParameter("id");
        String mode = request.getParameter("mode");
        CrmSupplyInventoryOrder order = inventoryOrderDao.get(id);
        List<Record> details = inventoryOrderService.getDetails(id);
        List<Record> warehouseList = warehouseService.findByType(order.getInventoryType());
        model.addAttribute("order", order);
        model.addAttribute("details", details);
        model.addAttribute("warehouseList", warehouseList);
        model.addAttribute("mode", mode);
        model.addAttribute("msgs", inventoryOrderService.listMsg(id));
        model.addAttribute("user", UserUtils.getUser());
        if("view".equals(mode)){
            flowableService.readApplication(order.getProcessInstanceId(),FormUtils.INVEBNTORY_ORDER_APPLICATION,id,UserUtils.getUser());
        }
        return "modules/supply/warehouse/inventoryOrderDetail";
    }

    /**
     * 新增盘点单页面
     */
    @RequestMapping(value = "toAddInventoryOrderForm")
    public String toAddInventoryOrderForm() {
        return "modules/supply/warehouse/addInventoryOrder";
    }

    /**
     * 查看物料清单页面
     */
    @RequestMapping(value = "toMaterialListForm")
    public String toMaterialListForm(String id, Model model) {
        CrmSupplyInventoryOrder order = inventoryOrderDao.get(id);
        List<Record> warehouseList = warehouseService.findByType(order.getInventoryType());
        List<Record> details = inventoryOrderService.getDetails(id);
        model.addAttribute("order", order);
        model.addAttribute("warehouseList", warehouseList);
        model.addAttribute("details", details);
        return "modules/supply/warehouse/materialListForm";
    }

    /**
     * 保存盘点单
     */
    @ResponseBody
    @RequestMapping(value = "saveInventOrder")
    public Result<Void> saveInventOrder(@Valid @RequestBody InventoryOrderReq req, BindingResult bindingResult) {
        logger.info(" into saveInventOrder, req={}", req);
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        inventoryOrderService.saveInventoryOrder(req);
        return Result.ok();
    }

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

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

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping(value = "deleteOrder")
    public Result<Void> deleteOrder(String ids) {
        logger.info(" into deleteOrder, ids={}", ids);
        inventoryOrderService.deleteOrder(ids);
        return Result.ok();
    }


    /**
     * 导入物料页面
     */
    @RequestMapping(value = "toImportMaterialForm")
    public String toImportMaterialForm(Model model, HttpServletRequest request) {
        String warehouseId = request.getParameter("warehouseId");
        model.addAttribute("warehouseId", warehouseId);
        return "modules/supply/bom/importBom";
    }

    /**
     * 校验 excel
     */
    @ResponseBody
    @RequestMapping(value = "checkImportExcel")
    public Object checkImportExcel(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = inventoryOrderService.checkImportExcel(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 导入 excel数据
     */
    @ResponseBody
    @RequestMapping(value = "importInventoryData")
    public JSONObject importInventoryData(MultipartFile file, String warehouseId) throws IOException {
        logger.info("into importBomData,warehouseId={}", warehouseId);
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        params.put("warehouseId", warehouseId);
        Map<String, Object> retMap = inventoryOrderService.importInventoryData(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 初始化库存
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "initiMethod")
    public Result<Void> initiMethod(String id,String warehouse_id) {
        logger.info(" into initiMethod, id={}", id);
        logger.info(" into initiMethod, warehouse_id={}", warehouse_id);
        inventoryOrderService.initiMethod(id,warehouse_id);
        return Result.ok();

    }



}
