package com.jeeplus.modules.sg.managementcenter.reserveManagement.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.filing.basicInformation.entity.BasicInformation;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.entity.Standard;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.service.StandardService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 物料规范 Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/managementCenter/standard")
public class StandardController extends BaseController {

    @Autowired
    private StandardService standardService;

    @ModelAttribute
    public Standard get(@RequestParam(required = false) String id) {
        Standard entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = standardService.get(id);
        }
        if (entity == null) {
            entity = new Standard();
        }
        return entity;
    }

    /**
     * 物料规范信息列表页面
     * @param standard
     * @param model
     * @return
     */
    @RequiresPermissions("sg:reserve:standard:list")
    @RequestMapping(value = "list")
    public String skipList(Standard standard, Model model) {
        model.addAttribute("standard", standard);
        return "modules/sg/managementcenter/reserveManagement/standardList";
    }

    /**
     * 物料规范信息数据列表
     * @param standard
     * @param request
     * @param response
     * @param model
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:standard:list")
    @RequestMapping(value = "data")
    public Map<String, Object> basicData(Standard standard, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Standard> page = standardService.findPage(new Page<Standard>(request, response), standard);
        return getBootstrapData(page);
    }

    @ResponseBody
    @RequiresPermissions("sg:reserve:standard:list")
    @RequestMapping(value = "dataDetail")
    public Map<String, Object> dataDetail(Standard standard, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Standard> page = standardService.findChildPage(new Page<Standard>(request, response), standard);
        return getBootstrapData(page);
    }

    /**
     * 专职人员增加，编辑表单页面
     * @param standard
     * @param model
     * @return
     */
    @RequiresPermissions(value={"sg:reserve:standard:add","sg:reserve:standard:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(Standard standard, Model model) {
        model.addAttribute("standard", standard);
        return "modules/sg/managementcenter/reserveManagement/standardForm";
    }

    /**
     * 保存表单
     * @param standard
     * @return
     */
    @ResponseBody
    @RequiresPermissions(value={"sg:reserve:standard:add","sg:reserve:standard:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(Standard standard){
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(standard);
        if (StringUtils.isNotBlank(errMsg)){
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        //新增或编辑表单保存
        //通过储备项目编号
        standardService.saveChild(standard);//保存
        j.setSuccess(true);
        j.setMsg("保存物料规范信息成功");
        return j;
    }


    /**
     *
     */
    @ResponseBody
    @RequiresPermissions(value={"sg:reserve:standard:del"},logical=Logical.OR)
    @RequestMapping(value = "deleteAll")
    public AjaxJson delete(String ids){
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
        for(String id : idArray){
            standardService.delete(standardService.get(id));
        }
        j.setMsg("删除物料规范信息成功");
        return j;
    }

   

    /**
     * 经理导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:standard:import")
    @RequestMapping(value = "import")
    public AjaxJson jlImportBasic(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            StringBuffer stringBuffer = new StringBuffer();
            List<Standard> list = ei.getDataList(Standard.class);
            List<Standard> insertList = new ArrayList<>();
            for (Standard s :
                    list) {
                if (!"".equals(s.getMaterialCode()) && !"".equals(s.getMaterialDescription())) {
                    insertList.add(s);
                }
            }
            if (insertList.size() > 0) {
                standardService.deleteChildList(insertList);
                standardService.insertChildList(insertList);
            }
            j.setSuccess(true);
            j.setMsg("已成功导入" + stringBuffer);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入物料规范信息失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    //导出excel
    @ResponseBody
    @RequiresPermissions("sg:reserve:standard:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Standard standard, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "物料规范信息"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Standard> page = standardService.findChildPage(new Page<Standard>(request, response, -1), standard);
            new ExportExcel("物料规范信息", Standard.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出物料规范信息记录失败！失败信息："+e.getMessage());
        }
        return j;
    }

   
    /**
     * 下载导入模板
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:standard:import")
    @RequestMapping(value = "template")
    public AjaxJson importTemplate(HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "物料规范信息详细导入模板.xlsx";
            List<BasicInformation> list = Lists.newArrayList();
            new ExportExcel("物料规范详细信息表", Standard.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
        }
        return j;
    }

    

}
