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

import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.doctor.SurveyUserDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.survey.ManagerQuestionnaireService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.web.WeixinBaseController;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端问卷调查 manager路径需要验证
 * Created by Reece on 2017/3/7.
 */
@Controller
@RequestMapping(value = "/doctor/questionnaire")
@Api(description = "管理端问卷调查")
public class ManagerQuestionnaireController extends WeixinBaseController {

    @Autowired
    private ManagerQuestionnaireService managerQuestionnaireService;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private SurveyUserDao surveyUserDao;
    @Autowired
    WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取问卷列表
     *
     * @return
     */
    @RequestMapping(value = "getQuestionnaireList", method = RequestMethod.GET)
    @ApiOperation(value = "获取问卷列表")
    @ResponseBody
    public String getQuestionnaireList(
            @ApiParam(value = "当前页")
            @RequestParam int pageNo,
            @ApiParam(value = "显示记录数")
            @RequestParam int pageSize) {
        try {
            JSONArray jsonArray = managerQuestionnaireService.getQuestionnaireList(pageNo, pageSize);
            return write(200, "查询成功!", "data", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }
    }

    /**
     * 获取单个问卷的概述
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "getQuestionnaireSummary", method = RequestMethod.GET)
    @ApiOperation(value = "获取单个问卷的概述")
    @ResponseBody
    public String getQuestionnaireSummary(
            @ApiParam(value = "问卷id")
            @RequestParam String id) {
        try {
            JSONObject jsonObject = managerQuestionnaireService.getQuestionnaireSummary(id);
            return write(200, "查询成功!", "data", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }
    }

    /**
     * 查看问卷内容
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "getQuestionnaireDetail", method = RequestMethod.GET)
    @ApiOperation(value = "查看问卷内容")
    @ResponseBody
    public String getQuestionnaireDetail(
            @ApiParam(value = "问卷id")
            @RequestParam String id) {
        try {
            JSONObject jsonObject = managerQuestionnaireService.getQuestionnaireDetail(id);
            logger.error("jsonObject=====>" + jsonObject);
            return write(200, "查询成功", "data", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }
    }

    /**
     * 更改单个问卷状态
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "modifyQuestionnaireStatus", method = RequestMethod.GET)
    @ApiOperation(value = "更改单个问卷状态")
    @ResponseBody
    @ObserverRequired
    public String modifyQuestionnaireStatus(
            @ApiParam(value = "问卷id")
            @RequestParam String id) {
        try {
            int status = managerQuestionnaireService.modifyQuestionnaireStatus(id);
            if (status == 1) {
                return write(200, "更改为正常状态!");
            } else {
                return write(200, "更改为暂停状态!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "更改状态失败!");
        }
    }

    /**
     * 查看调查结果
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "getAnswers", method = RequestMethod.GET)
    @ApiOperation(value = "查看调查结果")
    @ResponseBody
    public String getAnswers(
            @ApiParam(value = "问卷id")
            @RequestParam String id) {
        try {
            JSONObject jsonObject = managerQuestionnaireService.getAnswers(id);
            return write(200, "查询成功!", "data", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }

    }

    /**
     * 详细按钮 查看选项和问答题说明
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "getOptionsComment", method = RequestMethod.GET)
    @ApiOperation(value = "调查结果")
    @ResponseBody
    public String getOptionsComment(
            @RequestParam int pageNo,
            @RequestParam int pageSize,
            @ApiParam(value = "问卷id")
            @RequestParam String id,
            @ApiParam(value = "题目id")
            @RequestParam String questionId,
            @ApiParam(value = "选项id")
            @RequestParam(required = false) String optionId) {
        try {
            JSONObject jsonObject = managerQuestionnaireService.getOptionsComment(id, questionId, optionId, pageNo, pageSize);
            return write(200, "查询成功!", "data", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }

    }

    /**
     * 创建问卷（选择模板，自主创建）
     * 问题顺序是按自然先后顺序传进来还是需要乱序加题号传进来？自然以数组下标表示题号，乱序以sort字段表示题号
     *
     * @return
     */
    @RequestMapping(value = "createSurvey", method = RequestMethod.POST)
    @ApiOperation(value = "创建问卷")
    @ResponseBody
    @ObserverRequired
    public String createSurvey(
            @ApiParam(value = "自主创建JSON字符串", allowMultiple = true, defaultValue = "{\"surveyName\":\"问卷名称\",\"surveyTarget\":[{\"sex\":1},{\"disease\":[1,2]},{\"service\":[3,2]},{\"healthCondition\":[1,2,3]}],\"questions\":[{\"isRequired\":\"1\",\"options\":[{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"选项说明\",\"del\":\"1\",\"haveComment\":\"1\",\"sort\":\"1\",\"content\":\"选项内容\"},{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"选项说明\",\"del\":\"1\",\"haveComment\":\"1\",\"sort\":\"2\",\"content\":\"选项内容\"},{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"选项说明\",\"del\":\"1\",\"haveComment\":\"1\",\"sort\":\"3\",\"content\":\"选项内容\"}],\"comment\":\"问题说明\",\"del\":\"1\",\"sort\":\"1\",\"title\":\"问题题目\",\"type\":\"0\",\"qstCode\":\"yuiopyuiopuio\"},{\"isRequired\":\"1\",\"maxOptions\":\"5\",\"options\":[{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"选项说明\",\"del\":\"1\",\"haveComment\":\"1\",\"sort\":\"1\",\"content\":\"选项内容\"},{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"选项说明\",\"del\":\"1\",\"haveComment\":\"1\",\"sort\":\"2\",\"content\":\"选项内容\"},{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"选项说明\",\"del\":\"1\",\"haveComment\":\"1\",\"sort\":\"3\",\"content\":\"选项内容\"}],\"comment\":\"问题说明\",\"del\":\"1\",\"minOptions\":\"2\",\"sort\":\"2\",\"title\":\"问题题目\",\"type\":\"1\",\"qstCode\":\"yuiopyuiopuio\"},{\"isRequired\":\"1\",\"nextQuestion\":\"逻辑跳转下一题编号\",\"comment\":\"问题说明\",\"del\":\"1\",\"sort\":\"1\",\"title\":\"问题题目\",\"type\":\"2\",\"qstCode\":\"yuiopyuiopuio\"}],\"comment\":\"问卷说明\",\"templateCode\":\"\",\"label\":[1,2,3,4],\"send\":\"1\"}\n")
            @RequestParam String jsonData) {
        try {
//        解析整套问卷json字符串并保存
            JSONObject jsonStr = new JSONObject(jsonData.toString());
            System.out.println("==============================>" + jsonStr);
//            获取医生信息（仅限市级管理员）
            String doctor = getUID();
            String accessToken = getAccessToken();
            String surveyCode = managerQuestionnaireService.createSurvey(doctor, jsonStr, accessToken);
            return write(200, "创建成功!", "surveyCode", surveyCode);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "创建失败!");
        }
    }

    /**
     * 获取模板标签
     *
     * @return
     */
    @RequestMapping(value = "getTemplateLabel", method = RequestMethod.GET)
    @ApiOperation(value = "从字典中获取模板标签")
    @ResponseBody
    public String getTemplateLabel() {
        try {
            List list = managerQuestionnaireService.getTemplateLabel();
            return write(200, "查询成功!", "data", list);
        } catch (Exception e) {
            error(e);
            return write(-1, "查询失败!");
        }
    }

    /**
     * 由模板标签获取模板概述
     */
    @RequestMapping(value = "getTemplateByLabel", method = RequestMethod.GET)
    @ApiOperation(value = "由模板标签获取模板概述")
    @ResponseBody
    public String getTemplateByLabel(@RequestParam int pageNo,
                                     @RequestParam int pageSize,
                                     @ApiParam(value = "模板标签code值，多个逗号分隔,没有为默认列表")
                                     @RequestParam(required = false) String labels) {
        try {
            List list = managerQuestionnaireService.getTemplateByLabel(pageNo, pageSize, labels);
            return write(200, "查询成功!", "data", list);
        } catch (Exception e) {
            error(e);
            return write(-1, "查询失败!");
        }
    }

    /**
     * 由模板ID获取问卷模板详情getTemplateDetail(String id)
     */
    @RequestMapping(value = "getTemplateById", method = RequestMethod.GET)
    @ApiOperation(value = "由模板ID获取问卷模板详情")
    @ResponseBody
    public String getTemplateById(
            @ApiParam(value = "模板ID")
            @RequestParam String code) {
        try {
            Map<String, Object> map = managerQuestionnaireService.getTemplateById(code);
            return write(200, "查询成功!", "data", map);
        } catch (Exception e) {
            error(e);
            return write(-1, "查询失败!");
        }
    }

    /**
     * 由模板ID获取问卷模板具体问题
     */
    @RequestMapping(value = "getTemplateDetail", method = RequestMethod.GET)
    @ApiOperation(value = "由模板ID获取问卷模板具体问题")
    @ResponseBody
    public String getTemplateDetail(
            @ApiParam(value = "模板ID")
            @RequestParam String code) {
        try {
            JSONObject jsonObject = managerQuestionnaireService.getTemplateDetail(code);
            System.out.println("createSurvey's template===============>" + jsonObject);
            return write(200, "查询成功!", "data", jsonObject);
        } catch (Exception e) {
            error(e);
            return write(-1, "查询失败!");
        }
    }

    /**
     * 由模板标签或者标题获取模板简述（只有名称，时间及标签）sql like关键字
     * 由模板标签获取模板概述
     *
     * @return
     */
    @RequestMapping(value = "getTemplateByLabelOrTitle", method = RequestMethod.GET)
    @ApiOperation(value = "由模板标签或者标题获取模板简述")
    @ResponseBody
    public String getTemplateByLabelOrTitle(
            @ApiParam(value = "模板标题或标签")
            @RequestParam String name,
            @RequestParam int pageNo,
            @RequestParam int pageSize) {
        try {
            List list = managerQuestionnaireService.getTemplateByLabelOrTitle(name, pageNo, pageSize);
            return write(200, "查询成功!", "data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }
    }


    /**
     * 根据标题搜索题库问题
     *
     * @return
     */
    @RequestMapping(value = "getQuestionList", method = RequestMethod.GET)
    @ApiOperation(value = "根据标题搜索题库问题")
    @ResponseBody
    public String getQuestionList(
            @ApiParam(value = "题库标题")
            @RequestParam(required = false) String title,
            @RequestParam int pageNo,
            @RequestParam int pageSize) {
        try {
            JSONObject jsonObject = managerQuestionnaireService.getQuestionList(title, pageNo, pageSize);

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

    /**
     * 获取筛选条件
     *
     * @return
     */
    @RequestMapping(value = "getFilter", method = RequestMethod.GET)
    @ApiOperation(value = "获取筛选条件")
    @ResponseBody
    public String getFilter() {
        try {
            Map list = managerQuestionnaireService.getFilter();
            return write(200, "查询成功!", "data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败!");
        }
    }

    /**
     * 新建问卷保存为模板
     * 引用模板新建问卷保存变更到模板(可以增加删除问题)
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "savaSurveyAsTemplate", method = RequestMethod.GET)
    @ApiOperation(value = "新建问卷保存为模板")
    @ResponseBody
    public String savaSurveyAsTemplate(
            @ApiParam(value = "新建问卷编码")
            @RequestParam String code,
            @ApiParam(value = "旧模板编码")
            @RequestParam(required = false) String templateCode,
            @ApiParam(value = "修改后的标题")
            @RequestParam(required = false) String title) {
        try {
            int num = 0;
            if (StringUtils.isEmpty(templateCode)) {
//                保存为新模板(重复之后才会有title传进来)
                if (StringUtils.isEmpty(title)) {
                    num = managerQuestionnaireService.savaSurveyAsTemplate(code, null);
                } else {
                    num = managerQuestionnaireService.savaSurveyAsTemplate(code, title);
                }

            } else {
//                修改原模板(重复之后才会有title传进来)
                if (StringUtils.isEmpty(title)) {
                    num = managerQuestionnaireService.modifyTemplate(code, templateCode, null);
                } else {
                    num = managerQuestionnaireService.modifyTemplate(code, templateCode, title);
                }

            }
            if (num == 0) {
                return write(200, "保存成功！");
            } else {
                Map map = new HashMap();
//              标题重复码
                map.put("errorCode", "001");
                map.put("number", num);
                return write(-1, "标题重复！", "data", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "保存失败！");
        }
    }

    /**
     * 提醒做答按钮功能发送居民模板消息
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "remindAnswer", method = RequestMethod.GET)
    @ApiOperation(value = "提醒做答按钮功能")
    @ResponseBody
    public String remindAnswer(
            @ApiParam(value = "问卷编码")
            @RequestParam String code) {
        try {
            List<String> codes = surveyUserDao.findBySurveyCodeAndStatus(code);

            String accessToken = getAccessToken();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String str = "{\"remark\":\"我们将按调查最终结果，优化健康服务。\",\"keyword1\":\"调查问卷\"}";
            JSONObject json = new JSONObject(str);
           /* codes.stream().forEach(c -> {
                Patient p = patientDao.findByCode(c);
                String name = p.getName();
                String openId = p.getOpenid();
                json.put("keyword2", sdf.format(new Date()));
                json.put("toUser", c);
                json.put("survey_id", code);
                json.put("first", name + "，您好！为了给您提供更好的家庭医生健康服务，现有一份问卷需要您填写。");
                logger.error("patient =======>" + code);
                logger.error("name =======>" + name);
                logger.error("openId =======>" + openId);

                //判断是否有openId,有发送没有则查找家人发送
                if (StringUtils.isNotBlank(p.getOpenid())) {
                    // 添加到发送队列
                    logger.error("json =======>" + json);
                    PushMsgTask.getInstance().putWxMsg(accessToken, 11, openId, name, json);
                } else {
                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getOpenid());
                    Patient member = (Patient) j.get("member");
                    if (StringUtils.isNotBlank(member.getOpenid())) {
                        String first = (String) json.get("first");
                        json.remove("first");
                        try {
                            json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()) + first);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        logger.error("没有opIn  json =======>" + json);
                        PushMsgTask.getInstance().putWxMsg(accessToken, 11, member.getOpenid(), member.getName(), json);
                    }
                }
            });*/

            new Thread() {
                public void run() {
                    for (String c : codes) {
                        Patient p = patientDao.findByCode(c);
                        String name = p.getName();
                        String openId = p.getOpenid();
                        json.put("keyword2", sdf.format(new Date()));
                        json.put("toUser", c);
                        json.put("represented", c);
                        json.put("survey_id", code);
                        String first = name + "，您好！为了给您提供更好的家庭医生健康服务，现有一份问卷需要您填写。";
                        json.put("first", first);
                        //判断是否判定openId,有没有发则查找家人发送
                        if (StringUtils.isNotBlank(p.getOpenid())) {
                            // 添加到发送队列
                            logger.error("json =======>" + json);
//                            PushMsgTask.getInstance().putWxMsg(accessToken, 11, openId, name, json);
                            PushMsgTask.getInstance().sendWeixinMessage(accessToken, 11, openId, name, json);
                        }
//                        else {
//                            JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getOpenid());
//                            Patient member = (Patient) j.get("member");
//                            if (StringUtils.isNotBlank(member.getOpenid())) {
//                                String first = (String) json.get("first");
//                                json.remove("first");
//                                try {
//                                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()) + first);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                logger.error("没有opIn  json =======>" + json);
////                                PushMsgTask.getInstance().putWxMsg(accessToken, 11, member.getOpenid(), member.getName(), json);
//                                PushMsgTask.getInstance().sendWeixinMessage(accessToken, 11, member.getOpenid(), member.getName(), json);
//                            }
//                        }
                        //发送代理人
                        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                        if(jsonArray!=null&&jsonArray.length()>0){
                            for (int i = 0;i<jsonArray.length();i++){
                                JSONObject j  = jsonArray.getJSONObject(i);
                                Patient member = (Patient) j.get("member");
                                if(StringUtils.isNotBlank(member.getOpenid())){
                                    json.remove("toUser");
                                    json.put("toUser",member.getCode());
                                    json.remove("first");
                                    try {
                                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    PushMsgTask.getInstance().sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 11, member.getOpenid(), p.getName(), json);
                                }
                            }
                        }
                    }
                }
            }.start();

            return write(200, "发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "发送失败！");
        }
    }

    /**
     * 获取筛选条件数量
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "getAmount", method = RequestMethod.POST)
    @ApiOperation(value = "获取筛选条件数量")
    @ResponseBody
    public String getAmount(
            @ApiParam(value = "筛选条件")
            @RequestParam String json) {
        try {
            int amount = managerQuestionnaireService.getAmount(json);
            return write(200, "查询成功！", "amount", amount);
        } catch (Exception e) {
            e.printStackTrace();
            return write(-1, "查询失败！");
        }
    }


}
