package com.engine.voting.cmd.VotingList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.PageIdConst;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.setting.HrmUserSettingComInfo;

import com.alibaba.fastjson.JSON;
import com.api.voting.util.ConditionUtil;
import com.api.voting.util.VotingTableType;
import com.cloudstore.dev.api.bean.SplitMobileDataBean;
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.VotingPageUidFactory;
import com.engine.voting.biz.VotingCreateMobileTemplate;
import com.engine.voting.biz.VotingGetSqlWhere;
import com.engine.voting.biz.VotingGetVotingIdByShare;

/**
 * 根据tabinfo来获取前台参与调查页面的未参与调查列表和已参与调查列表
 * 
 * @author ZH
 *
 */
public class VotingGetMyVotingCmd extends AbstractCommonCommand<Map<String, Object>> {
    protected int tabInfo;
    private static final String JSON_CONFIG = "[ \n" + "]";

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

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        VotingGetSqlWhere votinggetsqlwhere = new VotingGetSqlWhere();
        VotingCreateMobileTemplate votingcreatemobiletemplate = new VotingCreateMobileTemplate();
        VotingGetVotingIdByShare votinggetvotingidbyshare = new VotingGetVotingIdByShare();
        Map<String, Object> apidatas = new HashMap<String, Object>();
        params = params == null ? new HashMap<String, Object>() : params;
        String backFields = " id,descr, subject,begindate,begintime,enddate,endtime,createrid,approverid,status,createdate ,createtime,istemplate,id countid,id picid ";
        String fromSql = " voting ";

        String sqlWhere = "";
        VotingTableType tableType;

        String pageId = "";
        if (tabInfo == 2) {// 我发起的
            tableType = VotingTableType.VOTING_ME_CREATE;
            pageId = "VOTING_ME_CREATE";
            sqlWhere = " where (istemplate <> '1' or istemplate is null) and status in (1,2) and createrid ="
                    + user.getUID();
            sqlWhere += votinggetsqlwhere.getSqlWhere(params);
        } else if (tabInfo == 3) {// 与我有关的
            tableType = VotingTableType.VOTING_ME_RELATED;
            pageId = "VOTING_ME_RELATED";
            sqlWhere = " where (istemplate <> '1' or istemplate is null) and status in(1,2) and (id in("
                    + votinggetvotingidbyshare.getJoinVotingIdByShare(user) + ") or createrid =" + user.getUID() + ")";

            String votingCurrentDate = TimeUtil.getCurrentDateString();
            String votingCurrentTime = TimeUtil.getOnlyCurrentTimeString();

            sqlWhere += " and (beginDate<'" + votingCurrentDate + "' or (beginDate='" + votingCurrentDate
                    + "' and (beginTime is null or beginTime='' or beginTime<='" + votingCurrentTime + "')))";

            sqlWhere += votinggetsqlwhere.getSqlWhere(params);
        } else {
            sqlWhere = " where id in(" + votinggetvotingidbyshare.getJoinVotingIdByShare(user) + ")";

            HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo();
            String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID() + "");
            String account_type = user.getAccount_type();
            String belongtoids = user.getBelongtoids();
            if (belongtoshow.equals("1") && account_type.equals("0") && !belongtoids.equals("")) {
                belongtoids += "," + user.getUID();
            } else {
                belongtoids = user.getUID() + "";
            }

            sqlWhere += " and (istemplate <> '1' or istemplate is null)";
            sqlWhere += votinggetsqlwhere.getSqlWhere(params);

            if (tabInfo == ConditionUtil.TAB_VOTING_DO) { // 已参与
                tableType = VotingTableType.VOTING_HAS_DOWN;
                pageId = "VOTING_HAS_DOWN";
                sqlWhere += " and status in(1,2) ";// 已参与只可能是进行中，已结束
                sqlWhere += " and exists";
                sqlWhere += " (select 1 from VotingRemark where votingid=voting.id and resourceid"
                        + (belongtoids.contains(",") ? (" in (" + belongtoids + ")") : ("=" + belongtoids)) + ")";
            } else {// 未参与
                tableType = VotingTableType.VOTING_UN_DO;
                pageId = "VOTING_UN_DO";
                String votingCurrentDate = TimeUtil.getCurrentDateString();
                String votingCurrentTime = TimeUtil.getOnlyCurrentTimeString();
                sqlWhere += " and status=1 ";
                sqlWhere += " and (beginDate<'" + votingCurrentDate + "' or (beginDate='" + votingCurrentDate
                        + "' and (beginTime is null or beginTime='' or beginTime<='" + votingCurrentTime + "')))";
                sqlWhere += " and (";

                List<String> belongtoidsList = Util.TokenizerString(belongtoids, ",");
                for (int k = 0; k < belongtoidsList.size(); k++) {// 次账号存在于参与人范围，又不存在提交remark表
                    if (k == 0) {
                        sqlWhere += " (exists(select 1 from VotingShareDetail where votingid=voting.id and resourceid="
                                + belongtoidsList.get(k) + ")";
                        sqlWhere += " and not exists(select 1 from VotingRemark where votingid=voting.id and resourceid="
                                + belongtoidsList.get(k) + "))";
                    } else {
                        sqlWhere += " or (exists(select 1 from VotingShareDetail where votingid=voting.id and resourceid="
                                + belongtoidsList.get(k) + ")";
                        sqlWhere += " and not exists(select 1 from VotingRemark where votingid=voting.id and resourceid="
                                + belongtoidsList.get(k) + "))";
                    }
                }

                sqlWhere += ") ";
            }

        }

        BaseBean bb = new BaseBean();
        String voting_type = Util.null2String(params.get("votingtype"));
        bb.writeLog("voting_type:"+voting_type);
        if(StringUtils.isNotBlank(voting_type)){
            sqlWhere += " and votingtype in("+voting_type+")";
        }
        bb.writeLog("sqlWhere:"+sqlWhere);

        boolean isSys = true;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select 1 from hrmresource where id=" + user.getUID());
        if (rs.next()) {
            isSys = false;
        }
        if (isSys && user.getUID() != 1) {
            sqlWhere = " 1=2";
        }

        String mobileTemplate = votingcreatemobiletemplate.createMobileTemplate(JSON.parseArray(JSON_CONFIG,
                SplitMobileDataBean.class));

        String pageUid = VotingPageUidFactory.getPageUid(pageId);

        String tableString = "<table mobileshowtemplate=\"" + mobileTemplate + "\" pageUid=\"" + pageUid
                + "\" pageId=\"" + pageId + "\" pagesize=\""
                + PageIdConst.getPageSize(pageId, user.getUID(), PageIdConst.VOTING) + "\" tabletype=\"none\">";
        tableString += "<sql backfields=\""
                + backFields
                + "\" sqlform=\""
                + Util.toHtmlForSplitPage(fromSql)
                + "\" sqlorderby=\"begindate ,begintime \"  sqlprimarykey=\"id\" sqlsortway=\"Desc\" sqlwhere=\""
                + Util.toHtmlForSplitPage(sqlWhere)
                + "\" />"
                + "<head>"
                + "<col width=\"8%\"  text=\""
                + SystemEnv.getHtmlLabelName(15486, user.getLanguage())
                + "\" column=\"id\" orderkey=\"id\" />"
                + "<col width=\"30%\"  text=\""
                + SystemEnv.getHtmlLabelName(195, user.getLanguage())
                + "\" column=\"subject\" orderkey=\"subject\" />"
                + "<col width=\"10%\"  text=\""
                + SystemEnv.getHtmlLabelName(882, user.getLanguage())
                + "\" column=\"createrid\" orderkey=\"createrid\" transmethod=\"weaver.hrm.resource.ResourceComInfo.getMulResourcename1\"/>"
                + "<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\"/>";
        String isFromMobile = Util.null2String(params.get("_ec_ismobile"));
        if ("true".equals(isFromMobile) && tabInfo == 0) {
            tableString += "<col text=\"\" column=\"begintime\" orderkey=\"begintime\" />"
                    + "<col text=\"\" column=\"endtime\" orderkey=\"endtime\" />"
                    + "<col text=\"\" column=\"countid\" orderkey=\"countid\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getVotingRemarkCount\" />"
                    + "<col text=\"\" column=\"picid\" orderkey=\"picid\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getVotingPathPic\" />"
                    + "<col text=\"\" column=\"enddate\" _key=\"countDownTime\" otherpara=\"column:endtime+"
                    + user.getLanguage()
                    + "\"  transmethod=\"com.api.voting.util.VotingCommonUtil.getCountDownTime2\" />"
                    + "<col text=\"\" column=\"id\" _key=\"joinStatus\" otherpara=\"" + user.getUID()
                    + "\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getVotingUserJoinStatus\" />";
        } else if ("true".equals(isFromMobile) && tabInfo != 0) {
            tableString += "<col text=\"\" column=\"begintime\" orderkey=\"begintime\" />"
                    + "<col text=\"\" column=\"endtime\" orderkey=\"endtime\" />"
                    + "<col text=\"\" column=\"countid\" orderkey=\"countid\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getVotingRemarkCount\" />"
                    + "<col text=\"\" column=\"id\" _key=\"joinStatus\" otherpara=\"" + user.getUID()
                    + "\" transmethod=\"com.api.voting.service.VotingTransMethod4E9.getVotingUserJoinStatus\" />";
        }
        tableString += "</head>" + "</table>";

        String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom());
        Util_TableMap.setVal(sessionkey, tableString);

        apidatas.put("sessionkey", sessionkey);

        // String isFromMobile = Util.null2String(params.get("_ec_ismobile"));
        // if("true".equals(isFromMobile)){
        // if(tabInfo == ConditionUtil.TAB_VOTING_DO){ //已参与
        // //已参与调查中的已参与人数
        // Map<String, String> remarkMap = getVotingRemarkCount(votingShareSql, votingCurrentDate,
        // votingCurrentTime, 1);
        // apidatas.put("remarkMap", remarkMap);
        //
        // }else if(tabInfo == ConditionUtil.TAB_VOTING_UN_DO){//未参与
        // //未参与调查中的已参与人数
        // Map<String, String> remarkMap = getVotingRemarkCount(votingShareSql, votingCurrentDate,
        // votingCurrentTime, 0);
        // apidatas.put("remarkMap", remarkMap);
        // Map<String, String> votingPicMap = getVotingPathPic(votingShareSql, votingCurrentDate,
        // votingCurrentTime);
        // apidatas.put("votingPicMap", votingPicMap);
        // }
        // }

        return apidatas;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }
}
