package com.yihu.jw.base.service.sync;

import com.yihu.jw.base.dao.sync.BaseSyncDataDao;
import com.yihu.jw.base.useragent.UserAgent;
import com.yihu.jw.entity.base.sync.BaseSyncDataDO;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.YkyyEntranceService;
import com.yihu.jw.restmodel.base.wx.WxReplySceneVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2020/5/25
 */
@Service
public class BaseSyncDataService extends BaseJpaService<BaseSyncDataDO, BaseSyncDataDao> {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private XzzxEntranceService xzzxEntranceService;

    @Autowired
    private UserAgent userAgent;

    @Autowired
    private YkyyEntranceService ykyyEntranceService;

    @Autowired
    private EntranceService entranceService;

    @Autowired
    private BaseSyncDataDao baseSyncDataDao;
//    public PageEnvelop findAll(Integer page, Integer size){
//
//        StringBuffer sql= new StringBuffer("SELECT * FROM wlyy_data_sync ");
//        sql.append(" ORDER BY complete_time LIMIT ").append((page-1)*size).append(",").append(size);
//
//        List<BaseSyncDataDO> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(BaseSyncDataDO.class));
//
//        long count =list.size();
//
//        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find,list,page,size,count);
//    }
        private static Logger logger = LoggerFactory.getLogger(BaseSyncDataService.class);
    /**
     * 根据时间查询
     * @param startTime
     * @param endTime
     * @return
     */
    public PageEnvelop findAllSyncData(String startTime, String endTime,Integer page,Integer size,String wechatId) {

        StringBuffer sql= new StringBuffer("SELECT c.* FROM wlyy_data_sync c WHERE 1=1 ");
        StringBuffer sqlCount= new StringBuffer();
        List<BaseSyncDataDO> list=null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            sqlCount.append("SELECT COUNT(c.\"id\") AS count FROM wlyy_data_sync c WHERE 1=1  ");
//            AND  c."complete_time" BETWEEN to_date('2020-05-06 00:00:00','yyyy-mm-dd hh24:mi:ss') AND to_date('2020-08-06 00:00:00','yyyy-mm-dd hh24:mi:ss')
            if (StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime)){
                sql.append("  AND  c.\"complete_time\" BETWEEN to_date('").append(startTime).append("00:00:00','yyyy-mm-dd hh24:mi:ss')  AND to_date('").append(endTime).append("23:59:59','yyyy-mm-dd hh24:mi:ss')");
                sqlCount.append("  AND  c.\"complete_time\" BETWEEN to_date('").append(startTime).append("00:00:00','yyyy-mm-dd hh24:mi:ss')  AND to_date('").append(endTime).append("23:59:59','yyyy-mm-dd hh24:mi:ss')");
            }
            String oracleSql="SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tA .*\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";
            oracleSql+=sql;
            oracleSql+="ORDER BY c.\"create_time\" DESC";
            oracleSql+="\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <="+page*size +
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= "+(page-1)*size;
            logger.info("oracleSql="+oracleSql);
            list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper<>(BaseSyncDataDO.class));
        }else {
            sqlCount.append("SELECT COUNT(c.id) AS count FROM wlyy_data_sync c WHERE 1=1  ");
            if (StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime)){
                sql.append(" and c.complete_time BETWEEN ").append("'").append(startTime).append("'").append(" AND ").append("'").append(endTime).append("'");
                sqlCount.append(" and c.complete_time BETWEEN ").append("'").append(startTime).append("'").append(" AND ").append("'").append(endTime).append("'");
            }

            sql.append(" ORDER BY c.create_time DESC LIMIT ").append((page-1)*size).append(",").append(size);
            logger.info("sql="+sql);
            list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(BaseSyncDataDO.class));

        }


        logger.info("sqlCount="+sqlCount);
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sqlCount.toString());

        long count = Long.parseLong(mapList.get(0).get("count").toString());

        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find,list,page,size,count);
    }


    /**
     * 完成同步
     * @return
     */
    public void complete (String wxId) {
        logger.info("======================同步开始========================");
        BaseSyncDataDO syncDataDO = new BaseSyncDataDO();
        syncDataDO.setUpdateTime(DateUtil.getNowDate());
        syncDataDO.setStyle(1);
        try {
            //眼科中心
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                logger.info("======================眼科中心同步开始========================");
                String result = ykyyEntranceService.updateYkyyDept();
                if (result.equalsIgnoreCase("success")){
                    logger.info("======================同步科室信息成功========================");
                }else {
                    logger.info("======================同步科室信息失败========================");
                }

                String re = ykyyEntranceService.updateYkyyDoctor(null);
                if (re.equalsIgnoreCase("success")){
                    logger.info("======================同步医生信息成功========================");
                }else {
                    logger.info("======================同步医生信息失败========================");
                }

                if (result.equalsIgnoreCase("success")&&re.equalsIgnoreCase("success")){
                    syncDataDO.setSyncResult("同步成功");
                    logger.info("======================眼科中心同步成功========================");
                }else {
                    syncDataDO.setSyncResult("同步失败");
                    logger.info("======================眼科中心同步失败========================");
                }
                syncDataDO.setCompleteTime(DateUtil.getNowDate());
                logger.info("======================眼科中心同步结束========================");
            }else if ("xm_xzzx_wx".equalsIgnoreCase(wxId)){
                logger.info("======================心脏中心同步开始========================");
                Integer doctorInfo = xzzxEntranceService.syncDoctorInfo();
                if (doctorInfo==200){
                    logger.info("======================同步医生信息成功========================");
                }else {
                    logger.info("======================同步医生信息失败========================");
                }
                Integer deptInfo = xzzxEntranceService.syncDeptInfo();
                if (deptInfo==200){
                    logger.info("======================同步部门信息成功========================");
                }else {
                    logger.info("======================同步部门信息失败========================");
                }
                Integer jobTitle = xzzxEntranceService.syncJobTitle();
                if (jobTitle==200){
                    logger.info("======================同步职称信息成功========================");
                }else {
                    logger.info("======================同步职称信息失败========================");
                }
                Integer chargeDict = xzzxEntranceService.syncChargeDict();
                if (chargeDict==200){
                    logger.info("======================同步号别信息成功========================");
                }else {
                    logger.info("======================同步号别信息失败========================");
                }

                if (deptInfo==200&&doctorInfo==200&&jobTitle==200&&chargeDict==200){
                    syncDataDO.setSyncResult("同步成功");
                    logger.info("======================心脏中心同步成功========================");
                }else {
                    syncDataDO.setSyncResult("同步失败");
                    logger.info("======================心脏中心同步失败========================");
                }
                syncDataDO.setCompleteTime(DateUtil.getNowDate());
                logger.info("======================心脏中心同步结束========================");
            } else if("xm_zsyy_wx".equalsIgnoreCase(wxId)){
                logger.info("======================中山医院信息同步开始========================");
                Integer syncMS02003 = entranceService.syncMS02003();
                if (syncMS02003==200){
                    logger.info("======================同步医生信息成功========================");
                }else {
                    logger.info("======================同步医生信息失败========================");
                }
                Integer syncBS16010 = entranceService.syncBS16010();
                if (syncBS16010==200){
                    logger.info("======================同步医生简介信息成功========================");
                }else {
                    logger.info("======================同步医生简介信息失败========================");
                }
                Integer syncBS16011 = entranceService.syncBS16011();
                if (syncBS16011==200){
                    logger.info("======================同步科室简介信息成功========================");
                }else {
                    logger.info("======================同步科室简介信息失败========================");
                }
                Integer integer1 = entranceService.syncDoctorInfo();
                if (integer1==200){
                    logger.info("======================同步单个医生信息成功========================");
                }else {
                    logger.info("======================同步单个医生信息失败========================");
                }


                if (syncMS02003==200&&syncBS16010==200&&syncBS16011==200&&integer1==200){
                    syncDataDO.setSyncResult("同步成功");
                    logger.info("======================中山医院信息同步成功========================");
                }else {
                    syncDataDO.setSyncResult("同步失败");
                    logger.info("======================中山医院信息同步失败========================");
                }
                syncDataDO.setCompleteTime(DateUtil.getNowDate());
                logger.info("======================中山医院信息同步结束========================");
            }else {
                syncDataDO.setSyncResult("同步失败");
                syncDataDO.setCompleteTime(DateUtil.getNowDate());
                logger.info("======================同步信息失败========================");
            }

        } catch (Exception e) {
            syncDataDO.setSyncResult("同步失败");
            syncDataDO.setCompleteTime(DateUtil.getNowDate());
            e.printStackTrace();
        }
        syncDataDO.setCreateUserName(userAgent.getUNAME());
        baseSyncDataDao.save(syncDataDO);
        logger.info("======================同步结束========================");
    }

}
