package com.engine.voting.cmd.VotingForm;

//import com.api.voting.service.VotingListService;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.voting.util.CheckVotingFormPermission;
import com.engine.voting.util.VotingDetach;
import com.engine.voting.util.VotingPageUidFactory;
import com.google.common.collect.Maps;

import weaver.conn.RecordSet;
import weaver.general.PageIdConst;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 后台 调查 - 网上调查设置 列表
 */
public class VotingFormTableCmd
        extends
        AbstractCommonCommand<Map<String, Object>> {

    public VotingFormTableCmd() {
    }

    public VotingFormTableCmd(Map<String, Object> params, User user) {
        this.params = params;
        this.user = user;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> apidatas = Maps.newHashMap();
        try {
            String userid = user.getUID() + "";
            String loginType = user.getLogintype();
            
            //用户是否有删除权限
            boolean canDelete = HrmUserVarify.checkUserRight("voting:delete", user); //调查删除权限
            boolean canmaint = HrmUserVarify.checkUserRight("Voting:Maint", user); //调查维护权限
            boolean canmaintview = canmaint;

            boolean cancreate = false;
            //boolean canapprove = false ;
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from votingmaintdetail where createrid=? or approverid=?", userid, userid);
            if (rs.next()) {
                cancreate = true;
            }
            if (canmaint) {
                cancreate = true;
            }
            
            boolean canCommit = false;
            if (canmaint) {
            	canCommit = true;
            }else{
                rs.executeQuery("select id from votingmaintdetail where approverid=?", userid);
                if (rs.next()) {
                	canCommit = true;
                }
            }
            

            //设置好搜索条件
            String backFields = " id,descr, subject,begindate,begintime,enddate,endtime,createrid,approverid,status,createdate ,createtime,istemplate,votingtype ";
            String fromSql = " voting ";
            String sqlWhere = "";
            if (canmaintview) {
                sqlWhere = " where 1=1 ";
            } else if (cancreate) {
                sqlWhere = " where (createrid=" + userid + " or approverid=" + userid + ") ";
            } else {
                sqlWhere = " where 1 != 1 "; //没有调查维护权限，且没有被设置调查授权则不展示数据
//                VotingListService votingListService = new VotingListService();
//                sqlWhere = " where id in(" + votingListService.getVotingIdByShare(user) + ") and status in (1,2) ";
            }
            sqlWhere += " and (istemplate <> '1' or istemplate is null)";

            if(!"1".equals(userid)){
                sqlWhere += " and createrid = "+ userid ;
            }

            //调查名称
            String subject = Util.null2String(params.get("subject")).replace("'", "''");
            if (!subject.equals("")) {
                sqlWhere += " and subject like '%" + subject + "%'";
            }
            //创建人
            String createrid = Util.null2String(params.get("createrid"));
            if (!createrid.equals("")) {
                sqlWhere += " and createrid in (" + createrid + ")";
            }
            //调查类型
            String votingtype = Util.null2String(params.get("votingtype"));
            if (!votingtype.equals("")) {
                sqlWhere += " and votingtype in (" + votingtype + ")";
            }
            //状态
            String status = Util.null2String(params.get("status"));
            if (!status.equals("")) {
                sqlWhere += " and status in (" + status + ")";
            }
//            //开始日期
//            String begindate = Util.null2String(params.get("begindate"));
//            if (!begindate.equals("")) {
//                sqlWhere += " and begindate >= '" + begindate + "'";
//            }
//            //截止日期
//            String enddate = Util.null2String(params.get("enddate"));
//            if (!enddate.equals("")) {
//                sqlWhere += " and enddate <= '" + enddate + "'";
//            }
            
            // 开始日期  截止日期
            String datetype = Util.null2String(params.get("datetype")); // 时间（全部:空;今天:1;本周:2;本月:3;本季:4;本年:5;指定日期范围:6;)
            String begindate = Util.null2String(params.get("begindate")); // 开始日期
            String enddate = Util.null2String(params.get("enddate")); // 截止日期
            if (!"0".equals(datetype) && !"".equals(datetype) && !"6".equals(datetype)) {
                sqlWhere += " and begindate >= '" + TimeUtil.getDateByOption(datetype + "", "0") + "'";
                sqlWhere += " and enddate <= '" + TimeUtil.getDateByOption(datetype + "", "") + "'";
            }
            if ("6".equals(datetype) && !"".equals(begindate)) {
                sqlWhere += " and begindate >= '" + begindate + "'";
            }
            if ("6".equals(datetype) && !"".equals(enddate)) {
                sqlWhere += " and enddate <= '" + enddate + "'";
            }

            boolean detach = VotingDetach.isDetach(); //是否开启知识-管理分权
            if (detach) {
                String subcompanyid = Util.null2String(params.get("subcompanyid"));
                if (!subcompanyid.isEmpty()) {
                    sqlWhere += " and subcompanyid=" + subcompanyid;
                } else if (user.getUID() != 1) { //系统管理默认分权所有分部，不做过滤
                    String suncompanyids = Util.null2String(VotingDetach.getSubcompanyids(user));
                    suncompanyids = suncompanyids.startsWith(",") ? suncompanyids.substring(1) : suncompanyids;
                    suncompanyids = suncompanyids.endsWith(",") ? suncompanyids.substring(0, suncompanyids.length() - 1) : suncompanyids;
                    if(suncompanyids.isEmpty()){
                    	sqlWhere += " and 1 <> 1 ";
                    }else {
                        sqlWhere += " and (" + Util.getSubINClause(suncompanyids, "subcompanyid", "in") + ")";
                    }
                }

                rs.executeQuery("select count(id) num from voting where subcompanyid is null or subcompanyid =0 or subcompanyid =''");
                if (rs.next()) {
                    if (rs.getInt("num") > 0) {
                        String defaultId = VotingDetach.getDefaultId();
                        if (Util.getIntValue(defaultId) > 0) {
                            rs.execute("update voting set subcompanyid=" + defaultId + " where subcompanyid is null or subcompanyid =0 or subcompanyid =''");
                        }
                    }
                }
            }

            //当前是 批量删除页还是批量批准页
            String viewType = Util.null2String(params.get("viewType"));
            //writeLog("viewType---:"+viewType);
            String checkboxpopedom = "";
            String checkboxpopedompara= "";
            String pageId = PageIdConst.Voting_VotingListTable;
            String pageUid = VotingPageUidFactory.getPageUid(pageId);
            if("batchApprove".equals(viewType)){ //批量批准
            	
                checkboxpopedompara = "column:status+" + canCommit+ "+column:votingtype";
                checkboxpopedom = "<checkboxpopedom id=\"checkbox\" popedompara=\""+checkboxpopedompara+"\" showmethod=\"com.engine.voting.biz.VotingTransMethod4E9.getVotingListCheckBoxRight\" />";
            }else{  //批量删除
            	
                checkboxpopedompara = "column:status+" + canDelete;
                checkboxpopedom = "<checkboxpopedom id=\"checkbox\" popedompara=\""+checkboxpopedompara+"\" showmethod=\"com.engine.voting.biz.VotingTransMethod4E9.getVotingListCheckBoxRightDel\" />";
            }

            String orderBy = "id";
            
            String operatepopedompara = "column:status+" + cancreate + "+" + canDelete + "+column:id" + "+" + user.getUID() + "+column:votingtype";
            String operateString = "";
					operateString = " <operates>";
					operateString +=" <popedom column=\"id\" transmethod=\"com.engine.voting.cmd.VotingForm.VotingFormTableCmd.getVotingFormOperate\"  otherpara=\""+operatepopedompara+"\" ></popedom> ";
					operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(93, user.getLanguage()) + "\"   index=\"0\"/>";
					operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(142, user.getLanguage()) + "\"   index=\"1\"/>"; //批准
					operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(725, user.getLanguage()) + "\"   index=\"2\"/>"; //提交
					operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(91, user.getLanguage()) + "\"   index=\"3\"/>";
				   	operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(33832, user.getLanguage()) + "\" index=\"4\"/>";   
					operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(382638, user.getLanguage())+ "\" index=\"5\"/>";// 参与范围
				   	operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(20043, user.getLanguage()) + "\" index=\"6\"/>";
					operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(500603, user.getLanguage()) + "\" index=\"7\"/>";// 复制调查
				   	operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(19468, user.getLanguage()) + "\" index=\"8\"/>"; //另存为模板
				   	operateString +="     <operate text=\"" + SystemEnv.getHtmlLabelName(83, user.getLanguage()) + "\" index=\"9\"/>"; //日志
					operateString +=" </operates>";
					

            String tableString = "";
              tableString="<table pageUid=\""+pageUid+"\" pageId=\""+pageId+"\" pagesize=\""+PageIdConst.getPageSize(pageId,user.getUID(), PageIdConst.VOTING)+"\" tabletype=\"checkbox\">";
              tableString += checkboxpopedom;
              tableString +="<sql backfields=\""+backFields+"\" sqlform=\""+Util.toHtmlForSplitPage(fromSql)+"\" sqlorderby=\""+orderBy+"\"  sqlprimarykey=\"id\" sqlsortway=\"Desc\" sqlwhere=\""+Util.toHtmlForSplitPage(sqlWhere)+"\" />";
              tableString +=  operateString;
              tableString += "<head>"+
                      "<col width=\"8%\"  text=\""+SystemEnv.getHtmlLabelName(15486,user.getLanguage())+"\" column=\"id\" orderkey=\"id\" />"+
                      "<col width=\"28%\" text=\""+SystemEnv.getHtmlLabelName(195,user.getLanguage())+"\" column=\"subject\" orderkey=\"subject\" />"+
                      "<col width=\"28%\" text=\""+SystemEnv.getHtmlLabelName(24111,user.getLanguage())+"\" column=\"votingtype\" orderkey=\"votingtype\" transmethod=\"com.engine.voting.cmd.VotingForm.VotingFormTableCmd.getVotingTypeName\" />"+ //调查类型
                      "<col width=\"10%\"  text=\""+SystemEnv.getHtmlLabelName(882,user.getLanguage())+"\" column=\"createrid\" orderkey=\"createrid\" transmethod=\"weaver.hrm.resource.ResourceComInfo.getMutiResourceLink\" />"+
                      "<col width=\"20%\"  text=\""+SystemEnv.getHtmlLabelName(740,user.getLanguage())+"\" column=\"begindate\" orderkey=\"begindate\" otherpara=\"column:begintime\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getDateAndTime\"  />"+
                      "<col width=\"20%\"  text=\""+SystemEnv.getHtmlLabelName(741,user.getLanguage())+"\" column=\"enddate\" orderkey=\"enddate\" otherpara=\"column:endtime\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getDateAndTime\"  />"+
                      "<col width=\"12%\"  text=\""+SystemEnv.getHtmlLabelName(602,user.getLanguage())+"\" column=\"status\"  orderkey=\"status\" otherpara=\""+user.getLanguage()+"\" transmethod=\"weaver.voting.VotingManager.getStatus\"/>"+
                    "</head>"+
                "</table>";
            
            String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom());
            Util_TableMap.setVal(sessionkey, tableString);
            apidatas.put("sessionkey", sessionkey);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            return apidatas;
        }
        apidatas.put("api_status", true);
        return apidatas;
    }

    /**
     * 行  右侧下拉操作按钮权限
     * @param id
     * @param params
     * @return
     */
    public List<String> getVotingFormOperate(String id, String params) {
        List<String> result = new ArrayList<String>();

        List ps = Util.TokenizerString(params, "+");
        String votingstatus = ps.get(0) + "";
        String canCreate = ps.get(1) + "";
        String canDelete = ps.get(2) + "";
        String votingid = ps.get(3) + "";
        String userid = ps.get(4) + "";
        String votingtype = ps.get(5) + "";

        String canEdit = "false";
        if ("0".equals(votingstatus) && "true".equals(canCreate)) {
            canEdit = "true";
        }

        String canapprove = "false";
        User user = User.getUser(Util.getIntValue(userid), 0);
        if ("0".equals(votingstatus) && CheckVotingFormPermission.checkCanApprove(user, Util.getIntValue(votingid))) {
            canapprove = "true";
        }
        String tijiao = "false";
        if("true".equals(canapprove) && Util.getIntValue(votingtype) > 0) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select approver from voting_type where id = ?", votingtype);
            if(rs.next() && rs.getInt("approver") > 0) {
                tijiao = "true";
                canapprove = "false";
            }
        }

        //1、有调查删除权限 voting:delete ，2、非进行中状态 （创建 和 结束状态） 才可以删除。
        canDelete = "true".equals(canDelete) && (!"1".equals(votingstatus)&& !"3".equals(votingstatus)) ? "true" : "false";

        result.add(canEdit);
        result.add(canapprove);
        result.add(tijiao);
        result.add(canDelete);
        result.add(canCreate);
        result.add(canCreate);
        result.add(canCreate);
        result.add(canCreate);
        result.add(canCreate);
        result.add(canCreate); //日志

        return result;
    }

    /**
     * 批量批准时，列表的条目选择框状态
     * @param params
     * @return
     */
    public String getVotingListCheckBoxRight(String params) {
        List ps = Util.TokenizerString(params, "+");

        String status = ps.get(0) + "";
        String canCommit = ps.get(1) + "";
        String votingtype = ps.get(2) + "";
        
        String realCommit = "false";

        if ("0".equals(status) && "true".equals(canCommit)) { //创建状态
        	realCommit = "true";
        }
        if("true".equals(realCommit) && Util.getIntValue(votingtype) > 0){
        	RecordSet rs = new RecordSet();
            rs.executeQuery("select approver from voting_type where id = ?", votingtype);
            if(rs.next() && rs.getInt("approver") > 0) {
            	realCommit = "false";
            }
        }
        return realCommit;
    }
    
    /**
     * 根据调查类型id获取调查类型名称
     * @param votingtypeId
     * @return
     */
    public String getVotingTypeName(String votingtypeId) {
        String typename = "";
        if(Util.getIntValue(votingtypeId) > 0) {
            RecordSet rs = new RecordSet();
            rs.executeQuery("select typename from voting_type where id = ?", votingtypeId);
            if(rs.next()) {
                typename = rs.getString("typename");
            }
        }
        return typename;
    }
    
    @Override
    public BizLogContext getLogContext() {
        return null;
    }
}
