package com.cftech.activity.log.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.log.model.WheelLog;
import com.cftech.activity.log.model.WheelLogDto;
import com.cftech.activity.log.service.WheelLogService;
import com.cftech.core.poi.ExcelKit;
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.DateFormatUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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


/**
 * 大转盘活动记录表Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String WHEELLOG_VIEW = "qy:wheelLog:view"
 * 查看:public static final String WHEELLOG_EDIT = "qy:wheelLog:edit"
 *
 * @author lisw
 * @date: 2017-04-27 13:57
 */
@Slf4j
@Controller
@RequestMapping("/a/wheelLog")
public class WheelLogController {

    public static final String WHEELLOG_VIEW = "qy:wheelLog:view";
    public static final String WHEELLOG_EDIT = "qy:wheelLog:edit";

    @Autowired
    private WheelLogService wheelLogService;


    //列表页面
    @RequiresPermissions(value = WHEELLOG_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);
        return "wheelLog/wheelLoglist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = WHEELLOG_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST} )
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            WheelLog wheelLog = wheelLogService.fetchById(id);
            model.addAttribute("data", wheelLog);
        }
        return "wheelLog/wheelLogform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = WHEELLOG_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(WheelLog wheelLog, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (wheelLog != null && wheelLog.getId() != null) {
                wheelLog.setUpdateBy(UserUtils.getUser().getId());
                wheelLogService.update(wheelLog);
                rtnJson.put("errorNo", 0);
            } else {
                wheelLog.setAccountsId(accountsId);
                wheelLog.setDelFlag(false);
                wheelLog.setAccountsId(UserUtils.getmpaccounts(request));
                wheelLog.setCreateBy(UserUtils.getUser().getId());
                wheelLog.setUpdateBy(UserUtils.getUser().getId());
                wheelLogService.save(wheelLog);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = WHEELLOG_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, WheelLogDto wheelLog, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("w.del_flag", Constants.DEL_FLAG_0);
        conds.equal("wl.accounts_id", accountsId);
        if(!UserUtils.isAdmin()){
            conds.equal("w.create_by", UserUtils.getUser().getId());
        }
        if (!StringUtils.isEmpty(wheelLog.getTitle())) {
            conds.like("wl.title", wheelLog.getTitle());
        }
        if (!StringUtils.isEmpty(wheelLog.getName())) {
            conds.like("m.name", wheelLog.getName());
        }
        Sort sort = new Sort("wl.create_time", OrderType.DESC);

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

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

    @RequiresPermissions(value = WHEELLOG_EDIT)
    @RequestMapping(value = "/exportExcel",method = RequestMethod.GET)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, WheelLogDto wheelLogDto){
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("w.del_flag", Constants.DEL_FLAG_0);
        conds.equal("wl.accounts_id", accountsId);
        if (!StringUtils.isEmpty(wheelLogDto.getTitle())) {
            conds.like("wl.title", wheelLogDto.getTitle());
        }
        if (!StringUtils.isEmpty(wheelLogDto.getName())) {
            conds.like("m.name",wheelLogDto.getName());
        }


        Sort sort = new Sort("wl.create_time", OrderType.DESC);

        List<WheelLogDto> list = wheelLogService.fetchSearchByPageDto(conds, sort, 0, 0);
//        if(list!=null && list.size()>0){
//            for (WheelLogDto wheelLogDto1 : list){
//                if(wheelLogDto1.getCreate_time()!=null)
//                    wheelLogDto1.setCreate_time_str(DateFormatUtils.getDateFormat(wheelLogDto1.getCreate_time(),"yyyy-MM-dd HH:mm" ));
//            }
//        }
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(WheelLogDto.class, response).toExcel(list, "大转盘参与人员信息");
    }

}
