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;

    /**
     * 新增团队指导模板
     *
     * @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();
        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(new Date());
                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(new Date());
        doctorTeamGuidanceDetail.setImagesUrl(image);

        doctorTeamGuidanceDetailDao.save(doctorTeamGuidanceDetail);

    }

    /**
     * 修改团队模板
     *
     * @param guidanceCode
     * @param title
     * @param teams
     * @param content
     * @param images
     * @throws Exception
     */
    public void modifyTeamGuidance(String doctor, int saveAsGuidance, String guidanceCode, String title, JSONArray teams, String content, String images) throws Exception {
//        图片地址需要处理
        String image = "";
        if (StringUtils.isNotEmpty(images)) {
            image = validateImages(images);
        }

        switch (saveAsGuidance) {
            case 1:
                //      保存为个人模板
                DoctorGuidanceTemp doctorGuidanceTemp = new DoctorGuidanceTemp();
                doctorGuidanceTemp.setCode(getCode());
                doctorGuidanceTemp.setImagesUrl(image);
                doctorGuidanceTemp.setCreateTime(new Date());
                doctorGuidanceTemp.setContent(content);
                doctorGuidanceTemp.setModelName(title);
                doctorGuidanceTemp.setOwner(doctor);
                doctorGuidanceTemp.setLastTime(new Date());
                doctorGuidanceTemp.setSendTimes(0);
                doctorGuidanceTempDao.save(doctorGuidanceTemp);
            case 0:
                for (Object team : teams) {
                    JSONObject teamJson = new JSONObject(team.toString());
                    int teamId = teamJson.getInt("teamId");
                    String teamName = teamJson.getString("teamName");
//                    团队内模板标题要去重复（去掉自身）
                    List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
                    if (list.size() <= 1) {
                        doctorTeamGuidanceTemplateDao.modifyTeamGuidance(teamId,guidanceCode, title);
                    } else {
                        throw new Exception(teamName + "：团队标题重复！");
                    }
                    //                直接修改团队模板后修改模板团队对应表
                    doctorTeamGuidanceDetailDao.modifyTeamGuidanceDetail(title, content, image, guidanceCode);
                }
                break;
        }

    }

    /**
     * 根据医生所属的单个团队获取团队模板列表
     *
     * @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;
    }

}
