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

import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
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 com.yihu.wlyy.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 健康教育业务控制类
 *
 * @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 result xml格式
     * @return
     * @throws Exception
     */
    public int saveHealthEduArticles(String result) throws Exception {
        List<Map<String,String>> listmap= Xml2ListMap.xml2List(result);
        String code = null;
        String title = null;
        String imgUrl = null;
        String content = null;
        String keyWord = null;
        String type = null;
        String summary = null;
        int rows = 0;
        for(Map<String,String> temp : listmap){
            code = temp.get("xml.Result.MessageId");
            title = temp.get("xml.Result.MessageTitle");
            imgUrl = temp.get("xml.Result.ImageUrlSmall");
            content = temp.get("xml.Result.MessageContent");
            keyWord = temp.get("xml.Result.MessageType");

            String str = Html2Text.Html2Text(content);
            if(str.length()>50){
            summary = str.substring(0,50).replace("\n","").replace(" ","").replace("&nbsp;","");
            }else {
                summary = str.replace("\n","").replace(" ","").replace("&nbsp;","");
            }

            switch (keyWord){
                case "1":
                    keyWord = "高血压";
                    type = "2";
                    break;
                case "2":
                    keyWord = "糖尿病";
                    type = "1";
                    break;
                case "3":
                    keyWord = "儿保";
                    type = "3";
                    break;
                case "4":
                    keyWord = "妇保";
                    type = "3";
                    break;
                case "5":
                    keyWord = "孕产";
                    type = "3";
                    break;
                case "6":
                    keyWord = "医药";
                    type = "4";
                    break;
                case "7":
                    keyWord = "急救";
                    type = "4";
                    break;
                case "8":
                    keyWord = "生活";
                    type = "0";
                    break;
                case "9":
                    keyWord = "更多";
                    type = "0";
                    break;
            }

            String sql = "INSERT INTO wlyy_health_edu_article  " +
                    "VALUES(NULL,?,?,?,?,?,NULL,?,?)";
           /* String sql = "INSERT INTO wlyy_health_article  " +
                    "VALUES(NULL,?,?,?,?,?,NULL,?,?)";*/
            rows = jdbcTemplate.update(sql,code,title,summary,imgUrl,content,keyWord,type);
            rows+=rows;
        }
        return rows;
    }

    /**
     * 由请求参数获取福州健康教育文章
     * @param params
     * @return
     * @throws Exception
     */
    public String getHealthEduArticles(Map<String, String> params) throws Exception {
        HttpClientUtil httpClientUtil = new HttpClientUtil();

//      获取远程地址url 、App Key 和 App secret  
        String prixUrl = SystemConf.getInstance().getYihuOpenPlatformUrl();
//        String prixUrl ="http://apitest.yihu.com.cn/OpenPlatform/cgiBin/1.0/";
        String appId =SystemConf.getInstance().getYihuOpenPlatformAppId();
//        String appId = "9000276";
        String secret = SystemConf.getInstance().getYihuOpenPlatformSecret();
//        String secret = "OKC8BS1KGXTDE9GPP1EO4VYLUXF8DJ7QUP72H613ZXA";
//      请求参数（i健康接口说明文档）正式接口 由prixUrl获取apixUrl
        String apiUrl = prixUrl+"jkjy/JkjyImpl/queryHealtheducationForIHealth";


//      获取加密后参数集合
        Map<String,String> param = httpClientUtil.getSecretParams(params,appId,secret);
//      拼接请求URL （加密签名+apiUrl）
//      获取返回数据（ HTTP post请求，参数需要utf-8编码)
        String  results = httpClientUtil.httpPost(apiUrl,param);


        return results;
    }

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

    public HealthEduArticle findArticleById(Long id) {
        return healthEduArticleDao.findOne(id);
    }

    /**
     * 获取文章列表
     *
     * @param page     页码
     * @param pagesize 分页大小
     * @return 列表
     */
    public List<Map<String, Object>> findAll(int page, int pagesize, String filter, String doctor, String patient,int wheaType) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        if (page <=0) {
            page = 1;
        }
        page = page-1;
        List<Object> params = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select a.id,a.code,a.title,a.url,a.czrq,a.summary 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 = " where 1=1 ";
        if (StringUtils.isNotBlank(filter)) {
            //记录搜索记录
            healthEduArticleLabelService.saveOrUpdateLabel(filter, doctor);
            filter = "%" + filter + "%";
            where += " and  ( a.title like ? or a.keyword like ? )";
            params.add(filter);
            params.add(filter);
        }
        if(wheaType>=0){
            where += " and  ( a.whea_type = ? )";
            params.add(wheaType);
        }
        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" +
                "    ,b.title" +
                "    ,b.url" +
                "    ,a.czrq" +
                "    ,b.summary content" +
                "    ,d.code" +
                "    ,d.name" +
                "    ,d.photo" +
                "    ,a.admin_team_code" +
                "    ,a.is_read" +
                "    ,a.attached_content" +
                "  from" +
                "    wlyy_health_edu_article_patient a" +
                "    ,wlyy_health_edu_article b" +
                "    ,wlyy_doctor d" +
                "  where" +
                "    a.article = b.code " +
                "    and 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 patient
     * @return
     */
    public int readAllArticle(String patient) {
        return healthEduArticlePatientDao.readAllArticle(patient);
    }

    /**
     * 发送文章列表
     *
     * @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;
        }

    }
}
