package com.cftech.qy.qyagent.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.qy.qyagent.api.QyAgentUtil;
import com.cftech.qy.qyagent.model.Qyagent;
import com.cftech.qy.qyagent.service.QyagentService;
import com.cftech.sys.model.User;
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 java.util.List;


/**
 * 企业应用管理Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String QYAGENT_VIEW = "qy:qyagent:view"
 * 查看:public static final String QYAGENT_EDIT = "qy:qyagent:edit"
 *
 * @author Neil
 * @date: 2017-04-26 15:02
 */
@Slf4j
@Controller
@RequestMapping("/a/qyagent")
public class QyagentController {

    public static final String QYAGENT_VIEW = "qy:qyagent:view";
    public static final String QYAGENT_EDIT = "qy:qyagent:edit";

    @Autowired
    private QyagentService qyagentService;
    @Autowired
    private QyAgentUtil qyAgentUtil;


    //列表页面
    @RequiresPermissions(value = QYAGENT_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 "qyagent/qyagentlist";
    }

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

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

    //获取列表数据
    @RequiresPermissions(value = QYAGENT_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Qyagent qyagent, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    @RequestMapping(value = "/sync",method = {RequestMethod.GET})
    @RequiresPermissions(value = QYAGENT_EDIT)
    @ResponseBody
    public JSONObject sync(HttpServletRequest request) {
        Long accountId = UserUtils.getmpaccounts(request);
        User user = UserUtils.getUser();
        // 同步微信端的应用，下拉到本地为主
        JSONObject retObj = qyAgentUtil.sync(accountId, user.getId());
        log.info("同步结果: {}", retObj.toJSONString());
        return retObj;
    }

}
