package com.cftech.accounts.controller;

import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.util.OutputJSONUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.sys.model.User;
import com.cftech.sys.security.UserUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lisw
 * @date 2016年8月26日 下午2:28:30
 */
@Controller
@RequestMapping(value = "/a/manageaccounts")
public class MpAccountsController {
    @Autowired
    private MpAccountsService mpAccountsService;

    @RequestMapping(value = "/accountslist",method = {RequestMethod.GET,RequestMethod.POST})
    public String useradd(HttpServletRequest request,
                          HttpServletResponse response) {
        return "manageaccounts/accountslist";
    }

    @RequestMapping(value = "/accountsaddform",method ={RequestMethod.GET,RequestMethod.POST})
    public String accountsaddform(HttpServletRequest request,
                                  HttpServletResponse response) {
        return "manageaccounts/accountsadd";
    }

    // 插入账户
    @RequestMapping(value = "/addaccounts",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addAccounts(MpAccountsEntity accounts,
                                  HttpServletResponse response) {
        JSONObject returnObj = new JSONObject();
        returnObj.put("errorCode", 0);
        User user = UserUtils.getUser();//获得当前用户
        accounts.setUserid(user.getId());

        if (StringUtils.isNotBlank(accounts.getSecret())) {

            mpAccountsService.insert(accounts);

        }
        return returnObj;
    }

    // 获取数据
    @RequestMapping(value = "/accounts/fetchdata",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public void getUsers(int iDisplayStart, int iDisplayLength,
                         HttpServletResponse response) {
        User user = UserUtils.getUser();// 获得当前用户

        List<MpAccountsEntity> users = null;

        if (user.getId() == 1) {//超级管理员获取所有的公众号
            List<MpAccountsEntity> accounts = mpAccountsService.getAllMpAccounts();
            List<MpAccountsEntity> qyAccounts = mpAccountsService.getAllQpAccounts();
            accounts.addAll(qyAccounts);
            users=accounts;
        } else {
            users = mpAccountsService.getAllAccounts(user.getId());
        }
        JSONObject returnObj = new JSONObject();
        returnObj.put("aaData", JSONArray.fromObject(users));
        OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
    }

    // 修改账户
    @RequestMapping(value = "/updateaccounts",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateaccounts(MpAccountsEntity accounts,
                                     String oldappid, HttpServletResponse response) {
        JSONObject returnObj = new JSONObject();
        returnObj.put("errorCode", 0);
        User user = UserUtils.getUser();// 获得当前用户
        MpAccountsEntity isexist = mpAccountsService
                .getMpAccountsAppid(accounts.getAppid());// 新的公众号是否存在
        mpAccountsService.updateByPrimaryKey(accounts);
        if (accounts != null && StringUtils.isNotBlank(accounts.getAppid())) {
            if (StringUtils.equals(accounts.getAppid(), oldappid)) {// appid未做修改
                accounts.setUpdatetime(new Date());
                accounts.setAccesstoken(isexist.getAccesstoken());
                mpAccountsService.updateByPrimaryKey(accounts);
            } else {
                if (isexist != null) {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("userid", user.getId());
                    params.put("accountsid", accounts.getAppid());
                    int count = mpAccountsService.getUserAccounts(params);// 新的公众号此人是否已经在管理
                    if (count > 0) {
                        returnObj.put("errorCode", 1); // 新公众号此人已经在管理
                    } else {// 将此人与新的公众号进行关联
                        Map<String, Object> param = new HashMap<String, Object>();
                        param.put("userid", user.getId());
                        param.put("accountsid", isexist.getId());
                        mpAccountsService.insertUserAccounts(param);
                    }
                } else {
                    returnObj.put("errorCode", 2);// 新公众号不存在，需添加
                }
            }
        } else {
            returnObj.put("errorCode", 3);// 参数错误
        }
        return returnObj;
    }

    // //启用账户
    // @RequestMapping(value = "startaccounts")
    // @ResponseBody
    // public JSONObject startaccounts(Long id,
    // HttpServletResponse response) {
    // JSONObject returnObj = new JSONObject();
    // returnObj.put("errorCode", 0);
    // mpAccountsService.startByPrimaryKey(id);
    // return returnObj;
    // }

    // 删除账户
    @RequestMapping(value = "/deleteaccounts",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteaccounts(String id) {
        JSONObject returnObj = new JSONObject();
        User user = UserUtils.getUser();// 获得当前用户
        returnObj.put("errorCode", 0);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userid", user.getId());
        params.put("accountsid", id);
        //mpAccountsService.deleteByUserAccount(params);
        mpAccountsService.deleteByPrimaryKey(Long.valueOf(id));
        return returnObj;
    }

    // 获取详细信息
    @RequestMapping(value = "/getaccountdetail",method = RequestMethod.GET)
    public String getaccountdetail(Long id, HttpServletResponse response,
                                   Model model) {
        MpAccountsEntity accountsEntity = mpAccountsService.getDetail(id);
        model.addAttribute("accountsEntity", accountsEntity);
        return "manageaccounts/detail";
    }
}
