package com.yihu.wlyy.service.app.health;

import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.repository.education.HealthEduArticleDao;
import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
import com.yihu.wlyy.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

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

/**
 * 健康教育患者业务逻辑类
 *
 * @author linz
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class HealthEduArticlePatientService extends BaseService {

    @Autowired
    private HealthEduArticlePatientDao healthEduArticlePatientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据文章标示获取数据
     *
     * @param article
     * @return
     */
    @Deprecated
    public HealthEduArticlePatient findByArticle(String article) {
        return healthEduArticlePatientDao.findByArticle(article);
    }

    /**
     * 根据文章id获取数据
     *
     * @param id
     * @return
     */
    public HealthEduArticlePatient findById(Long id) {
        return healthEduArticlePatientDao.findOne(id);
    }

    public List<HealthEduArticlePatient> findByArticleAndPatient(String article, String patient) {
        return healthEduArticlePatientDao.findByArticleAndPatient(article, patient);
    }

    /**
     * 查询患者文章
     * @param patient 患者标识
     * @param pagesize 分页大小
     * @return
     */
//	public Page<HealthEduArticlePatient> findByPatient(String patient, long id, int pagesize) {
//		if (pagesize <= 0) {
//			pagesize = 10;
//		}
//		// 排序
//		Sort sort = new Sort(Direction.DESC, "id");
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//		// 设置查询条件
//		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//		// 患者过滤
//		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//		if (id > 0) {
//			filters.put("id", new SearchFilter("id", Operator.LT, id));
//		}
//		Specification<HealthEduArticlePatient> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthEduArticlePatient.class);
//		return healthEduArticlePatientDao.findAll(spec, pageRequest);
//	}

    /**
     * 查询患者文章
     *
     * @param patient  患者标识
     * @param pagesize 分页大小
     * @return
     */
    public List<HealthEduArticlePatient> findByPatient(String patient,int wheaType, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        String sql = "select " +
                "    a.id" +
                "    ,a.patient" +
                "    ,a.article" +
                "    ,a.doctor" +
                "    ,a.doctor_name as doctorName" +
                "    ,b.title" +
                "    ,b.url" +
                "    ,b.summary as content" +
                "    ,a.is_read as 'read'" +
                "    ,a.czrq" +
                "    ,a.attached_content" +
                "    ,b.id as article_id" +
                " from" +
                "     wlyy_health_edu_article_patient a" +
                "     , wlyy_health_edu_article b" +
                " where" +
                "      a.article = b.code" +
                " and a.patient = ?" +
                (id > 0 ? " and a.id < ? " : "") +
                (wheaType > 0 ? " and a.wheaType = ? " : "") +
                " order by a.id desc limit 0," + pagesize;
        Object params[] = null;
        if(wheaType>-1&&id>0){
            params = new Object[]{patient,id,wheaType};
        }else if(wheaType>-1&&id<0){
            params = new Object[]{patient,wheaType};
        }
        else if(wheaType<0&&id>0){
            params = new Object[]{patient,id};
        }else{
            params = new Object[]{patient};
        }
        List<HealthEduArticlePatient> list = jdbcTemplate.query(sql,params, new BeanPropertyRowMapper(HealthEduArticlePatient.class));
        return list;
    }


    /**
     * 查询患者文章
     *
     * @param doctor  医生标识
     * @param  page 第几页
     * @param pagesize 分页大小
     * @return
     */
    public List<Map<String,Object>> findByDoctor(String doctor,int page, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        if(page<=0){
            page = 1 ;
        }
        int start = (page-1) * pagesize;
        String sql ="select a.article,b.title,b.summary,a.attached_content, a.czrq,count( distinct a.patient) as amount,GROUP_CONCAT( distinct p.name) as  patients,a.batch_no from "+
        " wlyy_health_edu_article_patient a, "+
        " wlyy_health_edu_article b,"+
        " wlyy_patient p"+
        " where"+
        " a.article = b.code"+
        " and a.patient = p.code"+
        " and a.doctor =? "+
        " group BY a.batch_no,a.article,a.attached_content,b.summary,a.doctor order by a.czrq desc  limit ?,? ";
        Object params[] = new Object[]{doctor,start,pagesize};
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,params);
        return list;
    }

    /**
     * 查询批次号相关的文章及成员信息
     * @param doctor
     * @param article
     * @param batchNo
     * @return
     */
    public List<Map<String,Object>> findByBatchNo(String doctor,String article, String  batchNo) {
        String sql ="select a.article,b.title,b.content,a.attached_content,b.url, a.czrq as send_time,b.czrq,a.batch_no,sum(a.is_read) as no_read from "+
                " wlyy_health_edu_article_patient a, "+
                " wlyy_health_edu_article b,"+
                " wlyy_patient p"+
                " where"+
                " a.article = b.code"+
                " and a.patient = p.code"+
                " and a.doctor =? "+
                " and a.article =? "+
                (StringUtils.isNotBlank(batchNo)?" and a.batch_no =? ":"and a.batch_no is null ")+
                " group BY a.batch_no,a.article,b.content,b.summary,a.doctor,b.title";
        Object params[] =  (StringUtils.isNotBlank(batchNo)?new Object[]{doctor,article,batchNo}:new Object[]{doctor,article});
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,params);
        for(Map<String,Object> dataMap :list){
            String patientListSql ="select a.patient,p.name,a.is_read "+
            " from wlyy_health_edu_article_patient a,wlyy_health_edu_article b,wlyy_patient p"+
            " where "+
            " a.article = b.code " +
            " and a.doctor=? and  a.article =?"+
            (StringUtils.isNotBlank(batchNo)?" and a.batch_no =? ":" and a.batch_no is null ")+
            " and a.patient = p.code " +
            " group BY a.batch_no,a.article,b.content,a.attached_content,a.patient,b.title";
            List<Map<String,Object>> patientList = jdbcTemplate.queryForList(patientListSql,params);
            dataMap.put("patients",patientList);
            dataMap.put("read_amount",patientList.size()-Integer.parseInt(dataMap.get("no_read").toString()));
            dataMap.put("amount",patientList.size());
        }
        return list;
    }




    /**
     * 文章更新为已读
     *
     * @param patient
     * @param article
     * @return
     */
    public int updateRead(String patient, String article) {
        return healthEduArticlePatientDao.updateRead(patient, article);
    }

}
