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

import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.sign.SignWebService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

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

/**
 * 医生端:签约管理控制类
 *
 * @author AndyTsai
 */

@RestController
@RequestMapping(value = "/doctor/sign", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-签约管理")
public class DoctorSignController extends WeixinBaseController {

    //	@Autowired
//	private SignContractService signContractService;
    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private SignWebService signWebService;

    @Autowired
    private DoctorInfoService infoService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private PatientService patientService;
    /**
     * 三师签约列表查询
     *
     * @param type     类型：1已签约，2未过期
     * @param id
     * @param pagesize
     * @return
     */
//	@RequestMapping(value = "list")
//	@ResponseBody
//	public String list( int type,  long id,  int pagesize, @RequestParam(required=false) String patientName) {
//		try {
//			Page<Object> page = signContractService.findByDoctor(type, getUID(), id, pagesize,patientName);
//			JSONArray array = new JSONArray();
//			if (page != null) {
//				for (Object obj : page) {
//					Object[] temp = (Object[]) obj;
//					if (temp == null ) {
//						continue;
//					}
//					JSONObject json = new JSONObject();
//					json.put("id", temp[0]);
//					
//					// 患者姓名
//					json.put("name", temp[1]);
//					// 患者头像
//					json.put("photo", temp[2]);
//					// 省名称
//					json.put("provinceName", temp[3]);
//					// 城市名称
//					json.put("cityName", temp[4]);
//					// 区县名称
//					json.put("townName", temp[5]);
//					// 详细地址
//					json.put("address", temp[6]);
//					// 签约日期
//					json.put("qyrq", DateUtil.dateToStrShort((Date) temp[7]));
//					//患者标识
//					json.put("code", temp[8]);
//					//患者联系方式
//					json.put("mobile", temp[9]);
//					array.put(json);
//				}
//			}
//			return write(200, "查询成功！", "list", array);
//		} catch (Exception e) {
//			error(e);
//			return error(-1, "查询失败！");
//		}
//	}
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(int type, long id, int pagesize, @RequestParam(required = false) String patientName) {
        try {
            String doctor = getUID();
            Page<Object> page = infoService.findPatientByDoctorSign(doctor, id, pagesize, patientName);
            JSONArray array = new JSONArray();
            Map<Object,Object> exitMap = new HashMap<>();
            if (page != null) {
                for (Object obj : page) {
                    Object[] temp = (Object[]) obj;
                    if (temp == null) {
                        continue;
                    }
                    if(exitMap.get(temp[9])!=null){//防止患者既有三师签约也有家庭签约导致数据重复
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", temp[1]);

                    // 患者姓名
                    json.put("name", temp[2]);
                    // 患者头像
                    json.put("photo", temp[3]);
                    // 省名称
                    json.put("provinceName", temp[4]);
                    // 城市名称
                    json.put("cityName", temp[5]);
                    // 区县名称
                    json.put("townName", temp[6]);
                    // 详细地址
                    json.put("address", temp[7]);
                    // 签约日期
                    json.put("qyrq", DateUtil.dateToStrShort((Date) temp[8]));
                    //患者标识
                    json.put("code", temp[9]);
                    //患者联系方式
                    json.put("mobile", temp[10]);
                    array.put(json);
                    exitMap.put(temp[9],temp);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败！");
        }
    }


    /**
     * 患者信息查询
     *
     * @param patient 患者标识
     * @return
     */
    @RequestMapping(value = "patient")
    @ResponseBody
    public String patient(String patient) {
        try {
            Patient temp = patientInfoService.findByCode(patient);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置患者姓名
                json.put("name", temp.getName());
                // 设置患者头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置患者年龄
                json.put("age", DateUtil.getAgeByBirthday(temp.getBirthday()));
                // 设置患者性别
                json.put("sex", temp.getSex());
                // 设置手机号码
                //CommonUtil.getMobileEncode(temp.getMobile())
                json.put("mobile", temp.getMobile());
                // 设置身份证号
                json.put("idcard", CommonUtil.getIdcardEncode(temp.getIdcard()));
                // 设置社保卡号
                json.put("ssc", temp.getSsc());
                // 设置省名称
                json.put("province", temp.getProvinceName());
                // 设置市名称
                json.put("city", temp.getCityName());
                // 设置区县名称
                json.put("area", temp.getTownName());
                // 设置街道
                json.put("street", temp.getStreet());
                // 设置街道名称
                json.put("streetName", temp.getStreetName());
                // 设置地址
                json.put("address", temp.getAddress());
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 获取签约患者信息
     *
     * @param status     签约状态 1:待签约 2 待解约 3 已签约  4已经解约  5未缴费
     * @param doctorType 医生类别 健管 3  全科 2
     * @return
     */
    @RequestMapping("/sign_info")
    public String getSignInfoByDoctor(
            int status,
            int doctorType,
            int page,
            int pageSize) {
        try {
            page = page > 0 ? page -1 : 0;
            List<Map<String, Object>> listSign = signWebService.getSignWebByDoctor(getUID(), status, page, pageSize);

            JSONObject data = new JSONObject();
            List<JSONObject> jsonArray = new ArrayList<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (listSign != null) {
                for (Map<String, Object> temp : listSign) {
                    if (temp == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", temp.get("code"));
                    json.put("doctorCode", temp.get("doctor"));
                    json.put("patientCode", temp.get("patient"));
                    json.put("patientName", temp.get("name"));
                    json.put("age", IdCardUtil.getAgeForIdcard(String.valueOf(temp.get("idcard"))));
                    json.put("provinceName", temp.get("provinceName"));
                    json.put("cityName", temp.get("cityName"));
                    json.put("townName", temp.get("townName"));
                    json.put("address", temp.get("address"));
                    json.put("photo", temp.get("photo"));
                    json.put("status", temp.get("status"));
                    json.put("openid", temp.get("openid"));
                    json.put("renewFlag", temp.get("renewFlag"));
                    String statusName = "";
                    switch (Integer.parseInt(temp.get("status").toString())) {
                        case 0:
                            statusName = "待签约";
                            break;
                        case 1:
                            statusName = "已签约";
                            break;
                        case 2:
                            statusName = "待解约";
                            break;
                        case -3:
                        case -4:
                            statusName = "已解约";
                            break;
                    }
                    json.put("statusName", statusName);
                    json.put("id", temp.get("id"));
                    json.put("applyDate", DateUtil.dateToStrLong((Date) temp.get("applyDate")));
                    json.put("releaseSpeak", temp.get("reason"));
                    json.put("streetName", temp.get("streetName"));
                    json.put("sex", temp.get("sex"));
                    if (status == 5) {
                        boolean epTime = false;
                        try {
                            epTime = redisTemplate.opsForSet().isMember("expenses:remind:set", temp.get("patient"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!epTime) {
                            json.put("expensesRemindStatus", 0);
                        } else {
                            json.put("expensesRemindStatus", 1);
                        }
                    }
                    if (status == 3) {
                        boolean epTime = false;
                        try {
                            epTime = redisTemplate.opsForSet().isMember("wechat:focus:remind:set", temp.get("patient"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!epTime) {
                            json.put("wechatFocusRemind", 0);
                        } else {
                            json.put("wechatFocusRemind", 1);
                        }
                    }
                    jsonArray.add(json);
                }
            }

            if (status == 5) {
                jsonArray.sort(new Comparator<JSONObject>() {
                    @Override
                    public int compare(JSONObject o1, JSONObject o2) {
                        if (o1.getInt("expensesRemindStatus") > o2.getInt("expensesRemindStatus")) {
                            return 1;
                        } else if (o1.getInt("expensesRemindStatus") < o2.getInt("expensesRemindStatus")) {
                            return -1;
                        } else if (o1.getInt("expensesRemindStatus") == o2.getInt("expensesRemindStatus")) {
                            return 0;
                        } else {
                            return 0;
                        }
                    }
                });
            }

            data.put("list", jsonArray);
//            data.put("totalPage", totalPage);
//            data.put("page", page);
            return write(200, "查询成功！", "data", data);
        } catch (Exception e) {
            error(e);
            return error(-1, "系统错误,请联系管理员!");
        }
    }

    /**
     * 查询今天是否全部提醒关注
     *
     * @return
     */
    @RequestMapping(value = "/is_remind_focus_all")
    @ApiOperation(value = "今天是否已全部提醒关注")
    public String isRemindFocusAllToday(){
        try{
            return write(200,"查询成功","data",signWebService.isRemindFocusAll(getUID()));
        }catch (Exception e){
            return error(-1,"查询失败");
        }
    }

    /**
     * 查询今天是否全部提醒关注
     *
     * @return
     */
    @RequestMapping(value = "/is_remind_expenses_all")
    @ApiOperation(value = "今天是否已全部提醒缴费")
    public String isRemindFExpensesAllToday(){
        try{
            return write(200,"查询成功","data",signWebService.isRemindExpensesAll(getUID()));
        }catch (Exception e){
            error(e);
            return error(-1,"查询失败");
        }
    }

    /**
     * 获取续签约患者信息
     *
     * @param status     签约状态 1:待签约 2 待缴费 3 已签约
     * @return
     */
    @RequestMapping("/sign_info_renew")
    @ApiOperation(value = "医生获取获取列表")
    public String getSignRenewInfoByDoctor(
            @RequestParam(required = true)int status,
            @RequestParam(required = true)int page,
            @RequestParam(required = true)int pageSize) {
        try {
            page = page > 0 ? page -1 : 0;
            List<Map<String, Object>> listSign = signWebService.getSignRenewWebByDoctor(getUID(), status, page, pageSize);
            //List<Map<String, Object>> listSign = signWebService.getSignRenewWebByDoctor("64de930c-5b15-11e6-8344-fa163e8aee56", status, page, pageSize);
            JSONObject data = new JSONObject();
            List<JSONObject> jsonArray = new ArrayList<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (listSign != null) {
                for (Map<String, Object> temp : listSign) {
                    if (temp == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", temp.get("code"));
                    json.put("doctorCode", temp.get("doctor"));
                    json.put("patientCode", temp.get("patient"));
                    json.put("patientName", temp.get("name"));
                    json.put("age", IdCardUtil.getAgeForIdcard(String.valueOf(temp.get("idcard"))));
                    json.put("provinceName", temp.get("provinceName"));
                    json.put("cityName", temp.get("cityName"));
                    json.put("townName", temp.get("townName"));
                    json.put("address", temp.get("address"));
                    json.put("photo", temp.get("photo"));
                    json.put("status", temp.get("status"));
                    json.put("openid", temp.get("openid"));
                    json.put("renewTime", temp.get("czrq"));
                    json.put("renewFlag",temp.get("renewFlag"));
                    String statusName = "";
                    switch (Integer.parseInt(temp.get("status").toString())) {
                        case 0:
                            statusName = "待签约";
                            break;
                        case 1:
                            statusName = "已签约";
                            break;
                        case 2:
                            statusName = "待解约";
                            break;
                        case -3:
                        case -4:
                            statusName = "已解约";
                            break;
                    }
                    json.put("statusName", statusName);
                    json.put("id", temp.get("id"));
                    json.put("applyDate", DateUtil.dateToStrLong((Date) temp.get("applyDate")));
                    json.put("releaseSpeak", temp.get("reason"));
                    json.put("streetName", temp.get("streetName"));
                    json.put("sex", temp.get("sex"));
                    jsonArray.add(json);
                }
            }
            data.put("list", jsonArray);
            return write(200, "查询成功！", "data", data);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "系统错误,请联系管理员!");
        }
    }

    /**
     * 批量提醒居民续签
     * @return
     */
    @RequestMapping("/sendRenewToPatients")
    @ApiOperation(value = "提醒用户签约接口")
    @ObserverRequired
    public String sendRenewToPatients(){
        try{
            int rs ;
            if(DateUtil.getNowMonth()>=7){
                rs = signWebService.sendRenewOverToPatients(getAccessToken(),getUID());
            }else{
                rs = signWebService.sendRenewToPatients(getAccessToken(),getUID());
            }

            //int rs = signWebService.sendRenewToPatients(getAccessToken(),"zbqD201703150222");
            if(rs == 0){
                return write(200, "您当前签约用户无需提醒！", "data", rs);
            }else{
                return write(200, "提醒成功！", "data", rs);
            }
        }catch (Exception e){
            error(e);
            return error(-1, "提醒失败");
        }
    }

    /**
     * 同意或拒绝
     * @param state
     * @return
     */
    @RequestMapping("/agreeRenew")
    @ApiOperation(value = "医生处理签约")
    @ObserverRequired
    public String agreeRenew(@RequestParam(required = true)String state,
                             @RequestParam(required = true)String patient,
                             @RequestParam(required = false) Long mesId,
                             @RequestParam(required = false)String signCode,
                             @RequestParam(required = false) String health,
                             @RequestParam(required = false) String disease,
                             @RequestParam(required = false) String custom,
                             @RequestParam(required = false) String sevId,
                             @RequestParam(required = false) String healthDoctor,
                             @RequestParam(required = false) Long teamCode,
                             @RequestParam(required = false) String expenses){
        try{
            //判断是否存在下个年度续签
            int isNowYearSign = signWebService.checkNowYearSign(getUID(),patient);
            if(isNowYearSign==0){
                //设置代码为已读
                signWebService.setMessState(mesId);
                return  write(200, "已经存在下个年度的签约关系", "data", -1);
            }

            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH)+1;
            int rs = 0;
            if(month<7){
                rs =signWebService.agreeRenew(getAccessToken(),getUID(),patient,state,mesId,year+"",signCode,health,disease,custom,sevId,healthDoctor,teamCode,expenses);
//            int rs =signWebService.agreeRenew(getAccessToken(),"test00000000005",patient,state);
            }else{
//                rs =signWebService.agreeRenew(getAccessToken(),getUID(),patient,state,mesId,year+"",signCode,health,disease,custom,sevId,healthDoctor,teamCode,expenses);
//                //如果没有续签记录,走签约记录
//                if(rs!=0){
//                    rs =signWebService.agreeRenewOverDue(getAccessToken(),getUID(),patient,state,mesId,year+"",signCode,health,disease,custom,sevId,healthDoctor,teamCode,expenses);
//                }
                rs =signWebService.agreeRenewOverDue(getAccessToken(),getUID(),patient,state,mesId,year+"",signCode,health,disease,custom,sevId,healthDoctor,teamCode,expenses);

            }
            if(rs != 1){
                //设置代码为已读
                signWebService.setMessState(mesId);
                return  write(200, "未找到签约记录", "data", rs);
            }else{
                return write(200, "操作成功！", "data", rs);
            }
        }catch (Exception e){
            error(e);
            return error(-1, "请求失败");
        }
    }

//    /**
//     * 获取用户详情列表
//     * @param year
//     * @param page
//     * @param pageSize
//     * @return
//     */
//    @RequestMapping("/getOverDuePatients")
//    @ApiOperation(value = "获取用户详情列表")
//    public String getOverDuePatients(@RequestParam(required = true)String year,
//                                     @RequestParam(required = true)Integer page,
//                                     @RequestParam(required = true)Integer pageSize){
//        try{
//            JSONObject rs =signWebService.getOverDuePatients(year,getUID(),page,pageSize);
//            //JSONObject rs =signWebService.getOverDuePatients(year,"64de930c-5b15-11e6-8344-fa163e8aee56",page,pageSize);
//
//            return write(200, "操作成功！", "data", rs);
//        }catch (Exception e){
//            return error(-1, "请求失败");
//        }
//    }

    /**
     *
     * 获取去医生下年度分组列表
     * @return
     */
//    @RequestMapping("/getRenewYearCount")
//    @ApiOperation(value = "获取年度分组")
//    public String getRenewYearCount(){
//        try{
//            JSONObject rs =signWebService.getRenewYearCount(getUID());
//            //JSONObject rs =signWebService.getRenewYearCount("64de930c-5b15-11e6-8344-fa163e8aee56");
//            return write(200, "操作成功！", "data", rs);
//        }catch (Exception e){
//            return error(-1, "请求失败");
//        }
//    }

    /**
     *
     *统计
     * 咨询量、获取待预约、获取健康教育、获取健康指导
     * @return
     */
    @RequestMapping("/getSignCountInfoInYear")
    @ApiOperation(value = "统计咨询量、获取待预约、获取健康教育、获取健康指导")
    public String getSignCountInfoInYear(@RequestParam(required = true)String patient){
        try{
            JSONObject rs =signWebService.getSignCountInfoInYear(patient);
            //JSONObject rs =signWebService.getRenewYearCount("64de930c-5b15-11e6-8344-fa163e8aee56");
            return write(200, "操作成功！", "data", rs);
        }catch (Exception e){
            error(e);
            return error(-1, "请求失败");
        }
    }

    @RequestMapping("/remindPatientRenew")
    @ApiOperation(value = "提醒居民续签")
    @ObserverRequired
    public String remindPatientRenew(@RequestParam(required = true)String patient){
        try{
            int rs =signWebService.remainPatientRenew(getAccessToken(),patient,getUID());
            //int rs =signWebService.remainPatientRenew(getAccessToken(),patient,"zbqD201703150222");
            if(rs==-1){
                return error(-1, "提醒失败");
            }else if(rs ==1){
                return write(200, "微信提醒成功！", "data", rs);
            }else if(rs ==2){
                return write(200, "短信提醒成功！", "data", rs);
            }
            return error(-1, "提醒失败");
        }catch (Exception e){
            error(e);
            return error(-1, "请求失败");
        }
    }

    /**
     * 验证是否允许签约
     * @param patient
     * @return
     */
    @RequestMapping(value = "/checkCanRenew", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String checkCanRenew(@RequestParam(required = true) String patient){
        try {
            JSONObject result = patientService.checkCanSignRenew(patient);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取签约字典数据
     * @return
     */
    @RequestMapping(value = "/getSigndict", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getSigndict(@RequestParam(required = false) String signYear){
        try {
            JSONArray result = patientService.getSigndict(signYear);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取签约字典数据
     * @return
     */
    @RequestMapping(value = "/getSigndictTree", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getSigndictTree(@RequestParam(required = true) Long teamCode){
        try {
            JSONArray result = patientService.getSignByTeamCodeGpbyServer(teamCode);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取当前医生签约关系分组
     * @return
     */
    @RequestMapping(value = "/getSignByDoctorCodeGpbyServer", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getSignByDoctorCodeGpbyServer(){
        try {
            JSONArray result = patientService.getSignByDoctorCodeGpbyServer(getUID(),null);
            //JSONArray result = patientService.getSignByDoctorCodeGpbyServer("xh1D201703150222");
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }

    /**
     *  获取团队名称
     * @return
     */
    @RequestMapping(value = "/getTeamNameByTeamCode", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTeamNameByTeamCode(@RequestParam(required = true) Long teamCode){
        try {
            String result = patientService.getTeamNameByTeamCode(teamCode);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    @RequestMapping(value = "/getPatientSignLogInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getPatientSignLogInfo(@RequestParam(required = true)String patient){
        try {
            JSONObject result = signWebService.getPatientSignLogInfo(patient);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}
