package com.cftech.workshop.activ.web;

import com.alibaba.fastjson.JSONObject;

import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.workshop.activ.model.Activ;
import com.cftech.workshop.activ.model.SelectActivity;
import com.cftech.workshop.activ.service.ActivService;
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.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import com.cftech.workshop.meeting.service.MeetingService;
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.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String ACTIV_VIEW = "qy:activ:view"
 * 查看:public static final String ACTIV_EDIT = "qy:activ:edit"
 *
 * @author byj
 * @date: 2018-06-29 15:13
 */
@Slf4j
@Controller
@RequestMapping("/a/activ")
public class ActivController {

    public static final String ACTIV_VIEW = "qy:activ:view";
    public static final String ACTIV_EDIT = "qy:activ:edit";

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

    @Autowired
    private ActivService activService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private MeetingService meetingService;


    //列表页面
    @RequiresPermissions(value = ACTIV_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,Long meetingId) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("meetingId",meetingId);
        model.addAttribute("appid",appid);
        return "activ/activlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = ACTIV_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model,Long meetingId) {
        if (!StringUtils.isEmpty(id)) {
            Activ activ = activService.fetchById(id);
            String aid = String.valueOf(activ.getActiv_id());
            String atype = activ.getActiv_type();
            String activityName = aid + "," + atype;
            Conds conds = new Conds();
            conds.equal("id",aid);
            conds.equal("type",atype);
            Sort sort = new Sort("a.create_time",OrderType.DESC);
            List<SelectActivity> list = activService.searchActivity(conds,sort,0,0);
            String name = "";
            for (SelectActivity selectActivity:list){
                name = selectActivity.getTitle();
            }
            model.addAttribute("name",name);
            model.addAttribute("activityName",activityName);
            model.addAttribute("data", activ);
        }
        model.addAttribute("meetingId",meetingId);
        return "activ/activform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = ACTIV_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Activ activ, Model model, HttpServletRequest request, String activityid) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (activ != null && activ.getId() != null) {
                activ.setUpdateBy(UserUtils.getUser().getId());
                String id = "";
                String type = "";
                String[] splitactivityid = activityid.split(",");
                for(int i=0; i<splitactivityid.length; i++){
                    id = splitactivityid[0];
                    type = splitactivityid[1];
                }
                activ.setActiv_id(Long.valueOf(id));
                activ.setActiv_type(type);
                activService.update(activ);
                rtnJson.put("errorNo", 0);
            } else {
                String id = "";
                String type = "";
                activ.setNumber(codingruleUtils.getNumber(accountsId, Activ.class.getName()));
                activ.setAccountsId(accountsId);
                activ.setDelFlag(false);
                activ.setAccountsId(UserUtils.getmpaccounts(request));
                activ.setCreateBy(UserUtils.getUser().getId());
                activ.setUpdateBy(UserUtils.getUser().getId());
                String[] splitactivityid = activityid.split(",");
                for(int i=0; i<splitactivityid.length; i++){
                   id = splitactivityid[0];
                    type = splitactivityid[1];
                }
                activ.setActiv_id(Long.valueOf(id));
                activ.setActiv_type(type);
                activService.save(activ);
                meetingService.synMobileMenu();
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = ACTIV_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Activ activ, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("ac.del_flag", Constants.DEL_FLAG_0);
        conds.equal("ac.accounts_id", accountsId);

        if (!StringUtils.isEmpty(activ.getActiv_type())) {
            conds.equal("ac.activ_type", activ.getActiv_type());
        }
        if (!StringUtils.isEmpty(activ.getWorkshop_id())) {
            conds.equal("ac.workshop_id", activ.getWorkshop_id());
        }
        Sort sort = new Sort("ac.sort", OrderType.ASC);

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

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

    //选择活动
    @RequiresPermissions(value = ACTIV_VIEW)
    @RequestMapping(value = "/selectactivity",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject selectactivity(int iDisplayStart, int iDisplayLength, SelectActivity selectActivity, HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("a.create_by",UserUtils.getUser().getId());
        }
        if(!StringUtils.isEmpty(selectActivity.getTitle())){
            conds.like("a.title",selectActivity.getTitle());
        }
        Sort sort = new Sort("a.create_time",OrderType.DESC);
        List<SelectActivity> list = activService.searchActivity(conds,sort,iDisplayStart,iDisplayLength);
        Integer counts = activService.countActivity(conds);
        jsonObject.put("iTotalRecords", counts);
        jsonObject.put("iTotalDisplayRecords", counts);
        jsonObject.put("aaData", list);
        return jsonObject;
    }

}
