package com.cftech.activity.eggs.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.DateUtils;
import com.cftech.activity.eggs.model.Eggs;
import com.cftech.activity.eggs.service.EggsService;
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 EGGS_VIEW = "activity:eggs:view";
 * 查看: public static final String EGGS_EDIT = "activity:eggs:edit";
 *
 * @author wuxf
 * @date: 2017-04-27
 */
@Slf4j
@Controller
@RequestMapping("/a/activity/eggs")
public class EggsController {

    public static final String EGGS_VIEW = "activity:eggs:view";
    public static final String EGGS_EDIT = "activity:eggs:edit";
    public static final String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");

    @Autowired
    private EggsService eggsService;

    //列表页面
    @RequiresPermissions(value = EGGS_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 "eggs/eggslist";
    }

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


    @RequiresPermissions(value = EGGS_EDIT)
    @RequestMapping(value = "/startAndEnd",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject start(Eggs eggs){

        JSONObject rtnJson = new JSONObject();
        Eggs startWheel = eggsService.fetchById(eggs.getId());
        startWheel.setPrizes(HtmlUtils.htmlUnescape(startWheel.getPrizes()));
        if(eggs.getStatus().equals("1")){//redis开启活动
            eggsService.startActivity(startWheel);
        }else if(eggs.getStatus().equals("2")){//redis结束活动
            eggsService.endActivity(startWheel);
        }
        startWheel.setStatus(eggs.getStatus());
        startWheel.setUpdateBy(UserUtils.getUser().getId());
        eggsService.update(startWheel);
        rtnJson.put("errorNo", 0);
        return rtnJson;
    }



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

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

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

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

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

}
