package com.usoftchina.bi.server.service.user;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 同步人员资料
 * @Author chenwei
 * @Date 2019-04-18
 */
@Component
public class SynchronizeEmpInfo {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final Logger LOGGER = LoggerFactory.getLogger(SynchronizeEmpInfo.class);

    private String SQL = "MERGE INTO BI_USERS TARGETTABLE "
                       + "USING EMPLOYEE SOURCETABLE "
                       + "ON (SOURCETABLE.EM_CODE = TARGETTABLE.USER_NAME) "
                       + "WHEN MATCHED THEN "
                       + "  UPDATE  SET TARGETTABLE.BU_CLASS = SOURCETABLE.EM_CLASS, TARGETTABLE.PASS_WORD = SOURCETABLE.EM_PASSWORD "
                       + "WHEN NOT MATCHED THEN"
                       + "  INSERT (BU_ID,BU_NAME,BU_POST,BU_DEPARTMENT,BU_USER_GROUP,USER_NAME,PASS_WORD,BU_ROLE,CREATE_DATE,UPDATA_DATE,USER_TOKEN,BU_PHONE,BU_CLASS) "
                       + "  VALUES (SOURCETABLE.EM_ID,SOURCETABLE.EM_NAME,SOURCETABLE.EM_DEFAULTHSNAME,SOURCETABLE.EM_DEPART,NULL,SOURCETABLE.EM_CODE,SOURCETABLE.EM_PASSWORD,SOURCETABLE.EM_TYPE,SYSDATE,NULL,NULL,SOURCETABLE.EM_MOBILE,SOURCETABLE.EM_CLASS)";

    @Scheduled(cron = "0 0 1 * * ?")
    private void syncEmpInfo(){
        LOGGER.info("同步人员资料任务执行开始!,时间={}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        try {
            jdbcTemplate.execute(SQL);
        } catch (DataAccessException e) {
            LOGGER.error("同步人员资料任务执行失败!原因={}", e.getCause().getMessage());
            return;
        }
        LOGGER.info("同步人员资料任务执行成功!");
    }

}
