package cn.yw.machinemanage.action;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.base.excel.ExcelCol;
import cn.base.excel.ExportEngine;
import cn.base.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.base.aspect.OperateType;
import cn.base.bean.BaseAction;
import cn.bsystem.ptuserrole.model.PtyhBean;
import cn.yw.machinemanage.service.YwmachineinfoService;

@SuppressWarnings({"all"})
@Component("ywmachineinfoAction")
public class YwmachineinfoAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private static Logger iLog = Logger.getLogger(YwmachineinfoAction.class);

	@Autowired
	private YwmachineinfoService service;
	/**
	 * 分页
	 */

	@OperateType(value = LogConstants.LOG_QUERY ,info ="listYwmachineinfoByPage")
	public void listYwmachineinfoByPage(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			int page = Integer.parseInt(Struts2Utils.getParameter("page"));
			int rows = Integer.parseInt(Struts2Utils.getParameter("rows"));
			int start = ( (page == 0 ?  1 : page ) - 1) * rows ;
			map.put("start",start );
			map.put("limit",rows );
			Struts2Utils.renderJson(this.service.listYwmachineinfoByPage(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-listYwmachineinfoByPage-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}


	/**
	 * 查询总数
	 */

	@OperateType(value = LogConstants.LOG_QUERY ,info ="count_Ywmachineinfo")
	public void count_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.count_Ywmachineinfo(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-count_Ywmachineinfo-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}


	/**
	 * 查询 Ywmachineinfo
	 */

	@OperateType(value = LogConstants.LOG_GET ,info ="query_Ywmachineinfo")
	public void query_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.query_Ywmachineinfo(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-query_Ywmachineinfo-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}


	/**
	 * 查询 一条Ywmachineinfo
	 */

	@OperateType(value = LogConstants.LOG_GET ,info ="get_Ywmachineinfo")
	public void get_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.get_Ywmachineinfo(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoActionquery_Ywmachineinfo-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}


	/**
	 * 删除
	 */

	@OperateType(value = LogConstants.LOG_DELETE ,info ="deleteYwmachineinfo")
	public void delete_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(!CommUtils.isEmpty(map)){
				int result = service.delete_Ywmachineinfo(map);
				Struts2Utils.renderJson(Constants.SUCCESS);
			}else{
				 throw new Exception("请正确的选择删除记录!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-delete_Ywmachineinfo-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}


	/**
	 * 插入
	 */

	@OperateType(value = LogConstants.LOG_ADD ,info ="insert_Ywmachineinfo")
	public void insert_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(StringUtil.checkEmpty(map.get("machineid"))){
				map.put("machineid",StringUtil.getUUID());
			}
			String username = ((PtyhBean)Struts2Utils.getSession().getAttribute("userInfo")).getYhbh();
			String time = DateUtil.getDateTimeStr(new Date());
			map.put("createaccount", username);
			map.put("createtime", time);
			map.put("modifyaccount", username);
			map.put("modifytime", time);
			service.insert_Ywmachineinfo(map);
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-insert_Ywmachineinfo()-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}


	/**
	 * 修改
	 */

	@OperateType(value = LogConstants.LOG_UPDATE ,info ="update_Ywmachineinfo")
	public void update_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(!StringUtil.checkEmpty(map.get("checkparam"))){
				Map sMap = new HashMap();
				sMap.put("tableparam", map.get("checkparam"));
				List ls = service.query_Ywmachineinfo(sMap);
				if(!StringUtil.checkEmpty(ls)||ls.size()>0){
					Struts2Utils.renderJson(Constants.SAME);
				}else{
					int result = service.update_Ywmachineinfo(map);
					Struts2Utils.renderJson(Constants.SUCCESS);
				}
			}else{
				int result = service.update_Ywmachineinfo(map);
				Struts2Utils.renderJson(Constants.SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-update_Ywmachineinfo-error: " +e);
			Struts2Utils.renderJson(null);
		}
	}

	/**
	 * 修改备注
	 */

	@OperateType(value = LogConstants.LOG_UPDATE ,info ="update_Ywmachineinfo")
	public void update_YwmachineinfoRemarks(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			if(RHUtil.isNotEmpty(map.get("remarks"))&& map.get("remarks").toString().contains("survey")){
				map.put("repairstate",900);
				map.put("currentstate",1);
				this.service.update_YwmachinecurrentstateRepairstate(map);
			}
			int result = service.update_YwmachineinfoRemarks(map);
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-update_Ywmachineinfo-error: " +e);
			Struts2Utils.renderJson(null);
		}
	}


	// 更新
	@OperateType(value = LogConstants.LOG_UPDATE ,info ="edit_Ywmachineinfo")
	public void edit_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String username = ((PtyhBean)Struts2Utils.getSession().getAttribute("userInfo")).getYhbh();
			String time = DateUtil.getDateTimeStr(new Date());
			map.put("modifyaccount", username);
			map.put("modifytime", time);
			String ids = (String) map.get("ids");
			if(RHUtil.isNotEmpty(ids)) {
				String[] keys = ids.split(",");
				map.put("keys", keys);
			}
			int result = service.edit_Ywmachineinfo(map);
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-edit_Ywmachineinfo-error: " +e);
			Struts2Utils.renderJson(null);
		}
	}

	/**
	 * 批量删除
	 */

	@OperateType(value = LogConstants.LOG_DELETE ,info ="batch_delete_Ywmachineinfo")
	public void batch_delete_Ywmachineinfo(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			String keys = map.get("keyword").toString();
			if(RHUtil.isNotEmpty(keys)) {
				String[] ids = keys.split(",");
				map.put("ids", ids);
			}
			int result = service.batch_delete_Ywmachineinfo(map);
			Struts2Utils.renderJson(Constants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-batch_delete_Ywmachineinfo-error:" +e);
			Struts2Utils.renderJson(null);
		}
	}

	@OperateType(value = LogConstants.LOG_EXPORT ,info ="exp_Ywmachineinfo")
	public void exp_Ywmachineinfo(){
		try {
			Map map = Struts2Utils.getRequestParameterMap();
			map.put("start",0 );
			map.put("limit",5000);
			List<Map> sList = service.query_ALLYwmachineinfo(map);
			List<HashMap> expList = new ArrayList<HashMap>();
			for(Map m : sList){
				Map exportMap = new HashMap();
				exportMap.put("yhzh", m.get("yhzh"));
				expList.add((HashMap) exportMap);
			}
			int excelNum = 2;
			ExcelCol[] cells = new ExcelCol[excelNum];
			String[] zdbm = {"yhzh", "yhmc",};
			String[] zdmc = {"用户账号", "用户名称"};
			for(int i=0;i<excelNum;i++){
				cells[i] = new ExcelCol();
				cells[i].setColKey(zdbm[i]);
				cells[i].setColName(zdmc[i]);
			}

			SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");
        	String dateTime=formart.format(new Date());
			Map params = new HashMap();
			params.put("fileName", "运维服务器信息表-"+dateTime);
			params.put("sheetName", "运维服务器信息表");
			params.put("header", "运维服务器信息表");
			new ExportEngine().exportCommData(params, cells, (ArrayList)map.get("rows"), Struts2Utils.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction-exoprtExcel-error:" +e);

		}
	}

	@OperateType(value = LogConstants.LOG_IMPORT ,info ="imp_Ywmachineinfo")
	public void imp_Ywmachineinfo(String excelFile,Object user) {
        try {
            MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();
            String result = "0";
            List<Map> list = new ArrayList<>();
            List<List<Object>> listob = null;
            wrapper.getParameter("filename");
            File file = wrapper.getFiles("file")[0];
            if (null == file) {
                Struts2Utils.renderJson("文件不存在");
                iLog.error("YwmachineinfoAction-imp_Ywmachineinfo-error:文件不存在");
            }
            String directory = "/upload";
            String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);
            //生成上传的文件对象
            File target = new File(targetDirectory, wrapper.getParameter("filename"));
            //如果文件已经存在，则删除原有文件
            if (target.exists()) {
                target.delete();
            }
            FileUtils.copyFile(file, target);           //复制file对象，实现上传
            FileInputStream in = new FileInputStream(target);
            listob = new ImportExcelUtil().getBankListByExcel(in, target.getName());
            in.close();
            if (listob.size() > 0) {
                List<Object> columns = listob.get(0);
                if (columns.size() >= 13) { //判断模板列数是否正确
                    for (int i = 0; i < listob.size(); i++) {
                        Map vo = new HashMap();
                        vo.put("machineid", StringUtil.getUUID());
                        vo.put("machinenum", listob.get(i).get(0).toString());
                        vo.put("machinename", listob.get(i).get(1).toString());
                        vo.put("machinetype", listob.get(i).get(2).toString());
                        vo.put("machinebrand", listob.get(i).get(3).toString());
                        vo.put("machinebrandtype", listob.get(i).get(4).toString());
                        vo.put("machineos", listob.get(i).get(5).toString());
                        vo.put("machineostype", listob.get(i).get(6).toString());
                        vo.put("machineip", listob.get(i).get(7).toString());
                        vo.put("networkport", listob.get(i).get(8).toString());
                        vo.put("machineloginuser", listob.get(i).get(9).toString());
                        vo.put("machineloginpwd", listob.get(i).get(10).toString());
                        vo.put("machineposition", listob.get(i).get(11).toString());
                        vo.put("machineareanum", listob.get(i).get(12).toString());
                        vo.put("machinedescribe", listob.get(i).get(13).toString());
                        vo.put("machineruninterval", listob.get(i).get(14).toString());
                        vo.put("machinestatus", listob.get(i).get(15).toString());
                        vo.put("machinestatusuptime", listob.get(i).get(16).toString());
                        vo.put("machinefaulttype", listob.get(i).get(17).toString());
                        vo.put("detectionswitch", listob.get(i).get(18).toString());
                        vo.put("detectionstarttime", listob.get(i).get(19).toString());
                        vo.put("createaccount", listob.get(i).get(20).toString());
                        vo.put("createtime", listob.get(i).get(21).toString());
                        vo.put("modifyaccount", listob.get(i).get(22).toString());
                        vo.put("modifytime", listob.get(i).get(23).toString());
                        vo.put("remarks", listob.get(i).get(24).toString());
                        list.add(vo);
                    }
                    result = this.service.batch_insert_Ywmachineinfo(list);
                }
                if (result.equals("1")) {
                    Struts2Utils.renderJson("导入成功" + list.size() + "条数据");
                } else {
                    Struts2Utils.renderJson("导入失败");
                }
            } else {
                Struts2Utils.renderJson("模板错误");
            }

        } catch (Exception e) {
            Struts2Utils.renderJson("模板错误");
            iLog.error("YwmachineinfoAction-imp_Ywmachineinfo-error:" + e);
        }
    }


	// 首页    运维数据看板 下数字统计
	public void count_HomepageDeviceCount(){
		Map map = Struts2Utils.getRequestParameterMap();
		try {
			Struts2Utils.renderJson(this.service.count_HomepageDeviceCount(map));
		} catch (Exception e) {
			e.printStackTrace();
			iLog.error("YwmachineinfoAction - count_HomepageDeviceCount - error:" +e);
			Struts2Utils.renderJson(null);
		}
	}

	private class ExcelReader {
	}
}
