package com.reyun.controller.manage;

import com.reyun.dic.LogEnumType;
import com.reyun.dic.OperateObjectEnumType;
import com.reyun.exception.TipException;
import com.reyun.model.Account;
import com.reyun.model.App;
import com.reyun.security.annotation.CurrentAccount;
import com.reyun.service.AppService;
import com.reyun.service.UserLogService;
import com.reyun.util.ResultModel;
import com.reyun.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/mng/app")
public class MngAppController {
    protected Logger logger = LoggerFactory.getLogger(MngAppController.class);

    @Autowired
    private AppService appService;

    @Autowired
    private UserLogService userLogService;



    @RequestMapping(value = "find", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel list(HttpServletRequest request, @CurrentAccount Account loginAccount) {
//		userLogService.insertLog(loginAccount.getId(), LogEnumType.FIND.getCode(), LogEnumType.FIND.getName() + "应用列表", null);
        userLogService.insertLog(loginAccount, LogEnumType.FIND.getCode(), LogEnumType.FIND.getName() + "应用列表", null, null, OperateObjectEnumType.APP.getCode());
        return ResultModel.OK(appService.listAppByAccount(loginAccount.getId()));
    }

    @RequestMapping(value = "find/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel listone(HttpServletRequest request, @PathVariable Long id, @CurrentAccount Account loginAccount) {
        App app = appService.findById(id);
        userLogService.insertLog(loginAccount, LogEnumType.FIND.getCode(), LogEnumType.FIND.getName() + "应用" + app.getName(), app, id, OperateObjectEnumType.APP.getCode());
        return ResultModel.OK(app);
    }

    @RequestMapping(value = "find/getcategorys", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel listCategory(HttpServletRequest request, @CurrentAccount Account loginAccount) {
        return ResultModel.OK(appService.listCategory());
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public ResultModel create(HttpServletRequest request, @RequestBody App resource, @CurrentAccount Account account) {
        App app = appService.create(resource, account.getId());
        userLogService.insertLog(account, LogEnumType.CREATE.getCode(), LogEnumType.CREATE.getName() + "应用" + app.getName(), app, app.getId(), OperateObjectEnumType.APP.getCode());
        return ResultModel.OK(app);
    }

    @RequestMapping(value = "update", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel update(HttpServletRequest request, HttpServletResponse response,
                              @RequestBody App resource, @CurrentAccount Account account) {
        App app = appService.update(resource, account.getId());
        userLogService.insertLog(account, LogEnumType.UPDATE.getCode(), LogEnumType.UPDATE.getName() + "应用" + app.getName(), app, app.getId(), OperateObjectEnumType.APP.getCode());
        return ResultModel.OK(app);
    }

    @RequestMapping(value = "enable/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel enable(HttpServletRequest request, @PathVariable Long id, @CurrentAccount Account account) {

        try {
            App app = appService.enable(id, account.getId());
            userLogService.insertLog(account, LogEnumType.UPDATE.getCode(), "启用应用" + app.getName(), app, app.getId(), OperateObjectEnumType.APP.getCode());
        } catch (Exception e) {
            logger.error("授权失败", e);
            throw new TipException("授权失败");
        }
        return ResultModel.OK();
    }

    @RequestMapping(value = "forbidden/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel forbidden(HttpServletRequest request, @PathVariable Long id, @CurrentAccount Account account) {

        try {
            App app = appService.forbidden(id, account.getId());
            userLogService.insertLog(account, LogEnumType.UPDATE.getCode(), "停用应用" + app.getName(), app, app.getId(), OperateObjectEnumType.APP.getCode());
        } catch (Exception e) {
            logger.error("授权失败", e);
            throw new TipException("授权失败");
        }
        return ResultModel.OK();
    }

    @RequestMapping(value = "valid", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel check(@RequestParam String name, @CurrentAccount Account account) {
        Boolean flag = appService.validAppleId(account.getId(), name);
        if (!flag) {
            return ResultModel.OK(false);
        } else {
            return ResultModel.OK(true);
        }
    }

    @RequestMapping(value = "validdel/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel validDel(HttpServletRequest request, @PathVariable Long id, @CurrentAccount Account loginAccount) {
        App app = appService.findById(id);
        if (app.getDelFlag()) {
            return ResultModel.OK(true);
        } else {
            return ResultModel.OK(false);
        }
    }

    @RequestMapping(value = "validname", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel checkName(@RequestParam String name, @CurrentAccount Account account) {
        Boolean flag = appService.validName(account.getId(), name);
        if (!flag) {
            return ResultModel.OK(false);
        } else {
            return ResultModel.OK(true);
        }
    }

    @RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public ResultModel delete(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id, @CurrentAccount Account account) {
        try {
            App app = appService.delete(id, account.getId());
            String cookieId = getCookieToken(request.getCookies(), "ryioLastApp");
            if (!StringUtil.isEmpty(cookieId) && id.toString().equals(cookieId)) {
                Cookie cookie = new Cookie("ryioLastApp", null);
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
            userLogService.insertLog(account, LogEnumType.DELETE.getCode(), LogEnumType.DELETE.getName() + "应用" + app.getName(), app, app.getId(), OperateObjectEnumType.APP.getCode());
        } catch (Exception e) {
            logger.error("授权失败", e);
            throw new TipException("授权失败");
        }
        return ResultModel.OK();
    }

    private String getCookieToken(Cookie[] cookies, String name) {

        String token = null;

        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    token = cookie.getValue();
                }
            }
        }

        return token;
    }

}
