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

import java.io.File;
import java.util.*;

import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
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.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 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;

/**
 * 健康教育业务控制类
 *
 * @author George
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class HealthEduArticleService extends BaseService {

    @Autowired
    private HealthEduArticleDao healthEduArticleDao;
    @Autowired
    private HealthEduArticlePatientDao healthEduArticlePatientDao;
    @Autowired
    private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
    @Autowired
    private HealthEduArticleLabelService healthEduArticleLabelService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询文章信息
     *
     * @param code
     * @return
     */
    public HealthEduArticle findArticleByCode(String code) {
        return healthEduArticleDao.findByCode(code);
    }

    /**
     * 获取文章列表
     *
     * @param page     页码
     * @param pagesize 分页大小
     * @return 列表
     */
    public List<Map<String, Object>> findAll(int page, int pagesize, String filter, String doctor, String patient) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        if (page < 0) {
            page = 0;
        }
        List<Object> params = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select a.id,a.code,a.title,a.url,a.czrq,a.content,a.keyword");
        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 1) as readAmount");
        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 2) as collectionAmount");
        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 3) as repeatAmount");
        sql.append(",(select count(1) from wlyy_health_edu_article_doctor c where c.article = a.code and c.doctor =?) as collection");
        params.add(doctor);
        if (StringUtils.isNotBlank(patient)) {
            sql.append(",(select count(1) from wlyy_health_edu_article_patient c where c.article = a.code and c.doctor = ? and c.patient= ? ) as send");
            params.add(doctor);
            params.add(patient);
        }
        sql.append(" from wlyy_health_edu_article a ");//内联取文章内容
        String where = " ";
        if (StringUtils.isNotBlank(filter)) {
            //记录搜索记录
            healthEduArticleLabelService.saveOrUpdateLabel(filter, doctor);
            filter = "%" + filter + "%";
            where += " where ( a.title like ? or a.keyword like ? )";
            params.add(filter);
            params.add(filter);
        }
        int start = page * pagesize;

        String pageInfo = " limit " + start + "," + pagesize;

        String orderBy = " order by a.czrq,a.id desc";

        sql.append(where).append(orderBy).append(pageInfo);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        return result;
    }

    /**
     * 查询给患者发送的健康教育文章
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> findByPatientAndTeam(String patient, long teamCode, int page, int pageSize) {
        List<Object> params = new ArrayList<Object>();
        String sql = "select " +
                "    a.article" +
                "    ,a.title" +
                "    ,a.url" +
                "    ,a.czrq" +
                "    ,a.content" +
                "    ,d.code" +
                "    ,d.name" +
                "    ,d.photo" +
                "    ,a.admin_team_code" +
                "  from" +
                "    wlyy_health_edu_article_patient a" +
                "    ,wlyy_doctor d" +
                "  where" +
                "    a.doctor = d.code " +
                "    and a.patient = ?" +
                "    and a.admin_team_code = ?" +
                "  order by a.czrq desc limit " + page*pageSize + "," + pageSize;

        List<Map<String,Object>> result = jdbcTemplate.queryForList(sql,new Object[]{patient,teamCode});
        return result;
    }

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

    /**
     * 发送文章列表
     *
     * @param list
     * @return
     */
    public int send(List<HealthEduArticlePatient> list) {
        Iterable<HealthEduArticlePatient> iterable = healthEduArticlePatientDao.save(list);
        //记录转发量
        for (HealthEduArticlePatient healthEduArticlePatient : list) {
            healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.REPEAT_STATUS, healthEduArticlePatient.getArticle(), healthEduArticlePatient.getTitle(), healthEduArticlePatient.getDoctor());
        }
        Iterator<HealthEduArticlePatient> iterator = iterable.iterator();
        if (iterator.hasNext()) {
            return 1;
        } else {
            return 0;
        }

    }
}
