package com.cftech.activity.scratch.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.scratch.model.Scratch;
import com.cftech.activity.scratch.service.ScratchService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.Date;
import java.util.List;


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

    public static final String SCRATCH_VIEW = "qy:scratch:view";
    public static final String SCRATCH_EDIT = "qy:scratch:edit";

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

    @Autowired
    private ScratchService scratchService;



    //列表页面
    @RequiresPermissions(value = SCRATCH_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 "scratch/scratchlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = SCRATCH_VIEW)
    @RequestMapping(value = "/form",method ={RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Scratch scratch = scratchService.fetchById(id);
            String startTimeStr = DateUtils.formatDate(scratch.getStartTime(),"yyyy-MM-dd");
            String endTimeStr = DateUtils.formatDate(scratch.getEndTime(),"yyyy-MM-dd");
            model.addAttribute("startTimeStr",startTimeStr);
            model.addAttribute("endTimeStr",endTimeStr);
            model.addAttribute("data", scratch);
        }
        return "scratch/scratchform";
    }


    @RequestMapping(value = "/startAndEnd",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject start(Scratch scratch){
        JSONObject rtnJson = new JSONObject();

        Scratch scratchStart = scratchService.fetchById(scratch.getId());
        scratchStart.setPrizes(HtmlUtils.htmlUnescape(scratchStart.getPrizes()));
        boolean flag = false;
        if(scratch.getStatus().equals("1")){//redis开启活动
            if(scratchService.startActivity(scratchStart)){
                flag = true;
            }
        }else if(scratch.getStatus().equals("2")){//redis结束活动
            scratchService.endActivity(scratchStart);
            flag = true;
        }
        scratchStart.setStatus(scratch.getStatus());
        scratch.setUpdateBy(UserUtils.getUser().getId());
        if(flag){
            scratchService.update(scratchStart);
            rtnJson.put("errorNo", 0);
        }else{
            rtnJson.put("errorNo",1);
        }
        return rtnJson;
    }



    //提交数据（新增、修改）
    @RequiresPermissions(value = SCRATCH_EDIT)
    @RequestMapping(value = "/formData",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject formData(Scratch scratch, 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);
            scratch.setStartTime(startDate);
            scratch.setEndTime(endDate);
        }

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

    //获取列表数据
    @RequiresPermissions(value = SCRATCH_VIEW)
    @RequestMapping(value = "/listData",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Scratch scratch, 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(scratch.getTitle())) {
            conds.like("title", scratch.getTitle());
        }
        if (!StringUtils.isEmpty(scratch.getKeywords())) {
            conds.like("keywords", scratch.getKeywords());
        }
        if (!StringUtils.isEmpty(scratch.getExplain())) {
            conds.like("explain", scratch.getExplain());
        }
        if (!StringUtils.isEmpty(scratch.getStartTime())) {
            conds.equal("start_time", scratch.getStartTime());
        }
        if (!StringUtils.isEmpty(scratch.getEndTime())) {
            conds.equal("end_time", scratch.getEndTime());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

}
