package com.yihu.wlyy.service.template;

import com.yihu.wlyy.entity.template.DoctorGuidanceTemp;
import com.yihu.wlyy.repository.template.DoctorGuidanceTempDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.CommonUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 医生健康指导模板
 * <p>
 * Created by lyr-pc on 2017/2/3.
 */
@Service
@Transactional
public class DoctorGuidanceTempService extends BaseService {

    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 记录医生健康指导模板使用次数
     *
     * @param modelCode 健康指导模板编码
     */
    public void countSend(String modelCode) {
        synchronized (this) {
            String sql = "UPDATE wlyy_doctor_guidance_temp  " +
                    "SET send_times=send_times+1 " +
                    "WHERE CODE=?";
            jdbcTemplate.update(sql, modelCode);
        }
    }

    /**
     * 查询单个指导模板详情
     *
     * @param modelCode
     * @return
     * @throws Exception
     */
    public JSONObject listDetail(String modelCode) throws Exception {
        String sql = "SELECT wdgt.`model_name`,wdgt.`content`,wdgt.`images_url`,wdgt.`create_time`,wdgt.`send_times` " +
                "FROM wlyy_doctor_guidance_temp wdgt " +
                "WHERE wdgt.`code`=?";
        Map temp = (Map) jdbcTemplate.queryForMap(sql, modelCode);
        String modelName = (String) temp.get("model_name");
        String content = (String) temp.get("content");
        String imagesUrl = (String) temp.get("images_url");
//        多图按逗号分割保存成数组
        String[] imagesArray = null;
        if (imagesUrl != null) {
            imagesArray = imagesUrl.split(",");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = (Date) temp.get("create_time");
        String dateTime = sdf.format(createTime);
        String sendTimes = (String) temp.get("send_times").toString();
        JSONObject json = new JSONObject();
        json.put("modelName", modelName);
        json.put("content", content);
        json.put("imagesUrls", imagesArray);
        json.put("createTime", dateTime);
        json.put("sendTimes", sendTimes);
        return json;
    }

    /**
     * 添加指导模板
     *
     * @param doctor  医生
     * @param content 指导内容
     * @return
     */
    public DoctorGuidanceTemp add(String doctor, String content, String modelName, String imagesUrl) {
        DoctorGuidanceTemp guidanceTemp = new DoctorGuidanceTemp();
        String imageUrls = "";
        String imageRow = "";

        guidanceTemp.setCode(getCode());
        guidanceTemp.setOwner(doctor);
        guidanceTemp.setContent(content);
        guidanceTemp.setSendTimes(0);
        guidanceTemp.setCreateTime(new Date());

        guidanceTemp.setModelName(modelName);

        if (imagesUrl == null || "".equals(imagesUrl)) {
            imagesUrl = null;
        } else {
            String[] images = imagesUrl.split(",");
            for (String image : images) {
                if (image.contains("http://")) {
                    imageUrls += image + ",";
                } else {
                    try {
                        imageRow += CommonUtil.copyTempImage(image) + ",";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

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

        guidanceTemp.setImagesUrl(imagesUrl);

        return guidanceTempDao.save(guidanceTemp);
    }

    /**
     * 修改指导模板
     *
     * @param code    模板编码
     * @param content 指导内容
     * @return
     */
    public DoctorGuidanceTemp modify(String code, String modelName, String content, String imagesUrl) throws Exception {
        DoctorGuidanceTemp guidanceTemp = guidanceTempDao.findByCode(code);
        String imageUrls = "";
        String imageRow = "";

        if (guidanceTemp == null) {
            throw new Exception("模板不存在");
        }

        guidanceTemp.setModelName(modelName);
        guidanceTemp.setContent(content);

        if (imagesUrl == null || "".equals(imagesUrl)) {
            imagesUrl = null;
        } else {
            String[] images = imagesUrl.split(",");
            for (String image : images) {
                if (image.contains("http://")) {
                    imageUrls += image + ",";
                } else {
                    try {
                        imageRow += CommonUtil.copyTempImage(image) + ",";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

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

        guidanceTemp.setImagesUrl(imagesUrl);

        return guidanceTempDao.save(guidanceTemp);
    }

    /**
     * 删除指导模板
     *
     * @param code 模板编码
     * @return
     */
    public int delete(String code) throws Exception {
        String[] codes = code.split(",");

        if (codes != null && codes.length > 0) {
            for (String temp : codes) {
                String sql = "SELECT t.owner FROM wlyy_doctor_guidance_temp t WHERE t.code=?";
                String owner = jdbcTemplate.queryForObject(sql, String.class, temp);
                if (!"system".equals(owner)) {
                    guidanceTempDao.deleteByCode(temp);
                }

            }
        }

        return 1;
    }

    /**
     * 查询指导模板
     *
     * @param doctor 医生
     * @param type   模板类型
     * @return
     */
    public List<Map<String, Object>> list(String doctor, String type, int pageSize, int pageNo) throws Exception {
        Page<DoctorGuidanceTemp> temps = null;
        PageRequest pageRequest = new PageRequest(pageNo, pageSize);
        List<Map<String, Object>> listMap = new ArrayList<>();

        if (type.equals("1")) {
            temps = guidanceTempDao.findByOwner("system", pageRequest);

            List<DoctorGuidanceTemp> list = temps.getContent();
            for (int i = 0; i < list.size(); i++) {
                DoctorGuidanceTemp dgt = list.get(i);
                Map<String, Object> tem = new HashMap<>();
                tem.put("code", dgt.getCode());
                tem.put("owner", dgt.getOwner());
                tem.put("sendTimes", dgt.getSendTimes());
                tem.put("lastTime", dgt.getLastTime());
                tem.put("modelName", dgt.getModelName());
                listMap.add(tem);
            }
        } else if (type.equals("2")) {
            temps = guidanceTempDao.findByOwner(doctor, pageRequest);
            List<DoctorGuidanceTemp> list = temps.getContent();
            for (int i = 0; i < list.size(); i++) {
                DoctorGuidanceTemp dgt = list.get(i);
                Map<String, Object> tem = new HashMap<>();
                tem.put("code", dgt.getCode());
                tem.put("owner", dgt.getOwner());
                tem.put("sendTimes", dgt.getSendTimes());
                tem.put("lastTime", dgt.getLastTime());
                tem.put("modelName", dgt.getModelName());
                listMap.add(tem);
            }
        } else {
            temps = guidanceTempDao.findByOwnerAndSystem(doctor, pageRequest);
            List<DoctorGuidanceTemp> list = temps.getContent();
            for (int i = 0; i < list.size(); i++) {
                DoctorGuidanceTemp dgt = list.get(i);
                Map<String, Object> tem = new HashMap<>();
                tem.put("code", dgt.getCode());
                tem.put("owner", dgt.getOwner());
                tem.put("sendTimes", dgt.getSendTimes());
                tem.put("lastTime", dgt.getLastTime());
                tem.put("modelName", dgt.getModelName());
                listMap.add(tem);
            }
        }

        return listMap;
    }

}
