package com.yihu.wlyy.web.patient.archives;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.wlyy.config.FastDFSConfig;
import com.yihu.wlyy.service.app.archives.PatientEventService;
import com.yihu.wlyy.service.app.archives.PatientRecordService;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.fastdfs.FastDFSUtil;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by hzp on 2016/11/24.
 */
@Controller
@RequestMapping(value = "/patient/archives", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-健康档案服务接口")
public class PatientArchivesController extends WeixinBaseController {

    @Autowired
    private PatientRecordService patientRecordService;

    @Autowired
    private PatientEventService patientEventService;


    @ApiOperation("获取门诊记录/住院记录(基卫+APP)")
    @RequestMapping(value = "/event", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getAllEvent(@ApiParam(name="type",value="类型",defaultValue = "")
                              @RequestParam(value="type",required = false) String type,
                              @ApiParam(name="page",value="第几页",defaultValue = "1")
                              @RequestParam(value="page",required = true) String page,
                              @ApiParam(name="pageSize",value="每页几行",defaultValue = "10")
                              @RequestParam(value="pageSize",required = true) String pageSize,
                              @ApiParam(name="lastTime",value="最后一条时间",defaultValue = "2010-10-10 00:00:00")
                              @RequestParam(value="lastTime",required = false) String lastTime) {
        try {
            List<Map<String,String>> result = patientRecordService.getAllEvent(getUID(),type,page,pageSize,lastTime);

            return write(200, "获取就诊记录成功！", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取门/急诊数据失败！");
        }
    }

    @RequestMapping(value = "/event/healthData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取健康档案详情（基卫）")
    public String getHealthData(@ApiParam(name="event",value="事件ID",defaultValue = "")
                                @RequestParam(value="event",required = true) String event,
                                @ApiParam(name="catalog",value="档案类型",defaultValue = "")
                                @RequestParam(value="catalog",required = true) String catalog,
                                @ApiParam(name="serial",value="该类别顺序号，默认填1",defaultValue = "1")
                                @RequestParam(value="serial",required = true) String serial) {
        try {
            String result = patientRecordService.getHealthData(getUID(), event, catalog, serial);

            return write(200, "获取健康档案详情成功！", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取健康档案详情失败！");
        }
    }

    @RequestMapping(value = "/event/catalog", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("通过事件号获取档案类型列表（基卫）")
    public String getEventCatalog(@ApiParam(name="event",value="事件ID",defaultValue = "")
                                @RequestParam(value="event",required = true) String event) {
        try {
            List<Map<String,String>> result = patientRecordService.getEventCatalog(getUID(),event);

            return write(200, "通过事件号获取档案类型列表成功！", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }


    @RequestMapping(value = "/event/drug", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取用药记录（基卫）")
    public String getDrugsList(@ApiParam(name="page",value="第几页",defaultValue = "1")
                                   @RequestParam(value="page",required = true) String page,
                               @ApiParam(name="pageSize",value="每页几行",defaultValue = "10")
                                   @RequestParam(value="pageSize",required = true) String pageSize) {
        try {
            String result = patientRecordService.getDrugsListPage(getUID(), page, pageSize);     //"P20161008001"

            return write(200, "获取用药记录成功！", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取用药记录失败！");
        }
    }

    @ApiOperation("获取检查检验报告(基卫+APP)")
    @RequestMapping(value = "/event/report", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getReportList(@ApiParam(name="page",value="第几页",defaultValue = "1")
                                    @RequestParam(value="page",required = true) String page,
                                @ApiParam(name="pageSize",value="每页几行",defaultValue = "10")
                                    @RequestParam(value="pageSize",required = true) String pageSize)
    {
        try {
            List<Map<String,String>> result = patientRecordService.getExamAndLabReport(getUID(), page, pageSize);

            return write(200, "获取检查检验报告成功！", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取检查检验报告失败！");
        }
    }

    /******************************************* 就诊事件管理 **********************************************************/
    @RequestMapping(value = "/event/detail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取就诊事件详情")
    public String getEventDetail(@ApiParam(name="event",value="事件ID",defaultValue = "")
                                 @RequestParam(value="event",required = true) String event)
    {
        try {
            JSONObject result = patientEventService.getEventDetail(event);

            return write(200, "获取就诊事件详情成功！", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取就诊事件详情失败！");
        }
    }

    @RequestMapping(value = "/event/save", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("保存就诊事件详情")
    public String saveEventDetail(@ApiParam(name="data",value="就诊事件json数据",defaultValue = "")
                                 @RequestParam(value="data",required = true) String data)
    {
        try {
            patientEventService.saveEventDetail(data);

            return write(200, "保存就诊事件成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存就诊事件失败！");
        }
    }

    @RequestMapping(value = "/event/delete", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("删除就诊事件")
    public String deleteEvent(@ApiParam(name="event",value="就诊事件id",defaultValue = "")
                                  @RequestParam(value="event",required = true) Long event)
    {
        try {
            patientEventService.deleteEvent(event);

            return write(200, "删除就诊事件成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, "删除就诊事件失败！");
        }
    }

    @RequestMapping(value = "/event/uploadImg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("单张上传图片")
    public String uploadImg(@ApiParam(name="mediaId",value="微信图片标识",defaultValue = "wL1vfE9g1fiRCl5xd-Xotl1XycWQ9mwigDLUv-S0Kmde-pXNrlySKbf5RM5SwwFl")
                            @RequestParam(value="mediaId",required = true) String mediaId)
    {
        try {
            String url ="";
            FastDFSUtil fastDFSUtil = new FastDFSConfig().fastDFSUtil();
            InputStream wxImg = getInputStream(mediaId);
            ObjectNode result = fastDFSUtil.upload(wxImg, "jpg", "");
            wxImg.close();
            String serverUrl = SystemConf.getInstance().getSystemProperties().getProperty("fastdfs_file_url");
            if (result != null) {
                url = serverUrl
                        + result.get("groupName").toString().replaceAll("\"", "") + "/"
                        + result.get("remoteFileName").toString().replaceAll("\"", "");
            }
            else{
                return write(-1, "图片上传失败！");
            }

            return write(200, "图片上传成功！","url", url);
        } catch (Exception e) {
            return invalidUserException(e,-1, "图片上传失败！");
        }
    }


    @RequestMapping(value = "/event/img/delete", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("删除就诊事件图片")
    public String deleteEventImg(@ApiParam(name="id",value="就诊事件图片id",defaultValue = "")
                              @RequestParam(value="id",required = true) Long id)
    {
        try {
            patientEventService.deleteEventImg(id);

            return write(200, "删除就诊事件图片成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, "删除就诊事件图片失败！");
        }
    }

    @RequestMapping(value = "/event/img/add", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增就诊事件图片")
    public String addEventImg(@ApiParam(name="eventId",value="就诊事件id",defaultValue = "")
                                 @RequestParam(value="eventId",required = true) Long eventId,
                              @ApiParam(name="imgType",value="图片类别",defaultValue = "")
                              @RequestParam(value="imgType",required = true) String imgType,
                              @ApiParam(name="imgLabel",value="图片标签",defaultValue = "")
                                  @RequestParam(value="imgLabel",required = true) String imgLabel,
                              @ApiParam(name="imgUrl",value="图片路径",defaultValue = "")
                                  @RequestParam(value="imgUrl",required = true) String imgUrl)
    {
        try {
            patientEventService.addEventImg(eventId,imgType,imgLabel,imgUrl);

            return write(200, "新增就诊事件图片成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增就诊事件图片失败！");
        }
    }

    @RequestMapping(value = "/event/img/edit", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("修改就诊事件图片")
    public String editEventImg(@ApiParam(name="id",value="就诊事件图片id",defaultValue = "")
                              @RequestParam(value="id",required = true) Long id,
                              @ApiParam(name="imgType",value="图片类别",defaultValue = "")
                              @RequestParam(value="imgType",required = true) String imgType,
                              @ApiParam(name="imgLabel",value="图片标签",defaultValue = "")
                              @RequestParam(value="imgLabel",required = true) String imgLabel)
    {
        try {
            patientEventService.editEventImg(id,imgType,imgLabel);

            return write(200, "修改就诊事件图片成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, "修改就诊事件图片失败！");
        }
    }
}
