package weaver.interfaces.htsc.contacts;

import com.engine.common.util.ServiceUtil;
import com.engine.htsc.contacts.service.ContactsService;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;

public class ContactsJob extends BaseCronJob {

    @Override
    public void execute() {
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        RecordSet updateRs = new RecordSet();

        try{
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            ContactsService contactsService = ServiceUtil.getService(ContactsService.class);
            String currentTime = TimeUtil.getCurrentTimeString();

            List<String> leaderList = new ArrayList<>();
            String sql = "select id from hrmresource where seclevel >= 50 and status = '1'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while(rs.next()){
                leaderList.add(Util.null2String(rs.getString("id")));
            }

            for(String userid:leaderList){
                List<String> contactsList = contactsService.getTopContactsIdsByUserid(userid);
                String contactsStr = String.join(",",contactsList);
                sql = "select id from uf_hqbmfzrcylxr where bmfzr = '"+userid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    String update_sql = "update uf_hqbmfzrcylxr set cylxr = '"+contactsStr+"', gxsj = '"+currentTime+"' where bmfzr = '"+userid+"'";
                    bs.writeLog(update_sql);
                    updateRs.executeUpdate(update_sql);
                }else {
                    String deptid = resourceComInfo.getDepartmentID(userid);
                    String insert_sql = "insert into uf_hqbmfzrcylxr (bmmc,bmfzr,cylxr,gxsj) values('"+deptid+"','"+userid+"','"+contactsStr+"','"+currentTime+"')";
                    bs.writeLog(insert_sql);
                    updateRs.executeUpdate(insert_sql);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
