package com.cftech.activity.giftbox.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.giftbox.model.Giftbox;
import com.cftech.activity.giftbox.service.GiftboxService;
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 GIFTBOX_VIEW = "mp:scratch:view"
 * 查看:public static final String GIFTBOX_EDIT = "mp:scratch:edit"
 *
 * @author lisw
 * @date: 2017-04-24 17:26
 */
@Slf4j
@Controller
@RequestMapping("/a/giftbox")
public class GiftboxController {

    public static final String GIFTBOX_VIEW = "mp:giftbox:view";
    public static final String GIFTBOX_EDIT = "mp:giftbox:edit";
    public static final String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");

    @Autowired
    private GiftboxService giftboxService;



    //列表页面
    @RequiresPermissions(value = GIFTBOX_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 "giftbox/giftboxlist";
    }

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


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

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



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

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

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

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

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

}
