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

import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.sign.SignWebService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 患者所属标签控制类
 * <p>
 * Created by lyr on 2016/10/9.
 */
@RestController
@RequestMapping(value = "/doctor/patient_label_info")
@Api("居民管理")
public class SignPatientLabelInfoController extends BaseController {

    @Autowired
    SignPatientLabelInfoService labelInfoService;
    @Autowired
    SignWebService signWebService;
    @Autowired
    PatientService patientService;

    /**
     * 根据姓名，地址，身份证号搜索团队内居民
     *
     * @param filter   筛选关键字
     * @param teamCode 团队编码
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "getPatientByParams", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("由姓名|地址|身份证号搜索签约居民")
    public String getPatientByParams(@RequestParam String filter,
                                     @RequestParam String teamCode,
                                     @RequestParam int page,
                                     @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索条件不能为空！");
            }
            if (StringUtils.isEmpty(teamCode)) {
                return error(-1, "团队不能为空！");
            }
            long team = Long.parseLong(teamCode);
            JSONArray temp = labelInfoService.getPatientByParams(getUID(), filter, null, null, team, null, null, page, pagesize);
            return write(200, "查询成功！", "data", temp);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 根据姓名，地址，身份证号搜索团队内未分配健管的居民
     *
     * @param filter   筛选关键字
     * @param teamCode 团队编码
     * @return
     */
    @RequestMapping(value = "getPatientUnSign", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("由姓名|地址|身份证号搜索团队内未分配健管的居民")
    public String getPatientUnSign(@RequestParam String filter,
                                   @RequestParam String teamCode,
                                   @RequestParam int page,
                                   @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索条件不能为空！");
            }
            if (StringUtils.isEmpty(teamCode)) {
                return error(-1, "团队不能为空！");
            }
            long team = Long.parseLong(teamCode);
            List list = labelInfoService.findNoHealthSignFamilyHealth(filter, team,page,pagesize);
            return write(200, "查询成功！", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    @RequestMapping(value = "getPatientByNameOrIdcard", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("医生端搜索签约居民")
    public String search(@RequestParam(required = true) String str) {
        try {
            if (StringUtils.isEmpty(str)) {
                return error(-1, "居民不能为空！");
            }
            JSONObject temp = labelInfoService.search(str, getUID());
            return write(200, "查询成功！", "data", temp);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败！");
        }
    }

    /**
     * 查询居民信息
     *
     * @param patient 患者
     * @return
     */
    @RequestMapping(value = "/patient")
    public String getPatient(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不能为空");
            }
            JSONObject p = labelInfoService.getPatient(patient);
            return write(200, "查询成功", "data", p);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个团队的某个标签下的患者信息
     *
     * @param labelCode 标签code
     * @param labelType 标签类型
     * @param teamCode  团队code
     * @param page      第几页
     * @param pagesize  页大小
     * @return
     */
    @RequestMapping(value = "/patients_by_label")
    public String getPatientInfoByLabel(@RequestParam(required = false) String labelCode,
                                        @RequestParam(required = false) String labelType,
                                        @RequestParam(required = false)Long teamCode,
                                        @RequestParam(required = false)int page,
                                        @RequestParam(required = false)int pagesize) {
        try {
            if (StringUtils.isEmpty(labelCode)) {
                return error(-1, "标签cdoe不能为空");
            }
            if (StringUtils.isEmpty(labelType)) {
                return error(-1, "标签类型不能为空");
            }
            if (StringUtils.isEmpty(String.valueOf(teamCode)) || teamCode < 1) {
                return error(-1, "团队cdoe不能为空");
            }

            page = page - 1;
            if(labelType.equals("9")){
                JSONObject jsonObject = signWebService.getOverDuePatients(labelCode,teamCode,getUID(),page,pagesize);
                return write(200, "查询成功", "data", jsonObject);
            }

            JSONArray result = labelInfoService.getPatientByLabel(getUID(), labelCode, labelType, teamCode, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取团队下的居民(当前医生下)
     *
     * @param teamCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/patients_by_team")
    public String getPatientInfoByTeam(Long teamCode,
                                       @RequestParam(required = false) String exLabelCode,
                                       @RequestParam(required = false) String exLabelType,
                                       int page, int pagesize) {
        try {
            if (teamCode == null || teamCode < 1) {
                return error(-1, "团队cdoe不能为空");
            }

            if (!StringUtils.isEmpty(exLabelCode) && StringUtils.isEmpty(exLabelType)) {
                return error(-1, "过滤标签参数不为空时过滤标签类型不能为空");
            }

            page = page - 1;
            JSONArray result = labelInfoService.getPatientByTeamCode(getUID(), teamCode, exLabelCode, exLabelType, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取团队下的居民
     *
     * @param teamCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/team_patient")
    public String getTeamPatient(@RequestParam(required = true) Long teamCode,
                                 @RequestParam(required = false) String labelCode,
                                 @RequestParam(required = false) String labelType,
                                 @RequestParam(required = true) int page, @RequestParam(required = true) int pagesize) {
        try {
            if (teamCode == null || teamCode < 1) {
                return error(-1, "团队cdoe不能为空");
            }

            if (!StringUtils.isEmpty(labelCode) && StringUtils.isEmpty(labelType)) {
                return error(-1, "过滤标签参数不为空时过滤标签类型不能为空");
            }

            page = page > 0 ? page - 1 : 0;

            if(labelType.equals("9")){
                JSONObject jsonObject = signWebService.getOverDuePatientsByTeam(labelCode,teamCode,page,pagesize);
                return write(200, "查询成功", "data", jsonObject);
            }


            JSONArray result = labelInfoService.getPatientByTeamCodeExitDoctor(teamCode, labelCode, labelType, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * pc端im使用
     * @return
     */
    @RequestMapping(value = "/doctor_team_patient", method = RequestMethod.GET)
    @ApiOperation(value = "获取医生所有团队的所有居民")
    public String getDoctorTeamsPatient(){
        try {
            JSONArray result = labelInfoService.getSignPatientsByDoctorCode(getUID());
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个团队的某个标签类型下各标签患者数
     *
     * @param labelType 标签类型
     * @param teamCode  团队code
     * @return
     */
    @RequestMapping(value = "/label_patient_amount")
    public String getPatientAmountByLabelType(@RequestParam(required = false)String labelType, @RequestParam(required = false) Long teamCode) {
        try {
            if (StringUtils.isEmpty(labelType)) {
                return error(-1, "标签类型不能为空");
            }

            if (teamCode == null) {
                teamCode = 0L;
            }

            //计算年度数目
            if(labelType.equals("9")){
                JSONObject r= signWebService.getRenewYearCountByDoctor(teamCode,getUID());
                return write(200, "查询成功", "data", r);
            }

            if(labelType.equals("1")&&teamCode!=0L){
                JSONArray r= patientService.getSignByDoctorCodeGpbyServer(getUID(),teamCode+"");
                //JSONArray r= patientService.getSignByDoctorCodeGpbyServer("xh1D201703150222",teamCode+"");
                return write(200, "查询成功", "data", r);
            }

            JSONArray result = labelInfoService.getPatientAmountByLabelType(getUID(), labelType, teamCode);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            error(e);
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个团队的某个标签类型下各标签患者数/分组统计
     *
     * @param labelType 标签类型
     * @param teamCode  团队code
     * @return
     */
    @RequestMapping(value = "/label_team_amount")
    public String getPatientAmountByTeam(@RequestParam(required = false) String labelType, @RequestParam(required = true) Long teamCode) {
        try {
            if (StringUtils.isEmpty(labelType)) {
                labelType = "0";
            }

            if (teamCode == null) {
                teamCode = 0L;
            }
            if("1".equals(labelType)){
                JSONArray result =patientService.getSignByTeamCodeGpbyServer(teamCode);
                return  write(200, "查询成功", "data", result);
            }

            //计算年度数目
            if(labelType.equals("9")){
                JSONObject r= signWebService.getRenewYearCount(teamCode);
                return write(200, "查询成功", "data", r);
            }

            JSONArray result = labelInfoService.getPatientAmountByTeamGroupLable(teamCode, labelType);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个团队的患者数/汇总
     *
     * @param teamCode 团队code
     * @return
     */
    @RequestMapping(value = "/team_amount")
    public String getAmountByTeam(@RequestParam(required = true) Long teamCode) {
        try {
            int result = labelInfoService.getPatientAmountByTeam(teamCode);
            int resultFocus = labelInfoService.getPatientFocusAmountByTeam(teamCode);
            JSONObject re = new JSONObject();
            re.put("amount", result);
            re.put("focusAmount", resultFocus);

            return write(200, "查询成功", "data", re);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 患者标签更新
     *
     * @param patient 患者
     * @param health  健康情况
     * @param disease 疾病情况
     * @param custom  自定义情况
     * @return
     */
    @RequestMapping(value = "/patient_label_update")
    @ObserverRequired
    public String setPatientLabels(@RequestParam(required = false) String patient,
                                   @RequestParam(required = false) String health,
                                   @RequestParam(required = false) String disease,
                                   @RequestParam(required = false) String custom) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "患者不能为空");
            }
            if (StringUtils.isEmpty(health)) {
                return error(-1, "健康情况标签不能为空");
            }
            //xh1D201703150222
            int result = labelInfoService.setPatientLabels(patient, "", "", health, disease, custom, getUID(), getUID());
//            int result = labelInfoService.setPatientLabels(patient, "", "", health, disease, custom, "xh1D201703150222", "xh1D201703150222");

            if (result == 0) {
                return error(-1, "查不到患者信息");
            }
            if (result == -1) {
                return error(-1, "标签不存在");
            }
            if (result == -2) {
                return error(-1, "健康情况标签不能为空");
            }
            if (result == -3) {
                return error(-1, "三师疾病不能更改");
            }
            if (result == -4) {
                return error(-1, "医生与居民没有签约关系");
            }
            if (result == 1) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            error(e);
            return error(-1, "更新失败");
        }
    }

    /**
     * 查询某个患者的某类标签
     *
     * @param patient   患者
     * @param labelType 标签类型
     * @return
     */
    @RequestMapping(value = "/patient_label")
    public String getPatientLabelByLabelType(@RequestParam String patient,
                                             @RequestParam(required = false) String labelType,
                                             @RequestParam(required = false, defaultValue = "0") Long teamCode) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "患者不能为空");
            }
            //D2016008240002
            JSONArray labels = labelInfoService.getPatientLabelByLabelTypeAndTeamCode(patient, labelType, teamCode, getUID());
            //JSONArray labels = labelInfoService.getPatientLabelByLabelTypeAndTeamCode(patient, labelType, teamCode, "xh1D201703150222");
            return write(200, "查询成功", "data", labels);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个患者的某类标签根据团队和当前医生
     *
     * @param filter 过滤字段
     * @return
     */
    @RequestMapping(value = "/patient_search")
    public String searchPatientByNameOrLabel(@RequestParam(required = true) String filter,
                                             @RequestParam(required = false) String labelCode,
                                             @RequestParam(required = false) String labelType,
                                             @RequestParam(required = false) Long teamCode,
                                             @RequestParam(required = false) String exLabelCode,
                                             @RequestParam(required = false) String exLabelType,
                                             @RequestParam(required = true) int page, @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索字段不能为空");
            }

            if (!StringUtils.isEmpty(labelCode) && StringUtils.isEmpty(labelType)) {
                return error(-1, "标签参数不为空时标签类型不能为空");
            }

            if (!StringUtils.isEmpty(exLabelCode) && StringUtils.isEmpty(exLabelType)) {
                return error(-1, "过滤标签参数不为空时过滤标签类型不能为空");
            }

            if (teamCode == null) {
                teamCode = 0L;
            }

            page = page - 1;

            JSONArray result = labelInfoService.searchPatientByNameOrLabel(getUID(), filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);
            //JSONArray result = labelInfoService.searchPatientByNameOrLabel("test00000000005", filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个患者的某类标签根据团队和当前医生
     *
     * @param filter 过滤字段
     * @return
     */
    @RequestMapping(value = "/patient_search_Overdue")
    public String searchPatientByNameOrLabelOverdue(@RequestParam(required = true) String filter,
                                             @RequestParam(required = false) String labelCode,
                                             @RequestParam(required = false) String labelType,
                                             @RequestParam(required = false) Long teamCode,
                                             @RequestParam(required = false) String exLabelCode,
                                             @RequestParam(required = false) String exLabelType,
                                             @RequestParam(required = true) int page, @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索字段不能为空");
            }

            if (!StringUtils.isEmpty(labelCode) && StringUtils.isEmpty(labelType)) {
                return error(-1, "标签参数不为空时标签类型不能为空");
            }

            if (!StringUtils.isEmpty(exLabelCode) && StringUtils.isEmpty(exLabelType)) {
                return error(-1, "过滤标签参数不为空时过滤标签类型不能为空");
            }

            if (teamCode == null) {
                teamCode = 0L;
            }

            page = page - 1;

            JSONArray result = labelInfoService.searchPatientByNameOrLabelOverdue(getUID(), filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);
            //JSONArray result = labelInfoService.searchPatientByNameOrLabel("test00000000005", filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }



    @RequestMapping(value = "/patient_search_all", method = RequestMethod.GET)
    @ApiOperation("根据姓名搜索所有团队下居民（根据团队和当前医生）")
    public String searchPatients(@RequestParam(required = true) String filter,
                                 @RequestParam(required = false, defaultValue = "0") long teamCode,
                                 @RequestParam(required = false, defaultValue = "0") int page,
                                 @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "查询参数不能为空");
            }

            JSONArray result = labelInfoService.searchTeamsPatients(filter, getUID(), teamCode, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 查询某个患者的某类标签（根据团队）
     *
     * @param filter 过滤字段
     * @return
     */
    @RequestMapping(value = "/patient_search_exitdoc")
    public String searchPatientByNameOrLabelExitDoc(@RequestParam(required = true) String filter,
                                                    @RequestParam(required = false) String labelCode,
                                                    @RequestParam(required = false) String labelType,
                                                    @RequestParam(required = true) Long teamCode,
                                                    @RequestParam(required = false) String exLabelCode,
                                                    @RequestParam(required = false) String exLabelType,
                                                    @RequestParam(required = true) int page, @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索字段不能为空");
            }

            if (!StringUtils.isEmpty(labelCode) && StringUtils.isEmpty(labelType)) {
                return error(-1, "标签参数不为空时标签类型不能为空");
            }

            if (!StringUtils.isEmpty(exLabelCode) && StringUtils.isEmpty(exLabelType)) {
                return error(-1, "过滤标签参数不为空时过滤标签类型不能为空");
            }

            if (teamCode == null) {
                teamCode = 0L;
            }

            page = page > 0 ? page - 1 : 0;

            JSONArray result = labelInfoService.searchPatientByNameOrLabel(filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    @RequestMapping(value = "/patient_search_all_exitdoc", method = RequestMethod.GET)
    @ApiOperation("根据姓名搜索所有团队下居民（根据团队）")
    public String searchPatientsExitDoc(@RequestParam(required = true) String filter,
                                        @RequestParam(required = true, defaultValue = "0") long teamCode,
                                        @RequestParam(required = false, defaultValue = "0") int page,
                                        @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "查询参数不能为空");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = labelInfoService.searchTeamsPatients(filter, teamCode, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 签约过期的居民
     * @param filter
     * @param teamCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/patient_search_all_exitdoc_overdue", method = RequestMethod.GET)
    @ApiOperation("根据姓名搜索所有团队下居民（根据团队）")
    public String searchPatientsExitDocOverdue(@RequestParam(required = true) String filter,
                                        @RequestParam(required = true, defaultValue = "0") long teamCode,
                                        @RequestParam(required = false, defaultValue = "0") int page,
                                        @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "查询参数不能为空");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = labelInfoService.searchTeamsPatientsOverdue(filter, teamCode, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 添加居民到某个标签
     *
     * @param patient   患者
     * @param labelCode 标签code
     * @param labelType 标签类型
     * @return
     */
    @RequestMapping(value = "/patient_label_add")
    @ObserverRequired
    public String addPatientLabel(String patient, String labelCode, String labelType) {
        try {
            if (StringUtils.isEmpty(String.valueOf(patient))) {
                return error(-1, "患者不能为空");
            }
            if (StringUtils.isEmpty(labelCode)) {
                return error(-1, "标签cdoe不能为空");
            }
            if (StringUtils.isEmpty(labelType)) {
                return error(-1, "标签类型不能为空");
            }

            int result = labelInfoService.addPatientsLabel(patient, labelCode, labelType);

            if (result == -1) {
                return error(-1, "患者不存在");
            } else if (result == -2) {
                return error(-1, "患者已在此标签");
            } else if (result == -3) {
                return error(-1, "标签不存在");
            } else if (result == 1) {
                return error(200, "添加成功");
            } else {
                return error(-1, "添加失败");
            }
        } catch (Exception e) {
            return error(-1, "添加失败");
        }
    }

    /**
     * 新增标签并分配患者
     *
     * @param labelName 标签名称
     * @param teamCode  团队Code
     * @param patients  患者
     * @return
     */
    @RequestMapping(value = "/label_and_patients_add")
    @ObserverRequired
    public String addLabelAndPatient(String labelName, Long teamCode, @RequestParam(required = false) String patients) {
        try {
            if (StringUtils.isEmpty(labelName)) {
                return error(-1, "标签名称不能为空");
            }
            if (teamCode == null || teamCode < 1) {
                return error(-1, "团队code不能为空");
            }

            if (labelName.equals("孕产妇") || labelName.equals("儿童")) {
                return error(-1, "该标签名称已存在");
            }

            int result = labelInfoService.addLabelAndPatient(labelName, getUID(), teamCode, patients);

            if (result != 1) {
                return error(-1, "添加失败");
            }

            return write(200, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "添加失败");
        }
    }

    /**
     * 删除居民某个标签
     *
     * @param patient   患者
     * @param labelCode 标签code
     * @param labelType 标签类型
     * @return
     */
    @RequestMapping(value = "/patient_label_delete")
    @ObserverRequired
    public String deletePatientLabel(String patient, String labelCode, String labelType) {
        try {
            if (StringUtils.isEmpty(String.valueOf(patient))) {
                return error(-1, "患者不能为空");
            }
            if (StringUtils.isEmpty(labelCode)) {
                return error(-1, "标签cdoe不能为空");
            }
            if (StringUtils.isEmpty(labelType)) {
                return error(-1, "标签类型不能为空");
            }

            int result = labelInfoService.deltePatientsLabel(patient, labelCode, labelType);

            if (result == -1) {
                return error(-1, "患者没有此标签");
            } else if (result == 1) {
                return error(200, "添加成功");
            } else {
                return error(-1, "删除失败");
            }
        } catch (Exception e) {
            return error(-1, "删除失败");
        }
    }

}
