package com.yihu.wlyy.service.template;

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
import com.yihu.wlyy.entity.template.DoctorGuidanceTemp;
import com.yihu.wlyy.entity.template.DoctorTeamGuidanceDetail;
import com.yihu.wlyy.entity.template.DoctorTeamGuidanceTemplate;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamMemberDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.template.DoctorGuidanceTempDao;
import com.yihu.wlyy.repository.template.DoctorTeamGuidanceDetailDao;
import com.yihu.wlyy.repository.template.DoctorTeamGuidanceTemplateDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.util.CommonUtil;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Reece on 2017/6/8.
 */
@Service
@Transactional
public class DoctorTeamGuidanceService extends BaseService {
    @Autowired
    private DoctorTeamGuidanceTemplateDao doctorTeamGuidanceTemplateDao;
    @Autowired
    private DoctorTeamGuidanceDetailDao doctorTeamGuidanceDetailDao;
    @Autowired
    private DoctorGuidanceTempDao doctorGuidanceTempDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private DoctorAdminTeamMemberDao memberDao;
    @Autowired
    private PatientHealthGuidanceService patientHealthGuidanceService;
    @Autowired
    private ConsultService consultService;
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;

    /**
     * 新增团队指导模板
     *
     * @param title
     * @param teams
     * @param content
     * @param images
     */
    public void saveTeamGuidance(String doctor, String title, JSONArray teams, String content, String images) throws Exception {
        String templateCode = getCode();
        Date nowDate = new Date();
        String image = "";
        if (StringUtils.isNotEmpty(images)) {
//            只限本地路径上传到FastDFS
            image = CommonUtil.copyTempImage(images);
            System.out.println("images =====>" + image);
        }

        for (Object team : teams) {
            JSONObject teamJson = new JSONObject(team.toString());
            int teamId = teamJson.getInt("teamId");
            String teamName = teamJson.getString("teamName");
            //             团队内标题排重
            List<DoctorTeamGuidanceTemplate> teamGuidanceTemplates = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
            if (teamGuidanceTemplates.size() == 0) {
                DoctorTeamGuidanceTemplate doctorTeamGuidanceTemplate = new DoctorTeamGuidanceTemplate();
                doctorTeamGuidanceTemplate.setCreater(doctor);
                doctorTeamGuidanceTemplate.setCreateTime(nowDate);
                doctorTeamGuidanceTemplate.setCzrq(nowDate);
                doctorTeamGuidanceTemplate.setDel(1);
                doctorTeamGuidanceTemplate.setTeamId(teamId);
                doctorTeamGuidanceTemplate.setTeamName(teamName);
                doctorTeamGuidanceTemplate.setTitle(title);
                doctorTeamGuidanceTemplate.setTeamTemplateCode(templateCode);
                doctorTeamGuidanceTemplate.setUseTimes(0);

                doctorTeamGuidanceTemplateDao.save(doctorTeamGuidanceTemplate);
            } else {
                throw new Exception(teamName + "：团队标题重复!");
            }

        }

//            团队内标题不重复保存到团队模板详情表团队模板表
        DoctorTeamGuidanceDetail doctorTeamGuidanceDetail = new DoctorTeamGuidanceDetail();
        doctorTeamGuidanceDetail.setCode(templateCode);
        doctorTeamGuidanceDetail.setTitle(title);
        doctorTeamGuidanceDetail.setCreater(doctor);
        doctorTeamGuidanceDetail.setContent(content);
        doctorTeamGuidanceDetail.setCreateTime(nowDate);
        doctorTeamGuidanceDetail.setCzrq(nowDate);
        doctorTeamGuidanceDetail.setImagesUrl(image);

        doctorTeamGuidanceDetailDao.save(doctorTeamGuidanceDetail);

    }

    /**
     * 修改团队模板
     *
     * @param guidanceCode
     * @param title
     * @param teams
     * @param content
     * @param images
     * @throws Exception
     */
    public void modifyTeamGuidance(String doctor, String isLeader,int saveAsGuidance,Boolean isRepeat , String guidanceCode, String title,
                                     JSONArray teams, String content, String images) throws Exception {

//        首先身份验证
        DoctorTeamGuidanceDetail guidanceDetail = doctorTeamGuidanceDetailDao.findGuidanceDetail(guidanceCode);
        String creater = guidanceDetail.getCreater();
        Date nowDate = new Date();

//        图片地址需要处理
        String image = "";
        if (StringUtils.isNotEmpty(images)) {
            image = validateImages(images);
        }
        if (saveAsGuidance == 1) {
            //      保存为个人模板 去除个人模板标题重复 个人模板重复和修改是分开的互不影响
            //        验证模板名称唯一性
            List<DoctorGuidanceTemp> templates = guidanceTempDao.findByTitle(doctor, title);
            DoctorGuidanceTemp doctorGuidanceTemp = new DoctorGuidanceTemp();
            if (!isRepeat) {
                doctorGuidanceTemp.setCode(getCode());
                doctorGuidanceTemp.setImagesUrl(image);
                doctorGuidanceTemp.setCreateTime(nowDate);
                doctorGuidanceTemp.setContent(content);
                doctorGuidanceTemp.setModelName(title);
                doctorGuidanceTemp.setOwner(doctor);
                doctorGuidanceTemp.setLastTime(nowDate);
                doctorGuidanceTemp.setSendTimes(1);
                doctorGuidanceTempDao.save(doctorGuidanceTemp);
            }

            if ((!doctor.equals(creater)) && (!"1".equals(isLeader))) {
                throw new Exception("没有修改权限");
            }
            //                        数据库中拥有该模板的所有团队
            List<DoctorTeamGuidanceTemplate> teamIds = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
            List teamList = new ArrayList();
            List tempTeams = new ArrayList();
            for (DoctorTeamGuidanceTemplate team : teamIds) {
                teamList.add(team.getTeamId());
            }
            for (Object team : teams) {
                JSONObject teamJson = new JSONObject(team.toString());
                int teamId = teamJson.getInt("teamId");
                tempTeams.add(teamId);
                String teamName = teamJson.getString("teamName");
//                    团队内模板标题要去重复（去掉自身）
                List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
                if (list.size() <= 1) {
//                        直接失效原有团队模板对应关系  在重新新增以前没有的团队关系 发送次数要归0
                    if (teamList.contains(teamId)) {
//                            数据库有
                        doctorTeamGuidanceTemplateDao.modifyTeamGuidance(teamId, guidanceCode, title);
                    } else if (!teamList.contains(teamId)) {
                        //                        现在有，而数据库没有 要新增
                        DoctorTeamGuidanceTemplate doctorTeamGuidanceTemplate = new DoctorTeamGuidanceTemplate();
                        doctorTeamGuidanceTemplate.setCreater(doctor);
                        doctorTeamGuidanceTemplate.setCreateTime(nowDate);
                        doctorTeamGuidanceTemplate.setCzrq(nowDate);
                        doctorTeamGuidanceTemplate.setDel(1);
                        doctorTeamGuidanceTemplate.setTeamId(teamId);
                        doctorTeamGuidanceTemplate.setTeamName(teamName);
                        doctorTeamGuidanceTemplate.setTitle(title);
                        doctorTeamGuidanceTemplate.setTeamTemplateCode(guidanceCode);
                        doctorTeamGuidanceTemplate.setUseTimes(0);
                        doctorTeamGuidanceTemplateDao.save(doctorTeamGuidanceTemplate);
                    }
                } else {
                    throw new Exception(teamName + "：团队标题重复！");
                }
                //                直接修改团队模板后修改模板团队对应表
                doctorTeamGuidanceDetailDao.modifyTeamGuidanceDetail(title, content, image, guidanceCode);
            }
//                            数据库有，而现在没有
            teamList.removeAll(tempTeams);
            for (Object team : teamList) {
                doctorTeamGuidanceTemplateDao.deleteTeamGuidance(Integer.parseInt(team.toString()), guidanceCode);
            }



        } else if (saveAsGuidance == 0) {
            if ((!doctor.equals(creater)) && (!"1".equals(isLeader))) {
                throw new Exception("没有修改权限");
            }
            //                        数据库中拥有该模板的所有团队
            List<DoctorTeamGuidanceTemplate> teamIds = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
            List teamList = new ArrayList();
            List tempTeams = new ArrayList();
            for (DoctorTeamGuidanceTemplate team : teamIds) {
                teamList.add(team.getTeamId());
            }
            for (Object team : teams) {
                JSONObject teamJson = new JSONObject(team.toString());
                int teamId = teamJson.getInt("teamId");
                tempTeams.add(teamId);
                String teamName = teamJson.getString("teamName");
//                    团队内模板标题要去重复（去掉自身）
                List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
                if (list.size() <= 1) {
//                        直接失效原有团队模板对应关系  在重新新增以前没有的团队关系 发送次数要归0
                    if (teamList.contains(teamId)) {
//                            数据库有
                        doctorTeamGuidanceTemplateDao.modifyTeamGuidance(teamId, guidanceCode, title);
                    } else if (!teamList.contains(teamId)) {
                        //                        现在有，而数据库没有 要新增
                        DoctorTeamGuidanceTemplate doctorTeamGuidanceTemplate = new DoctorTeamGuidanceTemplate();
                        doctorTeamGuidanceTemplate.setCreater(doctor);
                        doctorTeamGuidanceTemplate.setCreateTime(nowDate);
                        doctorTeamGuidanceTemplate.setCzrq(nowDate);
                        doctorTeamGuidanceTemplate.setDel(1);
                        doctorTeamGuidanceTemplate.setTeamId(teamId);
                        doctorTeamGuidanceTemplate.setTeamName(teamName);
                        doctorTeamGuidanceTemplate.setTitle(title);
                        doctorTeamGuidanceTemplate.setTeamTemplateCode(guidanceCode);
                        doctorTeamGuidanceTemplate.setUseTimes(0);
                        doctorTeamGuidanceTemplateDao.save(doctorTeamGuidanceTemplate);
                    }
                } else {
                    throw new Exception(teamName + "：团队标题重复！");
                }
                //                直接修改团队模板后修改模板团队对应表
                doctorTeamGuidanceDetailDao.modifyTeamGuidanceDetail(title, content, image, guidanceCode);
            }
//                            数据库有，而现在没有
            teamList.removeAll(tempTeams);
            for (Object team : teamList) {
                doctorTeamGuidanceTemplateDao.deleteTeamGuidance(Integer.parseInt(team.toString()), guidanceCode);
            }
        }

    }

    /**
     * 根据医生所属的单个团队获取团队模板列表
     *
     * @param teamId
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public List getTeamGuidanceList(int teamId, int pageNo, int pageSize) throws Exception {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest request = new PageRequest(pageNo, pageSize, sort);

        List<DoctorTeamGuidanceTemplate> listGuidances = doctorTeamGuidanceTemplateDao.findGuidanceByTeamId(teamId, request);
        List list = new ArrayList();
        for (DoctorTeamGuidanceTemplate guidance : listGuidances) {
            Map map = new HashMap();
            String title = guidance.getTitle();
            int useTimes = guidance.getUseTimes();
            String teamTemplateCode = guidance.getTeamTemplateCode();
            map.put("teamTemplateCode", teamTemplateCode);
            map.put("title", title);
            map.put("useTimes", useTimes);
            list.add(map);
        }
        return list;
    }

    /**
     * 根据团队模板编码获取单个 有效的 模板详情
     *
     * @param guidanceCode
     * @return
     * @throws Exception
     */
    public JSONObject getTeamGuidanceDetail(int teamId, String guidanceCode) throws Exception {
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = "";
        String czrq = "";

        DoctorTeamGuidanceDetail guidanceDetail = doctorTeamGuidanceDetailDao.findGuidanceDetail(guidanceCode);
        List<DoctorTeamGuidanceTemplate> doctorTeamGuidanceTemplate = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
        List teamList = new ArrayList();
        for (DoctorTeamGuidanceTemplate teamGuidanceTemplate : doctorTeamGuidanceTemplate) {
            Map map = new HashMap();
            map.put("teamId", teamGuidanceTemplate.getTeamId());
            map.put("teamName", teamGuidanceTemplate.getTeamName());
            if (teamGuidanceTemplate.getTeamId() == teamId) {
                jsonObject.put("useTimes", teamGuidanceTemplate.getUseTimes());
            }
            teamList.add(map);
        }

        Date create = guidanceDetail.getCreateTime();
        Date cztime = guidanceDetail.getCzrq();
        if (create != null) {
            createTime = sdf.format(create);
        }
        if (cztime != null) {
            czrq = sdf.format(cztime);
        }

        jsonObject.put("id", guidanceDetail.getId() != null ? guidanceDetail.getId() : "");
        jsonObject.put("code", guidanceDetail.getCode() != null ? guidanceDetail.getCode() : "");
        jsonObject.put("creater", guidanceDetail.getCreater() != null ? guidanceDetail.getCreater() : "");
        jsonObject.put("title", guidanceDetail.getTitle() != null ? guidanceDetail.getTitle() : "");
        jsonObject.put("content", guidanceDetail.getContent() != null ? guidanceDetail.getContent() : "");
        jsonObject.put("imagesUrl", guidanceDetail.getImagesUrl() != null ? guidanceDetail.getImagesUrl() : "");
        jsonObject.put("createTime", createTime);
        jsonObject.put("czrq", czrq);
        jsonObject.put("teamList", teamList);
        return jsonObject;
    }

    /**
     * 删除团队所属的团队模板
     *
     * @param teamId
     * @param guidanceCode
     * @throws Exception
     */
    public void deleteTeamGuidance(String doctor, int deteleAll, Integer teamId, String guidanceCode) throws Exception {
        String str = "";
        if (deteleAll == 0) {
            doctorTeamGuidanceTemplateDao.deleteTeamGuidance(teamId, guidanceCode);
        } else {
//            删除该医生所有团队内该模板
            List<AdminTeam> teams = memberDao.findDoctorTeams(doctor);
            for (AdminTeam team : teams) {
                int teamCode = team.getId().intValue();
                doctorTeamGuidanceTemplateDao.deleteTeamGuidance(teamCode, guidanceCode);
            }
        }

    }

    /**
     * 给居民发送团队模板
     *
     * @param accessToken
     * @param patient
     * @param content
     * @param guidanceCode
     * @param images
     * @throws Exception
     */
    public void sendTeamGuidance(String accessToken, String dc, String patient, String content, String guidanceCode, String images, int teamId) throws Exception {
        String image = "";
        if (StringUtils.isNotEmpty(images)) {
            image = validateImages(images);
        }

        PatientHealthGuidance guidance = new PatientHealthGuidance();
        guidance.setContent(content);
        guidance.setDoctor(dc);
        guidance.setPatient(patient);
        Doctor doctor = doctorDao.findByCode(dc);
        guidance.setImages(image);

        // 保存
        if (patientHealthGuidanceService.add(guidance, accessToken) != null) {
            String sendImgs = "";
            if (StringUtils.isNotBlank(images)) {
                sendImgs = images;
            }
            Patient p = patientDao.findByCode(patient);
            String imcotent = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + sendImgs + "\",\"content\":\"" + CommonUtil.getSubString(guidance.getContent(), 0, 30) + "\"}";
            consultService.sendMucMessageBySingnType(dc, doctor.getName(), patient, imcotent, "4", p.getName());
            BusinessLogs.info(BusinessLogs.BusinessType.guidance, dc, patient, new JSONObject(guidance));
            //发送成功记录模板发送次数
            doctorTeamGuidanceTemplateDao.countSend(teamId, guidanceCode);
        }

    }

    /**
     * 校验图片本地路径掺杂网络路径，统一返回网路路径
     *
     * @param images
     * @throws Exception
     */
    public static String validateImages(String images) throws Exception {
        String imagePath = "";
        String imageUrls = "";
        String imageRow = "";
        String[] imgs = images.split(",");
        for (String image : imgs) {
            if (image.contains("http://")) {
                imageUrls += image + ",";
            } else {
                try {
                    imageRow += CommonUtil.copyTempImage(image) + ",";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        imagePath += imageUrls + imageRow;
        imagePath = imagePath.substring(0, imagePath.length() - 1);
        return imagePath;
    }

}
