package com.yihu.jw.hospital.message.service;

import com.yihu.jw.entity.hospital.message.BaseBannerDO;
import com.yihu.jw.entity.hospital.message.BaseBannerDoctorDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.BaseBannerDao;
import com.yihu.jw.hospital.message.dao.BaseBannerDoctorDao;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BaseBannerService extends BaseJpaService<BaseBannerDO, BaseBannerDao> {
    @Autowired
    private BaseBannerDao baseBannerDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseBannerDoctorDao baseBannerDoctorDao;
    /**
     * 医生锦旗管理查询
     * @param
     * @return
     * @throws Exception
     */
   /* public List<BaseBannerDO> queryBannerByNameAndStatus(String name, String status, Integer page, Integer pageSize){
        Integer queryStatus =0;
        Integer pageNo = (page-1)*pageSize;
        Pageable pageable = new PageRequest(page,pageSize);
        if (StringUtils.isNotEmpty(status)) {
            queryStatus = Integer.valueOf(status);
            List<BaseBannerDO> result = baseBannerDao.queryByNameAndStatus(name,queryStatus,pageNo,pageSize);
            return result;
      }else {
            List<BaseBannerDO> result = baseBannerDao.queryByName(name,pageNo,pageSize);
            return result;
        }
    }*/
    public Envelop queryBannerByNameAndStatus(String name, String status, Integer page, Integer pageSize){
        Map<String,Object> params = new HashedMap();
        String sqlcount = dealSql(name,status,true);
        String sql  = dealSql(name,status,false);

        if (StringUtils.isNotEmpty(status)){
            params.put("status",status);
        }
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlcount,params);
        if(total!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params,page,pageSize);
        for (Map<String,Object> map:list){
            String createTime= map.get("create_time").toString();
            String updateTime = map.get("update_time").toString();
            map.put("create_time",DateUtil.dateToStrLong(DateUtil.strToDateLong(createTime)));
            map.put("update_time",DateUtil.dateToStrLong(DateUtil.strToDateLong(updateTime)));
            String bannerId = map.get("id").toString();
            String sqlId = "select t.id AS \"id\" from base_banner_doctor t where t.banner_id = '"+bannerId+"'";
            List<Map<String,Object>> listID=hibenateUtils.createSQLQuery(sqlId,0,1);
            String bannerGiveId ="";
            if (listID.size()>0){
                bannerGiveId = listID.get(0).get("id").toString();
            }
            BaseBannerDoctorDO baseBannerDoctorDO = baseBannerDoctorDao.findOne(bannerGiveId);
            if (null!=baseBannerDoctorDO){
                //1不能删除
                map.put("deleteFlag",1);
            }else {
                //2可以删除
                map.put("deleteFlag",2);
            }
        }
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, pageSize, count);
    }
    private String dealSql(String name, String status,Boolean isCount){

        StringBuffer sql = new StringBuffer();
        if (isCount) {
            sql.append("SELECT COUNT(1) AS \"total\" FROM (");
        }
        sql.append("select p.id as \"id\"," +
                "p.saas_id as \"saas_id\"," +
                "p.name as \"name\"," +
                "p.description as \"description\"," +
                "p.img as \"img\", p.is_sort as \"sort\",p.status as \"status\",p.create_time as \"create_time\",p.create_user as \"create_user\"," +
                "p.create_user_name as \"create_user_name\"," +
                "p.update_time as \"update_time\"," +
                "p.update_user as \"update_user\",p.update_user_name as \"update_user_name\" from base_banner p where 1=1");
        if(StringUtils.isNotEmpty(name)){
            sql.append(" and p.name like '%"+name+"%'");
        }if (StringUtils.isNotEmpty(status)){
            sql.append(" and p.status =:status");

        }
        sql.append(" order by  p.is_sort desc ");
        if (isCount) {
            sql.append(") t");
        }
        return sql.toString();
    }

    /**
     * 医生锦旗新增
     * @param
     * @return
     * @throws Exception
     */
    public BaseBannerDO creatBanner(BaseBannerDO baseBannerDO){
        String sql = "select max(is_sort) as sort from base_banner";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String,Object> map = list.get(0);
        int sort = 0;
        if (null!=map.get("sort")){
            if(null!=map){
                sort = Integer.valueOf(map.get("sort").toString());
            }
        }
        baseBannerDO.setSort(sort+1);
        baseBannerDO.setUpdateTime(new Date());
        baseBannerDO.setCreateTime(new Date());
        BaseBannerDO result =  baseBannerDao.save(baseBannerDO);
        return result;
    }
    /**
     * 医生锦旗更新
     * @param
     * @return
     * @throws Exception
     */
    public BaseBannerDO updateBanner(String id,String name,String img,String status,String updateUser,String updateUserName,String description){
        BaseBannerDO bannerDO = baseBannerDao.findOne(id);
        if (null == bannerDO){
            return null;
        }
        if (!StringUtil.isEmpty(name)){
            bannerDO.setName(name);
            bannerDO.setUpdateTime(new Date());
        }
        if (!StringUtil.isEmpty(img)){
            bannerDO.setImg(img);
        }
        if (!StringUtil.isEmpty(updateUser)){
            bannerDO.setUpdateUser(updateUser);
        }
        if (!StringUtil.isEmpty(updateUserName)){
            bannerDO.setUpdateUser(updateUserName);
        }
        if (!StringUtil.isEmpty(status)){
            bannerDO.setStatus(Integer.valueOf(status));
        }
        if (!StringUtil.isEmpty(description)){
            bannerDO.setDescription(description);
        }
        baseBannerDao.save(bannerDO);
        return bannerDO;
    }
    /**
     * 医生锦旗删除
     * @param
     * @return
     * @throws Exception
     */
    public Boolean deleteBanner(String id){
        BaseBannerDO bannerDO = baseBannerDao.findOne(id);
        if (null == bannerDO){
            return false;
        }
        baseBannerDao.delete(id);
        return true;
    }
    /**
     * 医生锦旗上移
     * @param
     * @return
     * @throws Exception
     */
    public BaseBannerDO upBanner(String id) throws Exception{
        BaseBannerDO bannerDO = baseBannerDao.findOne(id);
        int maxSort = baseBannerDao.getMaxSort();
        int sort = 0;
        if(null!=bannerDO){
            sort = bannerDO.getSort();
        }
        if (maxSort==sort){
            throw new Exception("不能上移");
        }
        String sql = "select t.id AS \"id\" from base_banner t where t.is_sort > "+sort+" order by t.is_sort asc ";
        System.out.println(sql);
        List<Map<String,Object>> list=hibenateUtils.createSQLQuery(sql,1,1);
        BaseBannerDO upPrevious = new BaseBannerDO();
        if (list.size()>0){
            String prviousBannerId = list.get(0).get("id").toString();
            upPrevious =baseBannerDao.findOne(prviousBannerId);
        }
        //BaseBannerDO upPrevious = baseBannerDao.upBanner(sort);

        //交换sort值
        bannerDO.setSort(upPrevious.getSort());
        upPrevious.setSort(sort);
        baseBannerDao.save(bannerDO);
        baseBannerDao.save(upPrevious);
        return bannerDO;
    }
    /**
     * 医生锦旗下移
     * @param
     * @return
     * @throws Exception
     */
    public BaseBannerDO downBanner(String id) throws Exception{
        //当前banner
        BaseBannerDO bannerDO = baseBannerDao.findOne(id);
        int minSort = baseBannerDao.getMinSort();
        int sort = 0;
        if(null!=bannerDO){
            sort = bannerDO.getSort();
        }
        if (minSort==sort){
            throw new Exception("不能下移");
        }
        String sql = " select id AS \"id\" from base_banner where is_sort < "+sort+" order by is_sort desc ";
        List<Map<String,Object>> list=hibenateUtils.createSQLQuery(sql,1,1);
        BaseBannerDO downPrevious = new BaseBannerDO();
        if (list.size()>0){
            String prviousBannerId = list.get(0).get("id").toString();
            downPrevious =baseBannerDao.findOne(prviousBannerId);
        }
        //获取的下一条banner
        //BaseBannerDO downPrevious = baseBannerDao.downBanner(sort);
        //交换sort值
        bannerDO.setSort(downPrevious.getSort());
        downPrevious.setSort(sort);
        baseBannerDao.save(bannerDO);
        baseBannerDao.save(downPrevious);
        return bannerDO;
    }
    /**
     * 锦旗开关
     * @param
     * @return
     * @throws Exception
     */
    public BaseBannerDO onOff(String id ,String status){
        BaseBannerDO bannerDO = baseBannerDao.findOne(id);
        if(null!=bannerDO){
            bannerDO.setStatus(Integer.valueOf(status));
        }
        baseBannerDao.save(bannerDO);
        return bannerDO;
    }
}
