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.flowpath.entity.ExamineInfo;
import com.sifang.modules.flowpath.service.ExamineInfoService;
import com.sifang.modules.flowpath.vo.UserApplyVo;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.entity.CrmFittingStockUpApply;
import com.sifang.modules.supply.warehouse.request.AddFittingStockReq;
import com.sifang.modules.supply.warehouse.request.MateFittingVo;
import com.sifang.modules.supply.warehouse.service.CrmFittingStockUpApplyService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
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.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.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 备货申请
 */
@Controller
@RequestMapping(value = "${adminPath}/fittingStockUp")
public class CrmFittingStockUpApplyController extends BaseExceptionController {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private CrmFittingStockUpApplyService crmFittingStockUpApplyService;

    @Autowired
    private ExamineInfoService examineInfoService;

    @Autowired
    private ProcessFlowableService processFlowableService;

    //列表数据
    @RequestMapping(value = "fittingStockUpPage")
    public String fittingStockUpPage(Model model) {
        model.addAttribute("formId", FormUtils.STOCK_UP_APPLY);
        User user = UserUtils.getUser();
        model.addAttribute("userId",user.getId());
        return "modules/supply/warehouse/fittingStockUp/fittingStockUpPage";
    }

    //列表数据
    @ResponseBody
    @RequestMapping(value = "fittingStockUpList")
    public Object fittingStockUpList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        crmFittingStockUpApplyService.fittingStockUpList(page,map);
        return page.renderJson();
    }

    @RequestMapping(value = "addFittingStockUpPage")
    public String addFittingStockUpPage(Model model,HttpServletRequest request){
        String id=request.getParameter("id");
        model.addAttribute("id",id);
        String createTime= DateUtils.getDateTime();
        model.addAttribute("createTime",createTime);
        if(StringUtil.isNotBlank(id)){
            CrmFittingStockUpApply crmFittingStockUpApply= crmFittingStockUpApplyService.getFittingApply(id);
            model.addAttribute("apply",crmFittingStockUpApply);
            List<Record> details=crmFittingStockUpApplyService.getFittingApplyDetail(id);
            model.addAttribute("details",details);
            model.addAttribute("createTime",DateUtils.formatDateTime(crmFittingStockUpApply.getCreateTime()));
        }
        List<Record> typeList = MaterialUtils.findMaterialTypeBz1();
        model.addAttribute("typeList",typeList);//非组件的标准物料
        Record typeZ = MaterialUtils.findMaterialTypeBz2();
        model.addAttribute("typeZ",typeZ);//仅组件的标准物料
        Ascription ascription = CrmUtils.getAscription();
        List<Record> list = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
        model.addAttribute("wares", list);
        User user = UserUtils.getUser();
        model.addAttribute("user",user);
        return "modules/supply/warehouse/fittingStockUp/addFittingStockUpPage";
    }

    //保存备货申请
    @ResponseBody
    @RequestMapping(value = "saveFittingStockApply")
    public Result saveFittingStockApply(@Valid @RequestBody AddFittingStockReq req){
        crmFittingStockUpApplyService.saveFittingStockApply(req);
        return Result.ok();
    }

    //详情、审批页面
    @RequestMapping(value = "fittingStockUpDetailPage")
    public String fittingStockUpDetailPage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        String from=request.getParameter("from"); //from = audit 那么就是审批操作  否则就是查看
        model.addAttribute("from",from);
        Record crmFittingStockUpApply= crmFittingStockUpApplyService.stockUpDetail(id);
        model.addAttribute("apply",crmFittingStockUpApply);
        List<ExamineInfo> infos=examineInfoService.getByApplyId(id,FormUtils.STOCK_UP_APPLY);
        model.addAttribute("infos",infos);
        List<Record> details=crmFittingStockUpApplyService.getFittingApplyDetail(id);
        model.addAttribute("details",details);
        User user=UserUtils.getUser();
        model.addAttribute("user",user);
        if(!"audit".equals(from)){
            processFlowableService.readApplication(crmFittingStockUpApply.getStr("process_instance_id"),FormUtils.STOCK_UP_APPLY,id,user);
        }
        return "modules/supply/warehouse/fittingStockUp/fittingStockUpDetailPage";
    }

    //审核
    @ResponseBody
    @RequestMapping(value = "examineFittingStockUpApplyApprove")
    public Result examineFittingStockUpApplyApprove(UserApplyVo userApplyVo){
        try{
            crmFittingStockUpApplyService.examineFittingStockUpApplyApprove(userApplyVo.getId(),userApplyVo.getTaskId(),userApplyVo.getContent());
            return Result.ok();
        }catch (RuntimeException c){
            logger.info(">>>>>>>>>>>>>>examineFittingStockUpApplyApprove c:{}",c);
            return Result.fail(c.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>examineFittingStockUpApplyApprove e:{}",e);
            return Result.fail("审核失败！"+e.getMessage());
        }
    }

    //审核驳回
    @ResponseBody
    @RequestMapping(value = "rejectFittingStockUpApplyTask")
    public Result rejectFittingStockUpApplyTask(@Valid UserApplyVo userApplyVo){
        try{
            crmFittingStockUpApplyService.rejectFittingStockUpApplyTask(userApplyVo.getId(),userApplyVo.getTaskId(),userApplyVo.getContent());
            return Result.ok();
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>rejectFittingStockUpApplyTask e:{}",e);
            return Result.fail("审核失败！"+e.getMessage());
        }
    }

    //匹配页面
    @RequestMapping(value = "mateFitting")
    public String mateFitting(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        model.addAttribute("id",id);
        Record crmFittingStockUpApply= crmFittingStockUpApplyService.stockUpDetail(id);
        model.addAttribute("apply",crmFittingStockUpApply);
        List<Record> details=crmFittingStockUpApplyService.getFittingApplyDetail(id);
        model.addAttribute("details",details);
        return "modules/supply/warehouse/fittingStockUp/fittingStockUpMateFittingPage";
    }

    //保存匹配信息
    @ResponseBody
    @RequestMapping(value = "tempFittingStockMateFitting")
    public Result tempFittingStockMateFitting(@Valid @RequestBody MateFittingVo mateFittingVo){
        crmFittingStockUpApplyService.tempFittingStockMateFitting(mateFittingVo);
        return Result.ok();
    }

    /**
     * 导入备货申请页面
     */
    @RequestMapping(value = "toImportFittingStockPage")
    public String toImportFittingStockPage(Model model, HttpServletRequest request) {
        String warehouseId = request.getParameter("warehouseId");
        model.addAttribute("warehouseId", warehouseId);
        return "modules/supply/warehouse/fittingStockUp/importFittingStockPage";
    }

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

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


}
