package com.cftech.questionnaire.core.questions.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.SystemConfig;
import com.cftech.questionnaire.core.questions.model.Questions;
import com.cftech.questionnaire.core.questions.model.QuestionsType;
import com.cftech.questionnaire.core.questions.service.QuestionsService;
import com.cftech.questionnaire.core.questionscategory.model.Questionscategory;
import com.cftech.questionnaire.core.questionscategory.service.QuestionscategoryService;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 问卷题库Controller
 *
 * 权限字符串说明:
 * 查看:public static final String QUESTION_VIEW = "qy:questions:view"
 * 查看:public static final String QUESTION_EDIT = "qy:questions:edit"
 *
 * @author wxf
 * @date: 2017-05-24 11:43
 */
@Slf4j
@Controller
@RequestMapping("/a/questions")
public class QuestionsController {

    public static final String QUESTION_VIEW = "qy:questions:view";
    public static final String QUESTION_EDIT = "qy:questions:edit";
    private final static String rootQCName = SystemConfig.p.getProperty("ROOT_QUESTIONSCATEGORY_NAME");
    @Autowired
    private QuestionsService questionService;
    @Autowired
    private QuestionscategoryService questionscategoryService;
    //列表页面
    @RequiresPermissions(value = QUESTION_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String list(HttpServletRequest request, Model model) {
       /* Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);*/
        model.addAttribute("questionType", JSONArray.fromObject(QuestionsType.values()).toString());
        return "questions/questionslist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = QUESTION_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.POST,RequestMethod.GET})
    public String form(HttpServletRequest request, Questions questions, Model model) {
        Long id=questions.getId();
        if (!StringUtils.isEmpty(id)) {
            questions = questionService.fetchById(id);

        }
        model.addAttribute("questionType", JSONArray.fromObject(QuestionsType.values()).toString());
        questions.setOptiondetails(ESAPI.encoder().decodeForHTML(questions.getOptiondetails()));
        model.addAttribute("data", questions);
        return "questions/questionsform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = QUESTION_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(Questions question, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (question != null && question.getId() != null) {
                question.setUpdateBy(UserUtils.getUser().getId());
                questionService.update(question);
                rtnJson.put("errorNo", 0);
            } else {
                question.setAccountsId(accountsId);
                question.setDelFlag(false);
                question.setAccountsId(UserUtils.getmpaccounts(request));
                question.setCreateBy(UserUtils.getUser().getId());
                question.setUpdateBy(UserUtils.getUser().getId());
                questionService.save(question);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("问卷题目保存失败 : "+e.getMessage());
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = QUESTION_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Questions question, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("q.del_flag", Constants.DEL_FLAG_0);
        //conds.equal("accounts_id", accountsId);
        if(!UserUtils.isAdmin()){
            conds.equal("q.create_by",UserUtils.getUser().getId());
        }
        conds.like("q.question_title",question.getQuestionTitle());
        conds.equal("q.question_type",question.getQuestionType());
        Sort sort = new Sort("q.create_time", OrderType.DESC);
        List<Questions> list = questionService.fetchSearchVOByPage(question.getQuestionsCategory(),conds, sort, iDisplayStart, iDisplayLength);
        for(Questions questions : list){
//            questions.setOptiondetails(ESAPI.encoder().decodeForHTML(questions.getOptiondetails()) );
            String optionDetails = questions.getOptiondetails();
            questions.setOptiondetails(HtmlUtils.htmlUnescape(optionDetails));
        }
        Integer counts = questionService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }




    //删除数据
    @RequiresPermissions(value = QUESTION_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            questionService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

}
