package com.teemlink.sync.util;

import cn.myapps.authtime.department.model.DepartmentVO;
import cn.myapps.authtime.user.model.UserDepartmentRoleSet;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.common.util.Security;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.document.ejb.Item;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.FormField;
import cn.myapps.util.DateUtil;
import cn.myapps.util.http.HttpRequestUtil;
import com.teemlink.sync.model.ColumnValue;
import com.teemlink.sync.model.DataObject;
import com.teemlink.sync.model.DataOperation;
import com.teemlink.sync.model.FileOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 同步表单工具
 */
public class SyncUtil {

    /**
     * 生成用户的数据对象
     */
    public static DataOperation buildUserDataOperation(UserVO userVO, String applicationId, String datasourceName, String action) throws Exception{
        DataOperation dataOperation = new DataOperation();
        dataOperation.setAction(action);
        dataOperation.setDataSourceName(datasourceName);
        dataOperation.setApplicationId(applicationId);

        DataObject dataObject = new DataObject();
        dataObject.setTableName("t_user");
        //ID
        dataObject.setId(userVO.getId());

        List<ColumnValue> columnValues = new ArrayList<ColumnValue>();
        //ID
        ColumnValue id = new ColumnValue();
        id.setName("id");
        id.setValue(userVO.getId());
        columnValues.add(id);

        //calendar
        ColumnValue calendar = new ColumnValue();
        calendar.setName("calendar");
        calendar.setValue(userVO.getCalendarType());
        columnValues.add(calendar);
        //levels
        ColumnValue levels = new ColumnValue();
        levels.setName("levels");
        levels.setValue(userVO.getLevel()+"");
        levels.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(levels);
        //remarks
        ColumnValue remarks = new ColumnValue();
        remarks.setName("remarks");
        remarks.setValue(userVO.getRemarks());
        columnValues.add(remarks);
        //superior
        if(userVO.getSuperior() != null){
            ColumnValue superior = new ColumnValue();
            superior.setName("superior");
            superior.setValue(userVO.getSuperior().getId());
            columnValues.add(superior);
        }
        //proxyuser
        if(userVO.getProxyUser() != null){
            ColumnValue proxyuser = new ColumnValue();
            proxyuser.setName("proxyuser");
            proxyuser.setValue(userVO.getProxyUser().getId());
            columnValues.add(proxyuser);
        }
        //defaultdepartment
        ColumnValue defaultdepartment = new ColumnValue();
        defaultdepartment.setName("defaultdepartment");
        defaultdepartment.setValue(userVO.getDefaultDepartment());
        columnValues.add(defaultdepartment);
        //defaultapplication
        ColumnValue defaultapplication = new ColumnValue();
        defaultapplication.setName("defaultapplication");
        defaultapplication.setValue(userVO.getDefaultApplication());
        columnValues.add(defaultapplication);
        //email
        ColumnValue email = new ColumnValue();
        email.setName("email");
        email.setValue(userVO.getEmail());
        columnValues.add(email);
        //loginno
        ColumnValue loginno = new ColumnValue();
        loginno.setName("loginno");
        loginno.setValue(userVO.getLoginno());
        columnValues.add(loginno);
        //loginpwd
        ColumnValue loginpwd = new ColumnValue();
        loginpwd.setName("loginpwd");
        loginpwd.setValue(userVO.getLoginpwd());
        columnValues.add(loginpwd);
        //name
        ColumnValue name = new ColumnValue();
        name.setName("name");
        name.setValue(userVO.getName());
        columnValues.add(name);
        //name_letter
        ColumnValue name_letter = new ColumnValue();
        name_letter.setName("name_letter");
        name_letter.setValue(userVO.getNameLetter());
        columnValues.add(name_letter);
        //telephone
        ColumnValue telephone = new ColumnValue();
        telephone.setName("telephone");
        telephone.setValue(userVO.getTelephone());
        columnValues.add(telephone);
        //status
        ColumnValue status = new ColumnValue();
        status.setName("status");
        status.setValue(userVO.getStatus()+"");
        status.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(status);
        //domainid
        ColumnValue domainid = new ColumnValue();
        domainid.setName("domainid");
        domainid.setValue(userVO.getDomainid());
        columnValues.add(domainid);
        //departmentuser
        ColumnValue departmentuser = new ColumnValue();
        departmentuser.setName("departmentuser");
        departmentuser.setValue(userVO.getDepartmentUser() ? "1" : "0");
        departmentuser.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(departmentuser);
        //startproxytime
        if(userVO.getStartProxyTime() != null){
            String startproxytimeValue = DateUtil.format(userVO.getStartProxyTime(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue startproxytime = new ColumnValue();
            startproxytime.setName("startproxytime");
            startproxytime.setValue(startproxytimeValue);
            startproxytime.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(startproxytime);
        }
        //endproxytime
        if(userVO.getEndProxyTime() != null){
            String endproxytimeValue = DateUtil.format(userVO.getEndProxyTime(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue endproxytime = new ColumnValue();
            endproxytime.setName("endproxytime");
            endproxytime.setValue(endproxytimeValue);
            endproxytime.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(endproxytime);
        }
        //useim
        ColumnValue useim = new ColumnValue();
        useim.setName("useim");
        useim.setValue(userVO.getUseIM() ? "1" : "0");
        useim.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(useim);
        //orderbyno
        ColumnValue orderbyno = new ColumnValue();
        orderbyno.setName("orderbyno");
        orderbyno.setValue(userVO.getOrderByNo()+"");
        orderbyno.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(orderbyno);
        //lastmodifytime
        if(userVO.getLastModifyTime() != null){
            String lastmodifytimeValue = DateUtil.format(userVO.getLastModifyTime(), "yyyy-MM-dd hh:mm:ss.sss");
            ColumnValue lastmodifytime = new ColumnValue();
            lastmodifytime.setName("lastmodifytime");
            lastmodifytime.setValue(lastmodifytimeValue);
            lastmodifytime.setType(ColumnValue.TYPE_TIMESTAMP);
            columnValues.add(lastmodifytime);
        }
        //passwordarray
        ColumnValue passwordarray = new ColumnValue();
        passwordarray.setName("passwordarray");
        passwordarray.setValue(userVO.getPasswordArray());
        columnValues.add(passwordarray);
        //lockflag
        ColumnValue lockflag = new ColumnValue();
        lockflag.setName("lockflag");
        lockflag.setValue(userVO.getLockFlag()+"");
        lockflag.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(lockflag);
        //publickey
        ColumnValue publickey = new ColumnValue();
        publickey.setName("publickey");
        publickey.setValue(userVO.getPublicKey());
        columnValues.add(publickey);
        //avatar
        ColumnValue avatar = new ColumnValue();
        avatar.setName("avatar");
        avatar.setValue(userVO.getAvatar());
        columnValues.add(avatar);
        //favorite_contacts
        ColumnValue favorite_contacts = new ColumnValue();
        favorite_contacts.setName("favorite_contacts");
        favorite_contacts.setValue(userVO.getFavoriteContacts());
        columnValues.add(favorite_contacts);
        //permission_type
        ColumnValue permission_type = new ColumnValue();
        permission_type.setName("permission_type");
        permission_type.setValue(userVO.getPermissionType());
        columnValues.add(permission_type);
        //liaison_officer
        ColumnValue liaison_officer = new ColumnValue();
        liaison_officer.setName("liaison_officer");
        liaison_officer.setValue(userVO.isLiaisonOfficer()?"1":"0");
        liaison_officer.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(liaison_officer);
        //dduserid
        ColumnValue dduserid = new ColumnValue();
        dduserid.setName("dduserid");
        dduserid.setValue(userVO.getDdUserId());
        columnValues.add(dduserid);
        //telephone2
        ColumnValue telephone2 = new ColumnValue();
        telephone2.setName("telephone2");
        telephone2.setValue(userVO.getTelephone2());
        columnValues.add(telephone2);
        //telephonepublic
        ColumnValue telephonepublic = new ColumnValue();
        telephonepublic.setName("telephonepublic");
        telephonepublic.setValue(userVO.isTelephonePublic()?"1":"0");
        telephonepublic.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(telephonepublic);
        //telephonepublic2
        ColumnValue telephonepublic2 = new ColumnValue();
        telephonepublic2.setName("telephonepublic2");
        telephonepublic2.setValue(userVO.isTelephonePublic2()?"1":"0");
        telephonepublic2.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(telephonepublic2);
        //emailpublic
        ColumnValue emailpublic = new ColumnValue();
        emailpublic.setName("emailpublic");
        emailpublic.setValue(userVO.isEmailPublic()?"1":"0");
        emailpublic.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(emailpublic);
        //userinfopublic
        ColumnValue userinfopublic = new ColumnValue();
        userinfopublic.setName("userinfopublic");
        userinfopublic.setValue(userVO.isUserInfoPublic()?"1":"0");
        userinfopublic.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(userinfopublic);
        //signs
        ColumnValue signs = new ColumnValue();
        signs.setName("signs");
        signs.setValue(userVO.getSigns());
        columnValues.add(signs);
        //usehomepage
        if(userVO.getUseHomePage() != null){
            ColumnValue usehomepage = new ColumnValue();
            usehomepage.setName("usehomepage");
            usehomepage.setValue(userVO.getUseHomePage()+"");
            usehomepage.setType(ColumnValue.TYPE_INTEGER);
            columnValues.add(usehomepage);
        }
        //userskin
        ColumnValue userskin = new ColumnValue();
        userskin.setName("userskin");
        userskin.setValue(userVO.getUserSkin());
        columnValues.add(userskin);
        //userstyle
        ColumnValue userstyle = new ColumnValue();
        userstyle.setName("userstyle");
        userstyle.setValue(userVO.getUserStyle());
        columnValues.add(userstyle);
        //pendingstyle
        ColumnValue pendingstyle = new ColumnValue();
        pendingstyle.setName("pendingstyle");
        pendingstyle.setValue(userVO.getPendingStyle());
        columnValues.add(pendingstyle);
        //generalpage
        ColumnValue generalpage = new ColumnValue();
        generalpage.setName("generalpage");
        generalpage.setValue(userVO.getGeneralPage());
        columnValues.add(generalpage);
        //configure
        ColumnValue configure = new ColumnValue();
        configure.setName("configure");
        configure.setValue(userVO.getConfigure());
        columnValues.add(configure);
        //common_opinion
        ColumnValue common_opinion = new ColumnValue();
        common_opinion.setName("common_opinion");
        common_opinion.setValue(userVO.getCommonOpinion());
        columnValues.add(common_opinion);
        //field1
        ColumnValue field1 = new ColumnValue();
        field1.setName("field1");
        field1.setValue(userVO.getField1());
        columnValues.add(field1);
        //field2
        ColumnValue field2 = new ColumnValue();
        field2.setName("field2");
        field2.setValue(userVO.getField2());
        columnValues.add(field2);
        //field3
        ColumnValue field3 = new ColumnValue();
        field3.setName("field3");
        field3.setValue(userVO.getField3());
        columnValues.add(field3);
        //field4
        ColumnValue field4 = new ColumnValue();
        field4.setName("field4");
        field4.setValue(userVO.getField4());
        columnValues.add(field4);
        //field5
        ColumnValue field5 = new ColumnValue();
        field5.setName("field5");
        field5.setValue(userVO.getField5());
        columnValues.add(field5);
        //field6
        ColumnValue field6 = new ColumnValue();
        field6.setName("field6");
        field6.setValue(userVO.getField6());
        columnValues.add(field6);
        //field7
        ColumnValue field7 = new ColumnValue();
        field7.setName("field7");
        field7.setValue(userVO.getField7());
        columnValues.add(field7);
        //field8
        ColumnValue field8 = new ColumnValue();
        field8.setName("field8");
        field8.setValue(userVO.getField8());
        columnValues.add(field8);
        //field9
        ColumnValue field9 = new ColumnValue();
        field9.setName("field9");
        field9.setValue(userVO.getField9());
        columnValues.add(field9);
        //field10
        ColumnValue field10 = new ColumnValue();
        field10.setName("field10");
        field10.setValue(userVO.getField10());
        columnValues.add(field10);
        //pwderrortimes
        ColumnValue pwderrortimes = new ColumnValue();
        pwderrortimes.setName("pwderrortimes");
        pwderrortimes.setValue(userVO.getPwdErrorTimes()+"");
        pwderrortimes.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(pwderrortimes);

        dataObject.setColumnValues(columnValues);
        dataOperation.setDataObject(dataObject);
        return dataOperation;
    }

    /**
     * 生成部门的数据对象
     */
    public static DataOperation buildDeptDataOperation(DepartmentVO departmentVO, String applicationId, String datasourceName, String action) throws Exception{
        DataOperation dataOperation = new DataOperation();
        dataOperation.setAction(action);
        dataOperation.setDataSourceName(datasourceName);
        dataOperation.setApplicationId(applicationId);

        DataObject dataObject = new DataObject();
        dataObject.setTableName("t_department");
        //id
        dataObject.setId(departmentVO.getId());

        List<ColumnValue> columnValues = new ArrayList<ColumnValue>();
        //id
        ColumnValue id = new ColumnValue();
        id.setName("id");
        id.setValue(departmentVO.getId());
        columnValues.add(id);

        //name
        ColumnValue name = new ColumnValue();
        name.setName("name");
        name.setValue(departmentVO.getName());
        columnValues.add(name);
        //superior
        if(departmentVO.getSuperior() != null){
            ColumnValue superior = new ColumnValue();
            superior.setName("superior");
            superior.setValue(departmentVO.getSuperior().getId());
            columnValues.add(superior);
        }
        //domain_id
        ColumnValue domain_id = new ColumnValue();
        domain_id.setName("domain_id");
        domain_id.setValue(departmentVO.getDomain().getId());
        columnValues.add(domain_id);
        //levels
        ColumnValue levels = new ColumnValue();
        levels.setName("levels");
        levels.setValue(departmentVO.getLevel()+"");
        levels.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(levels);
        //indexcode
        ColumnValue indexcode = new ColumnValue();
        indexcode.setName("indexcode");
        indexcode.setValue(departmentVO.getIndexCode());
        columnValues.add(indexcode);
        //code
        ColumnValue code = new ColumnValue();
        code.setName("code");
        code.setValue(departmentVO.getCode());
        columnValues.add(code);
        //sortid
        ColumnValue sortid = new ColumnValue();
        sortid.setName("sortid");
        sortid.setValue(departmentVO.getSortId());
        columnValues.add(sortid);
        //valid
        ColumnValue valid = new ColumnValue();
        valid.setName("valid");
        valid.setValue(departmentVO.getValid()+"");
        valid.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(valid);
        //orderbyno
        ColumnValue orderbyno = new ColumnValue();
        orderbyno.setName("orderbyno");
        orderbyno.setValue(departmentVO.getOrderByNo()+"");
        orderbyno.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(orderbyno);
        //weixin_dept_id
        ColumnValue weixin_dept_id = new ColumnValue();
        weixin_dept_id.setName("weixin_dept_id");
        weixin_dept_id.setValue(departmentVO.getWeixinDeptId());
        columnValues.add(weixin_dept_id);
        //lanxin_dept_id
        ColumnValue lanxin_dept_id = new ColumnValue();
        lanxin_dept_id.setName("lanxin_dept_id");
        lanxin_dept_id.setValue(departmentVO.getLanxinDeptId());
        columnValues.add(lanxin_dept_id);
        //field1
        ColumnValue field1 = new ColumnValue();
        field1.setName("field1");
        field1.setValue(departmentVO.getField1());
        columnValues.add(field1);
        //field2
        ColumnValue field2 = new ColumnValue();
        field2.setName("field2");
        field2.setValue(departmentVO.getField2());
        columnValues.add(field2);
        //field3
        ColumnValue field3 = new ColumnValue();
        field3.setName("field3");
        field3.setValue(departmentVO.getField3());
        columnValues.add(field3);
        //field4
        ColumnValue field4 = new ColumnValue();
        field4.setName("field4");
        field4.setValue(departmentVO.getField4());
        columnValues.add(field4);
        //field5
        ColumnValue field5 = new ColumnValue();
        field5.setName("field5");
        field5.setValue(departmentVO.getField5());
        columnValues.add(field5);
        //field6
        ColumnValue field6 = new ColumnValue();
        field6.setName("field6");
        field6.setValue(departmentVO.getField6());
        columnValues.add(field6);
        //field7
        ColumnValue field7 = new ColumnValue();
        field7.setName("field7");
        field7.setValue(departmentVO.getField7());
        columnValues.add(field7);
        //field8
        ColumnValue field8 = new ColumnValue();
        field8.setName("field8");
        field8.setValue(departmentVO.getField8());
        columnValues.add(field8);
        //field9
        ColumnValue field9 = new ColumnValue();
        field9.setName("field9");
        field9.setValue(departmentVO.getField9());
        columnValues.add(field9);
        //field10
        ColumnValue field10 = new ColumnValue();
        field10.setName("field10");
        field10.setValue(departmentVO.getField10());
        columnValues.add(field10);
        //lastmodifytime
        if(departmentVO.getLastModifyTime() != null){
            String lastmodifytimeValue = DateUtil.format(departmentVO.getLastModifyTime(), "yyyy-MM-dd hh:mm:ss.sss");
            ColumnValue lastmodifytime = new ColumnValue();
            lastmodifytime.setName("lastmodifytime");
            lastmodifytime.setValue(lastmodifytimeValue);
            lastmodifytime.setType(ColumnValue.TYPE_TIMESTAMP);
            columnValues.add(lastmodifytime);
        }
        //dingding_dept_id
        ColumnValue dingding_dept_id = new ColumnValue();
        dingding_dept_id.setName("dingding_dept_id");
        dingding_dept_id.setValue(departmentVO.getDingdingDeptId());
        columnValues.add(dingding_dept_id);

        dataObject.setColumnValues(columnValues);
        dataOperation.setDataObject(dataObject);
        return dataOperation;
    }

    /**
     * 生成部门的数据对象
     */
    public static DataOperation buildUserDeptRoleDataOperation(UserDepartmentRoleSet userDepartmentRoleSet, String applicationId, String datasourceName, String action){
        DataOperation dataOperation = new DataOperation();
        dataOperation.setAction(action);
        dataOperation.setDataSourceName(datasourceName);
        dataOperation.setApplicationId(applicationId);

        DataObject dataObject = new DataObject();
        dataObject.setTableName("t_user_department_role_set");
        //id
        dataObject.setId(userDepartmentRoleSet.getId());

        List<ColumnValue> columnValues = new ArrayList<ColumnValue>();
        //id
        ColumnValue id = new ColumnValue();
        id.setName("id");
        id.setValue(userDepartmentRoleSet.getId());
        columnValues.add(id);
        //userid
        ColumnValue userid = new ColumnValue();
        userid.setName("userid");
        userid.setValue(userDepartmentRoleSet.getUserId());
        columnValues.add(userid);
        //departmentid
        ColumnValue departmentid = new ColumnValue();
        departmentid.setName("departmentid");
        departmentid.setValue(userDepartmentRoleSet.getDepartmentId());
        columnValues.add(departmentid);
        //roleid
        ColumnValue roleid = new ColumnValue();
        roleid.setName("roleid");
        roleid.setValue(userDepartmentRoleSet.getRoleId());
        columnValues.add(roleid);

        dataObject.setColumnValues(columnValues);
        dataOperation.setDataObject(dataObject);
        return dataOperation;
    }

    /**
     * 生成t_document的数据对象
     */
    public static DataOperation buildDocumentHeadOperation(Document doc, String applicationId, String datasourceName, String action) throws Exception{
        DataOperation dataOperation = new DataOperation();
        dataOperation.setAction(action);
        dataOperation.setDataSourceName(datasourceName);
        dataOperation.setApplicationId(applicationId);

        DataObject dataObject = new DataObject();
        dataObject.setTableName("t_document");
        //id
        dataObject.setId(doc.getId());

        List<ColumnValue> columnValues = new ArrayList<ColumnValue>();
        //id
        ColumnValue id = new ColumnValue();
        id.setName("id");
        id.setValue(doc.getId());
        columnValues.add(id);
        //lastmodified
        if(doc.getLastmodified() != null){
            String lastmodifiedValue = DateUtil.format(doc.getLastmodified(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue lastmodified = new ColumnValue();
            lastmodified.setName("lastmodified");
            lastmodified.setValue(lastmodifiedValue);
            lastmodified.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(lastmodified);
        }
        //formname
        ColumnValue formname = new ColumnValue();
        formname.setName("formname");
        formname.setValue(doc.getFormname());
        columnValues.add(formname);
        //auditdate
        if(doc.getAuditdate() != null){
            String auditdateValue = DateUtil.format(doc.getAuditdate(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue auditdate = new ColumnValue();
            auditdate.setName("auditdate");
            auditdate.setValue(auditdateValue);
            auditdate.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(auditdate);
        }
        //author
        ColumnValue author = new ColumnValue();
        author.setName("author");
        author.setValue(doc.getAuthorId());
        columnValues.add(author);
        //authordeptid

        //author_dept_index
        ColumnValue author_dept_index = new ColumnValue();
        author_dept_index.setName("author_dept_index");
        author_dept_index.setValue(doc.getAuthorDeptIndex());
        columnValues.add(author_dept_index);
        //author_user_index

        //created
        if(doc.getCreated() != null){
            String createdValue = DateUtil.format(doc.getCreated(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue created = new ColumnValue();
            created.setName("created");
            created.setValue(createdValue);
            created.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(created);
        }
        //formid
        ColumnValue formid = new ColumnValue();
        formid.setName("formid");
        formid.setValue(doc.getFormid());
        columnValues.add(formid);
        //subformids

        //istmp
        ColumnValue istmp = new ColumnValue();
        istmp.setName("istmp");
        istmp.setValue(doc.getIstmp()?"1":"0");
        istmp.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(istmp);
        //versions
        ColumnValue versions = new ColumnValue();
        versions.setName("versions");
        versions.setValue(doc.getVersions()+"");
        versions.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(versions);
        //sortid
        ColumnValue sortid = new ColumnValue();
        sortid.setName("sortid");
        sortid.setValue(doc.getStateid());
        columnValues.add(sortid);
        //applicationid
        ColumnValue applicationid = new ColumnValue();
        applicationid.setName("applicationid");
        applicationid.setValue(doc.getApplicationid());
        columnValues.add(applicationid);
        //statelabel
        ColumnValue statelabel = new ColumnValue();
        statelabel.setName("statelabel");
        statelabel.setValue(doc.getStateLabel());
        columnValues.add(statelabel);
        //initiator
        ColumnValue initiator = new ColumnValue();
        initiator.setName("initiator");
        initiator.setValue(doc.getInitiator());
        columnValues.add(initiator);
        //audituser
        ColumnValue audituser = new ColumnValue();
        audituser.setName("audituser");
        audituser.setValue(doc.getAudituser());
        columnValues.add(audituser);
        //auditornames
        ColumnValue auditornames = new ColumnValue();
        auditornames.setName("auditornames");
        auditornames.setValue(doc.getAuditorNames());
        columnValues.add(auditornames);
        //lastflowoperation
        ColumnValue lastflowoperation = new ColumnValue();
        lastflowoperation.setName("lastflowoperation");
        lastflowoperation.setValue(doc.getLastFlowOperation());
        columnValues.add(lastflowoperation);
        //parent
        ColumnValue parent = new ColumnValue();
        parent.setName("parent");
        parent.setValue(doc.getParentid());
        columnValues.add(parent);
        //state
        ColumnValue state = new ColumnValue();
        state.setName("state");
        state.setValue(doc.getStateid());
        columnValues.add(state);
        //stateint
        ColumnValue stateint = new ColumnValue();
        stateint.setName("stateint");
        stateint.setValue(doc.getStateInt()+"");
        stateint.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(stateint);
        //lastmodifier
        ColumnValue lastmodifier = new ColumnValue();
        lastmodifier.setName("lastmodifier");
        lastmodifier.setValue(doc.getLastmodifier());
        columnValues.add(lastmodifier);
        //domainid
        ColumnValue domainid = new ColumnValue();
        domainid.setName("domainid");
        domainid.setValue(doc.getDomainid());
        columnValues.add(domainid);
        //auditorlist
        ColumnValue auditorlist = new ColumnValue();
        auditorlist.setName("auditorlist");
        auditorlist.setValue(doc.getAuditorList());
        columnValues.add(auditorlist);
        //coauditorlist
        ColumnValue coauditorlist = new ColumnValue();
        coauditorlist.setName("coauditorlist");
        coauditorlist.setValue(doc.getCoAuditorList());
        columnValues.add(coauditorlist);
        //statelabelinfo
        ColumnValue statelabelinfo = new ColumnValue();
        statelabelinfo.setName("statelabelinfo");
        statelabelinfo.setValue(doc.getStateLabelInfo());
        columnValues.add(statelabelinfo);
        //prevauditnode
        ColumnValue prevauditnode = new ColumnValue();
        prevauditnode.setName("prevauditnode");
        prevauditnode.setValue(doc.getPrevAuditNode());
        columnValues.add(prevauditnode);
        //prevaudituser
        ColumnValue prevaudituser = new ColumnValue();
        prevaudituser.setName("prevaudituser");
        prevaudituser.setValue(doc.getPrevAuditUser());
        columnValues.add(prevaudituser);
        //optionitem
        ColumnValue optionitem = new ColumnValue();
        optionitem.setName("optionitem");
        optionitem.setValue(doc.getOptionItem());
        columnValues.add(optionitem);
        //sign
        ColumnValue sign = new ColumnValue();
        sign.setName("sign");
        sign.setValue(doc.getSign());
        columnValues.add(sign);
        //mappingid
        ColumnValue mappingid = new ColumnValue();
        mappingid.setName("mappingid");
        mappingid.setValue(doc.getMappingId());
        columnValues.add(mappingid);

        dataObject.setColumnValues(columnValues);
        dataOperation.setDataObject(dataObject);
        return dataOperation;
    }

    /**
     * 生成tlk表的数据对象
     */
    public static DataOperation buildDocumentOperation(Document doc, String applicationId, String datasourceName, String action) throws Exception{
        DataOperation dataOperation = new DataOperation();
        dataOperation.setAction(action);
        dataOperation.setDataSourceName(datasourceName);
        dataOperation.setApplicationId(applicationId);

        DataObject dataObject = new DataObject();

        dataObject.setTableName("tlk_"+doc.getFormShortName());
        //id
        dataObject.setId(doc.getId());

        List<ColumnValue> columnValues = new ArrayList<ColumnValue>();
        //id
        ColumnValue id = new ColumnValue();
        id.setName("id");
        id.setValue(doc.getId());
        columnValues.add(id);
        //lastmodified
        if(doc.getLastmodified() != null){
            String lastmodifiedValue = DateUtil.format(doc.getLastmodified(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue lastmodified = new ColumnValue();
            lastmodified.setName("lastmodified");
            lastmodified.setValue(lastmodifiedValue);
            lastmodified.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(lastmodified);
        }
        //formname
        ColumnValue formname = new ColumnValue();
        formname.setName("formname");
        formname.setValue(doc.getFormname());
        columnValues.add(formname);
        //auditdate
        if(doc.getAuditdate() != null){
            String auditdateValue = DateUtil.format(doc.getAuditdate(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue auditdate = new ColumnValue();
            auditdate.setName("auditdate");
            auditdate.setValue(auditdateValue);
            auditdate.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(auditdate);
        }
        //author
        ColumnValue author = new ColumnValue();
        author.setName("author");
        author.setValue(doc.getAuthorId());
        columnValues.add(author);
        //author_dept_index
        ColumnValue author_dept_index = new ColumnValue();
        author_dept_index.setName("author_dept_index");
        author_dept_index.setValue(doc.getAuthorDeptIndex());
        columnValues.add(author_dept_index);
        //created
        if(doc.getCreated() != null){
            String createdValue = DateUtil.format(doc.getCreated(), "yyyy-MM-dd hh:mm:ss");
            ColumnValue created = new ColumnValue();
            created.setName("created");
            created.setValue(createdValue);
            created.setType(ColumnValue.TYPE_DATETIME);
            columnValues.add(created);
        }
        //formid
        ColumnValue formid = new ColumnValue();
        formid.setName("formid");
        formid.setValue(doc.getFormid());
        columnValues.add(formid);
        //istmp
        ColumnValue istmp = new ColumnValue();
        istmp.setName("istmp");
        istmp.setValue(doc.getIstmp()?"1":"0");
        istmp.setType(ColumnValue.TYPE_BOOLEAN);
        columnValues.add(istmp);
        //versions
        ColumnValue versions = new ColumnValue();
        versions.setName("versions");
        versions.setValue(doc.getVersions()+"");
        versions.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(versions);
        //applicationid
        ColumnValue applicationid = new ColumnValue();
        applicationid.setName("applicationid");
        applicationid.setValue(doc.getApplicationid());
        columnValues.add(applicationid);
        //statelabel
        ColumnValue statelabel = new ColumnValue();
        statelabel.setName("statelabel");
        statelabel.setValue(doc.getStateLabel());
        columnValues.add(statelabel);
        //audituser
        ColumnValue audituser = new ColumnValue();
        audituser.setName("audituser");
        audituser.setValue(doc.getAudituser());
        columnValues.add(audituser);
        //auditornames
        ColumnValue auditornames = new ColumnValue();
        auditornames.setName("auditornames");
        auditornames.setValue(doc.getAuditorNames());
        columnValues.add(auditornames);
        //lastflowoperation
        ColumnValue lastflowoperation = new ColumnValue();
        lastflowoperation.setName("lastflowoperation");
        lastflowoperation.setValue(doc.getLastFlowOperation());
        columnValues.add(lastflowoperation);
        //parent
        ColumnValue parent = new ColumnValue();
        parent.setName("parent");
        parent.setValue(doc.getParentid());
        columnValues.add(parent);
        //state
        ColumnValue state = new ColumnValue();
        state.setName("state");
        state.setValue(doc.getStateid());
        columnValues.add(state);
        //stateint
        ColumnValue stateint = new ColumnValue();
        stateint.setName("stateint");
        stateint.setValue(doc.getStateInt()+"");
        stateint.setType(ColumnValue.TYPE_INTEGER);
        columnValues.add(stateint);
        //lastmodifier
        ColumnValue lastmodifier = new ColumnValue();
        lastmodifier.setName("lastmodifier");
        lastmodifier.setValue(doc.getLastmodifier());
        columnValues.add(lastmodifier);
        //domainid
        ColumnValue domainid = new ColumnValue();
        domainid.setName("domainid");
        domainid.setValue(doc.getDomainid());
        columnValues.add(domainid);
        //auditorlist
        ColumnValue auditorlist = new ColumnValue();
        auditorlist.setName("auditorlist");
        auditorlist.setValue(doc.getAuditorList());
        columnValues.add(auditorlist);
        //coauditorlist
        ColumnValue coauditorlist = new ColumnValue();
        coauditorlist.setName("coauditorlist");
        coauditorlist.setValue(doc.getCoAuditorList());
        columnValues.add(coauditorlist);
        //statelabelinfo
        ColumnValue statelabelinfo = new ColumnValue();
        statelabelinfo.setName("statelabelinfo");
        statelabelinfo.setValue(doc.getStateLabelInfo());
        columnValues.add(statelabelinfo);
        //prevauditnode
        ColumnValue prevauditnode = new ColumnValue();
        prevauditnode.setName("prevauditnode");
        prevauditnode.setValue(doc.getPrevAuditNode());
        columnValues.add(prevauditnode);
        //prevaudituser
        ColumnValue prevaudituser = new ColumnValue();
        prevaudituser.setName("prevaudituser");
        prevaudituser.setValue(doc.getPrevAuditUser());
        columnValues.add(prevaudituser);
        //optionitem
        ColumnValue optionitem = new ColumnValue();
        optionitem.setName("optionitem");
        optionitem.setValue(doc.getOptionItem());
        columnValues.add(optionitem);
        //sign
        ColumnValue sign = new ColumnValue();
        sign.setName("sign");
        sign.setValue(doc.getSign());
        columnValues.add(sign);
        //kinggridsignature
        ColumnValue kinggridsignature = new ColumnValue();
        kinggridsignature.setName("kinggridsignature");
        kinggridsignature.setValue(doc.getKinggridSignature());
        columnValues.add(kinggridsignature);

        Collection<Item> items = doc.getItems();
        for(Iterator<Item> iterator = items.iterator();iterator.hasNext();){
            Item item = iterator.next();
            String name = item.getName();
            Object value = item.getValue();
            String type = item.getType();
            ColumnValue itemColumnValue = new ColumnValue();
            itemColumnValue.setName("item_" + name);
            if(value != null){
                itemColumnValue.setValue(String.valueOf(value));
            } else {
                itemColumnValue.setValue(null);
            }
            if (type.equals(Item.VALUE_TYPE_DATE)) {
                itemColumnValue.setType(ColumnValue.TYPE_DATETIME);
            }
            if (type.equals(Item.VALUE_TYPE_NUMBER)) {
                itemColumnValue.setType(ColumnValue.TYPE_DOUBLE);
            }
            columnValues.add(itemColumnValue);
        }

        dataObject.setColumnValues(columnValues);
        dataOperation.setDataObject(dataObject);
        return dataOperation;
    }

    /**
     * 根据document附件生成fileOperation
     * @param doc
     *      文档
     * @param userId
     *      用户id（生成token）
     * @param serverRootUrl
     *      下载服务器网络地址（localhost:8080/obpm）
     * @param pathOnTargetServer
     *      服务器存储物理地址（D:/obpm-demo）
     * @return
     * @throws Exception
     */
    public static List<FileOperation> genFileDataOperationFromDocument(Document doc, String userId, String serverRootUrl, String pathOnTargetServer) throws Exception{
        List<FileOperation> result = new ArrayList<FileOperation>();

        Form form = doc.getForm();
        Collection<Item> items = doc.getItems();
        for(Item vo : items){
            String simpleName ="";
            FormField field = form.findFieldByName(vo.getName());
            if(field != null){
                simpleName =field.getClass().getSimpleName();
                //有存在附件则需要则发送附件,删除时不发送
                if(vo.getValue() != null && ("AttachmentUploadField".equals(simpleName) || "ImageUploadField".equals(simpleName)) ){
                    try {
                        JSONArray jsonArray = cn.myapps.util.json.JsonTmpUtil.fromObject(vo.getValue());
                        for (Object json : jsonArray) {
                            FileOperation fileOperation = new FileOperation();
                            JSONObject jsonObject = (JSONObject) json;
                            String path = jsonObject.getString("path");
                            String token = Security.getToken(userId);
                            String fielUrl = serverRootUrl + path + "?accessToken=" + token;

                            fileOperation.setDownloadUrl(fielUrl);
                            fileOperation.setPathOnTargetServer(pathOnTargetServer + path);
                            result.add(fileOperation);
                        }
                    }
                    catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        return result;
    }

    /**
     * 文件批量发送
     * @return
     */
    public static JSONArray sendFiles(String url, List<FileOperation> fileOperations) throws Exception{
        JSONArray msg = new JSONArray();
        for(FileOperation fileOperation : fileOperations){
            JSONObject result = HttpRequestUtil.post(url, JSONObject.fromObject(fileOperation).toString());
            msg.add(result);
        }
        return msg;
    }

    /**
     * 文件发送
     * @return
     */
    public static JSONObject sendFile(String url, FileOperation fileOperation) throws Exception{
        return HttpRequestUtil.post(url, JSONObject.fromObject(fileOperation).toString());
    }

    /**
     * 请求接口
     * @param url
     * @param dataOperation
     */
    public static JSONObject send(String url, DataOperation dataOperation) throws Exception{
        return HttpRequestUtil.post(url, JSONObject.fromObject(dataOperation).toString());
    }
}
