package com.cftech.questionnaire.core.paper.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.paper.model.PaperBaseEntity;
import com.cftech.questionnaire.core.paper.model.PaperSubject;
import com.cftech.questionnaire.core.paper.model.PaperType;
import com.cftech.questionnaire.core.paper.model.SelectActivity;
import com.cftech.questionnaire.core.paper.service.PaperService;
import com.cftech.questionnaire.core.papercategory.model.Papercategory;
import com.cftech.questionnaire.core.papercategory.service.PapercategoryService;
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 javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 问卷Controller
 *
 * 权限字符串说明:
 * 查看:public static final String QUESTION_VIEW = "qy:questionnaire:paper:view"
 * 查看:public static final String QUESTION_EDIT = "qy:questionnaire:paper:edit"
 *
 * @author wxf
 * @date: 2017-05-25 13:48
 */
@Slf4j
@Controller
@RequestMapping("/a/paper")
public class PaperController {

    public static final String QUESTION_VIEW = "qy:paper:view";
    public static final String QUESTION_EDIT = "qy:paper:edit";
    private final static String rootPCName = SystemConfig.p.getProperty("ROOT_PAPERCATEGORY_NAME");
    @Autowired
    private PaperService paperService;
    @Autowired
    private PapercategoryService papercategoryService;

    //列表页面
    @RequiresPermissions(value = QUESTION_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String list(HttpServletRequest request, Model model) {
        model.addAttribute("paperType", JSONArray.fromObject(PaperType.values()).toString());
        model.addAttribute("appid",SystemConfig.p.getProperty("WX_MP_SERVER_APPID"));
       /* Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);*/
        return "paper/paperlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = QUESTION_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.POST,RequestMethod.GET})
    public String form(HttpServletRequest request, PaperBaseEntity paper, Model model) {
        Long id=paper.getId();
        if (!StringUtils.isEmpty(id)) {
            paper = paperService.fetchById(id);
            paper.setContent_des(ESAPI.encoder().decodeForHTML(paper.getContent_des()));
            paper.setContent_des_en(ESAPI.encoder().decodeForHTML(paper.getContent_des_en()));
            if (paper.getPaperCategory() == 0) {
                paper.setPaperCategoryName(rootPCName);
                String aid = String.valueOf(paper.getActivity_id());
                String atype = paper.getActivity_type();
                String activityName = aid + "," + atype;
                //活动title
                Conds conds = new Conds();
                conds.equal("a.id",aid);
                conds.equal("a.type",atype);
                Sort sort = new Sort("a.create_time",OrderType.DESC);
                List<SelectActivity> list = paperService.searchActivity(conds,sort,0,0);
                String name = "";
                for (SelectActivity selectActivity:list){
                    name = selectActivity.getTitle();
                }
                model.addAttribute("name",name);
                model.addAttribute("activityName",activityName);


            } else {
                Papercategory parentPaperCategory = papercategoryService.fetchById(paper.getPaperCategory());
                paper.setPaperCategoryName(parentPaperCategory.getName());
            }
        }
        model.addAttribute("data", paper);
        model.addAttribute("paperType", JSONArray.fromObject(PaperType.values()).toString());
        return "paper/paperform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = QUESTION_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(PaperBaseEntity paper, Model model, HttpServletRequest request , String activityid , String activitytype) {
        JSONObject rtnJson = new JSONObject();
        paper.setQuestions(ESAPI.encoder().decodeForHTML(paper.getQuestions()));
        try {
            if (paper != null && paper.getId() != null) {
                String[] splitactivityid = activityid.split(",");
                String id = null;
                String type = null;
                if(splitactivityid!=null){
                 id = splitactivityid[0];
                 type = splitactivityid[1];
                    if(!id.equals("null")){
                        paper.setActivity_id(Long.valueOf(id));
                        paper.setActivity_type(type);
                        Conds conds = new Conds();
                        conds.notEqual("id",paper.getId());
                        conds.equal("activity_id",id);
                        conds.equal("activity_type",type);
                        conds.equal("del_flag",0);
                        PaperBaseEntity paperBaseEntity = paperService.fetchSearchByConds(conds);
                        if(paperBaseEntity!=null){  //该活动已经被别的问卷绑定
                            rtnJson.put("errorNo",3);
                        }else{
                            paper.setUpdateBy(UserUtils.getUser().getId());
                            paperService.updateBatch(paper);
                            rtnJson.put("errorNo", 0);
                        }
                    }else{
                        paper.setUpdateBy(UserUtils.getUser().getId());
                        paperService.updateBatch(paper);
                        rtnJson.put("errorNo", 0);
                    }

                }
            } else {
                paper.setDelFlag(false);
                paper.setCreateBy(UserUtils.getUser().getId());
                paper.setUpdateBy(UserUtils.getUser().getId());
                paper.setReading(Long.valueOf(0));
                String id = null;
                String type = null;
                if(!activityid.equals("")){
                    String[] splitactivityid = activityid.split(",");
                    id = splitactivityid[0];
                    type = splitactivityid[1];
                    Conds conds = new Conds();
                    conds.equal("activity_id",id);
                    conds.equal("activity_type",type);
                    conds.equal("del_flag",0);
                    PaperBaseEntity paperBaseEntity = paperService.fetchSearchByConds(conds);
                    if(paperBaseEntity!=null){  //改活动已经被别的问卷绑定
                        rtnJson.put("errorNo",3);
                    }else{
                        paper.setActivity_id(Long.valueOf(id));
                        paper.setActivity_type(type);
                        paperService.saveBatch(paper);
                        rtnJson.put("errorNo", 2);
                    }
                }else{
                    paperService.saveBatch(paper);
                    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, PaperBaseEntity paper, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("paper.create_by", UserUtils.getUser().getId());
        }
        if(!StringUtils.isEmpty(paper.getPaperTitle())){
            conds.equal("paper.paper_title",paper.getPaperTitle());
        }
        conds.equal("paper.del_flag", Constants.DEL_FLAG_0);
        conds.equal("paper.paper_type",paper.getPaperType());
        Sort sort = new Sort("paper.create_time", OrderType.DESC);
        List<PaperBaseEntity> list = paperService.fetchSearchVOByPage(paper.getPaperCategory(),conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = paperService.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 {
            paperService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }
    @RequiresPermissions(value = QUESTION_VIEW)
    @RequestMapping(value = "/selectactivity",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject selectactivity(int iDisplayStart, int iDisplayLength, SelectActivity selectActivity, HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("a.create_by",UserUtils.getUser().getId());
        }
        if(!StringUtils.isEmpty(selectActivity.getTitle())){
            conds.like("a.title",selectActivity.getTitle());
        }
        Sort sort = new Sort("a.create_time",OrderType.DESC);
        List<SelectActivity> list = paperService.searchActivity(conds,sort,iDisplayStart,iDisplayLength);
        Integer counts = paperService.countActivity(conds);
        jsonObject.put("iTotalRecords", counts);
        jsonObject.put("iTotalDisplayRecords", counts);
        jsonObject.put("aaData", list);
        return jsonObject;
    }

}
