package com.cftech.activity.wheel.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.log.model.WheelLogDto;
import com.cftech.activity.wheel.model.Wheel;
import com.cftech.activity.wheel.service.WheelService;
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.DateUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.sys.security.UserUtils;
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;
import lombok.extern.slf4j.Slf4j;
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 javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;


/**
 * 大转盘活动Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String WHEEL_VIEW = "qy:wheel:view"
 * 查看:public static final String WHEEL_EDIT = "qy:wheel:edit"
 *
 * @author lisw
 * @date: 2017-04-24 17:26
 */
@Slf4j
@Controller
@RequestMapping("/a/wheel")
public class WheelController {

    public static final String WHEEL_VIEW = "qy:wheel:view";
    public static final String WHEEL_EDIT = "qy:wheel:edit";

    public static final String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");

    @Autowired
    private WheelService wheelService;




    //列表页面
    @RequiresPermissions(value = WHEEL_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("appid", appid);
        return "wheel/wheellist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = WHEEL_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Wheel wheel = wheelService.fetchById(id);
            wheel.setPrizes(HtmlUtils.htmlUnescape(wheel.getPrizes()));
            String startTimeStr = DateUtils.formatDate(wheel.getStartTime(),"yyyy-MM-dd");
            String endTimeStr = DateUtils.formatDate(wheel.getEndTime(),"yyyy-MM-dd");
            model.addAttribute("startTimeStr",startTimeStr);
            model.addAttribute("endTimeStr",endTimeStr);
            model.addAttribute("data", wheel);

        }
        return "wheel/wheelform";
    }


    @RequestMapping(value = "/startAndEnd",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject start(Wheel wheel){
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 0);
        try{
            Wheel startWheel = wheelService.fetchById(wheel.getId());
            startWheel.setPrizes(HtmlUtils.htmlUnescape(startWheel.getPrizes()));
            boolean flag = false;
            if(wheel.getStatus().equals("1")){//redis开启活动
                if(wheelService.startActivity(startWheel)){
                    flag=true;
                }
            }else if(wheel.getStatus().equals("2")){//redis结束活动
                wheelService.endActivity(startWheel);
                flag=true;
            }

            startWheel.setUpdateBy(UserUtils.getUser().getId());
            startWheel.setStatus(wheel.getStatus());
            if(flag){
                wheelService.update(startWheel);
            }else{
                rtnJson.put("errorNo", 2);
            }

            return rtnJson;
        }catch (Exception e){
            rtnJson.put("errorNo", 1);
            e.printStackTrace();
        }
        return rtnJson;

    }



    //提交数据（新增、修改）
    @RequiresPermissions(value = WHEEL_EDIT)
    @RequestMapping(value = "/formData",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject formData(Wheel wheel, Model model, HttpServletRequest request,String startTimeStr,String endTimeStr) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        if(!StringUtils.isEmpty(startTimeStr) && !StringUtils.isEmpty(endTimeStr)){
            Date startDate = DateUtils.parseDate(startTimeStr);
            Date endDate = DateUtils.parseDate(endTimeStr);
            wheel.setStartTime(startDate);
            wheel.setEndTime(endDate);
        }

        try {
            if (wheel != null && wheel.getId() != null) {
                wheel.setUpdateBy(UserUtils.getUser().getId());
                wheelService.update(wheel);
                rtnJson.put("errorNo", 0);
            } else {
                wheel.setAccountsId(accountsId);
                wheel.setDelFlag(false);
                wheel.setAccountsId(UserUtils.getmpaccounts(request));
                wheel.setCreateBy(UserUtils.getUser().getId());
                wheel.setUpdateBy(UserUtils.getUser().getId());
                wheelService.save(wheel);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = WHEEL_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Wheel wheel, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if(!UserUtils.isAdmin()){
            conds.equal("create_by", UserUtils.getUser().getId());
        }
        if (!StringUtils.isEmpty(wheel.getTitle())) {
            conds.like("title", wheel.getTitle());
        }
        if (!StringUtils.isEmpty(wheel.getKeywords())) {
            conds.like("keywords", wheel.getKeywords());
        }
        if (!StringUtils.isEmpty(wheel.getExplain())) {
            conds.like("explain", wheel.getExplain());
        }
        if (!StringUtils.isEmpty(wheel.getStartTime())) {
            conds.equal("start_time", wheel.getStartTime());
        }
        if (!StringUtils.isEmpty(wheel.getEndTime())) {
            conds.equal("end_time", wheel.getEndTime());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

        List<Wheel> list = wheelService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = wheelService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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



}
