package com.yihu.wlyy.web.doctor.template;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.PatientHealthStandard;
import com.yihu.wlyy.entity.template.DoctorGuidanceTemp;
import com.yihu.wlyy.entity.template.DoctorTeamGuidanceDetail;
import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import com.yihu.wlyy.repository.template.DoctorGuidanceTempDao;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.service.template.DoctorTeamGuidanceService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
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.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
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 java.util.*;

/**
 * 医生端、后端团队指导模板控制类
 */
@Controller
@RequestMapping(value = "/doctor/team/guidance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端&后端团队指导模板")
public class DoctorTeamGuidanceController extends WeixinBaseController {

    @Autowired
    private AdminTeamService adminTeamService;
    @Autowired
    private DoctorTeamGuidanceService doctorTeamGuidanceService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;

    /**
     * 获取医生所属的所有团队
     *
     * @return
     */
    @RequestMapping(value = "/getDoctorTeams", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取医生所属的所有团队")
    public String getHealthIndexHistory() {
        try {
            String doctorCode = getUID();
            List<AdminTeam> doctorTeams = adminTeamService.getDoctorTeams(doctorCode);
            List teamList = new ArrayList();
            for (AdminTeam AdminTeam : doctorTeams) {
                Map map = new HashMap();
                String teamName = AdminTeam.getName();
                Long teamId = AdminTeam.getId();
                map.put("teamName", teamName);
                map.put("teamId", teamId);
                teamList.add(map);
            }
            return write(200, "获取医生所属团队成功！", "teamList", teamList);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }

    /**
     * 根据医生所属的单个团队获取团队模板列表
     *
     * @param teamId
     * @return
     */
    @RequestMapping(value = "/getTeamGuidanceList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取单个团队模板列表")
    public String getTeamGuidanceList(@RequestParam int teamId,
                                      @RequestParam int pageNo,
                                      @RequestParam int pageSize) {
        try {
            List list = doctorTeamGuidanceService.getTeamGuidanceList(teamId, pageNo - 1, pageSize);
            return write(200, "获取团队模板列表成功！", "templateList", list);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }

    /**
     * 根据团队模板编码获取单个模板详情
     *
     * @return
     */
    @RequestMapping(value = "/getTeamGuidanceDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取单个模板详情")
    public String getTeamGuidanceDetail(
            @ApiParam(value = "团队编码")
            @RequestParam int teamId,
            @ApiParam(value = "团队模板编码")
            @RequestParam String teamTemplateCode) {
        try {
            JSONObject guidanceDetail = doctorTeamGuidanceService.getTeamGuidanceDetail(teamId, teamTemplateCode);
            return write(200, "获取模板详情成功！", "guidanceDetail", guidanceDetail);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }

    /**
     * 新增团队模板
     *
     * @param title    模板标题要排重，团队内不可重复
     * @param teamInfo 该模板所属的团队ID及名称 可能会有多个
     * @param content  模板内容，前端限10000，后端无限制
     * @param images   多图以，分隔，取值1-9图,
     * @return
     */
    @RequestMapping(value = "/saveTeamGuidance", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增团队模板")
    @ObserverRequired
    public String saveTeamGuidance(
            @ApiParam(value = "团队模板标题")
            @RequestParam String title,
            @ApiParam(value = "所属团队ID及名称json串", defaultValue = "[{\"teamName\":\"一农\",\"teamId\":212},{\"teamName\":\"一\",\"teamId\":21}]")
            @RequestParam String teamInfo,
            @ApiParam(value = "模板内容")
            @RequestParam String content,
            @ApiParam(value = "图片路径")
            @RequestParam(required = false) String images
    ) {
        try {
//            前端参数校验
            String doctor = getUID();
            JSONArray teams = new JSONArray(teamInfo);
            doctorTeamGuidanceService.saveTeamGuidance(doctor, title, teams, content, images);
            return write(200, "保存团队模板成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }

    /**
     * 修改团队模板
     *
     * @param saveAsGuidance 团队模板是否保存为个人模板 0否 1是
     * @param title          模板标题要排重，团队内不可重复
     * @param teamInfo       该模板所属的团队ID及名称 可能会有多个
     * @param content        模板内容，前端限10000，后端无限制
     * @param images         多图以，分隔，取值0-9图,
     * @return
     */
    @RequestMapping(value = "/modifyTeamGuidance", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    @ApiOperation("修改团队模板")
    public String modifyTeamGuidance(
            @ApiParam(value = "团队模板团队模板是否保存为个人模板", defaultValue = "0")
            @RequestParam int saveAsGuidance,
            @ApiParam(value = "要修改的团队模板编号")
            @RequestParam String guidanceCode,
            @ApiParam(value = "团队模板标题")
            @RequestParam String title,
            @ApiParam(value = "所属团队ID及名称json串", defaultValue = "[{\"teamName\":\"一农\",\"teamId\":212},{\"teamName\":\"一\",\"teamId\":21}]")
            @RequestParam String teamInfo,
            @ApiParam(value = "模板内容")
            @RequestParam String content,
            @ApiParam(value = "是否团队长")
            @RequestParam String isLeader,
            @ApiParam(value = "图片路径")
            @RequestParam(required = false) String images) {
        try {
//            新增修改权限，只有创建者和团队长才能修改
            String result = "";
            Boolean isRepeat = false;
            String doctor = getUID();
            List<DoctorGuidanceTemp> templates = guidanceTempDao.findByTitle(doctor, title);
            if (templates != null && templates.size() != 0) {
                isRepeat = true;
                result = "个人模板标题重复";
            }
            JSONArray teams = new JSONArray(teamInfo);
            doctorTeamGuidanceService.modifyTeamGuidance(doctor, isLeader, saveAsGuidance, isRepeat, guidanceCode, title, teams, content, images);
            String str = "";
            return write(200, "修改团队模板成功！", "result", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }

    }

    /**
     * 删除团队所属的团队模板
     *
     * @param deleteAll    0否 1是
     * @param teamId
     * @param guidanceCode
     * @return
     */
    @RequestMapping(value = "/deleteTeamGuidance", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("删除团队所属的团队模板")
    @ObserverRequired
    public String deleteTeamGuidance(
            @ApiParam(value = "是否删除存在该模板的所有团队")
            @RequestParam int deleteAll,
            @ApiParam(value = "团队ID")
            @RequestParam(required = false) Integer teamId,
            @ApiParam(value = "团队模板编码")
            @RequestParam String guidanceCode) {
        try {
            String doctor = getUID();
            doctorTeamGuidanceService.deleteTeamGuidance(doctor, deleteAll, teamId, guidanceCode);
            return write(200, "删除模板成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }

    /**
     * 发送团队模板给居民
     *
     * @param patient
     * @param content
     * @param guidanceCode
     * @param images
     * @return
     */
    @RequestMapping(value = "/sendTeamGuidance", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("发送团队模板给居民")
    @ObserverRequired
    public String sendTeamGuidance(
            @ApiParam(value = "要发送的居民code")
            @RequestParam String patient,
            @ApiParam(value = "团队模板内容")
            @RequestParam String content,
            @ApiParam(value = "团队id")
            @RequestParam String teamId,
            @ApiParam(value = "团队模板code")
            @RequestParam String guidanceCode,
            @ApiParam(value = "团队模板图片")
            @RequestParam(required = false) String images) {
        try {
            String accessToken = getAccessToken();
            String doctor = getUID();
            JSONArray teams = new JSONArray(teamId);
            for (Object team : teams) {
                JSONObject teamJson = new JSONObject(team.toString());
                int teamCode = teamJson.getInt("teamId");
                doctorTeamGuidanceService.sendTeamGuidance(accessToken, doctor, patient, content, guidanceCode, images,teamCode);
            }
            return write(200, "发送成功！");
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }

}
