package com.cftech.activity.oil.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.oil.model.Oil;
import com.cftech.activity.oil.service.OilService;
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.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.ResponseBody;

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


/**
 * 机油大转盘活动Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String EGGS_VIEW = "activity:oil:view";
 * 查看: public static final String EGGS_EDIT = "activity:oil:edit";
 *
 * @author wuxf
 * @date: 2017-04-27
 */
@Slf4j
@Controller
@RequestMapping("/a/activity/oil")
public class OilController {

    public static final String EGGS_VIEW = "activity:oil:view";
    public static final String EGGS_EDIT = "activity:oil:edit";

    @Autowired
    private OilService oilService;

    //列表页面
    @RequiresPermissions(value = EGGS_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "oil/oillist";
    }

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


    @RequiresPermissions(value = EGGS_EDIT)
    @RequestMapping("/startAndEnd")
    @ResponseBody
    public JSONObject start(Oil oil){

        JSONObject rtnJson = new JSONObject();
        Oil startWheel = oilService.fetchById(oil.getId());
       /* if(oil.getStatus().equals("1")){//redis开启活动
            oilService.startActivity(startWheel);
        }else if(oil.getStatus().equals("2")){//redis结束活动
            oilService.endActivity(startWheel);
        }*/
        oil.setUpdateBy(UserUtils.getUser().getId());
        oilService.update(oil);
        rtnJson.put("errorNo", 0);
        return rtnJson;
    }



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

        try {
            if (oil != null && oil.getId() != null) {
                oil.setUpdateBy(UserUtils.getUser().getId());
                oilService.update(oil);
                rtnJson.put("errorNo", 0);
            } else {
                oil.setAccountsId(accountsId);
                oil.setDelFlag(false);
                oil.setStatus("1");//默认开启活动
                oil.setAccountsId(UserUtils.getmpaccounts(request));
                oil.setCreateBy(UserUtils.getUser().getId());
                oil.setUpdateBy(UserUtils.getUser().getId());
                oilService.save(oil);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

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

        List<Oil> list = oilService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = oilService.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("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            oilService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

}
