package com.jeeplus.modules.API.works.appshow;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.appversion.entity.Appversions;
import com.jeeplus.modules.appversion.service.AppversionsService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workappshow.entity.Workappshow;
import com.jeeplus.modules.workappshow.service.WorkappshowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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.servlet.mvc.support.RedirectAttributes;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Controller
@RequestMapping(value="${frontPath}/app/show")
public class WorkAppShowController extends BaseController {

    @Autowired
    private WorkappshowService workappshowService;

    private  Lock lock = new ReentrantLock();

    /**
     * 获取用户APP端信息展示
     * @return json数据
     */
    @Transactional
        @RequestMapping(value = "getAppShow", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getAppShow(String userId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            lock.lock();
            if (userId == null || userId.equals("")){
                userId = UserUtils.getUser().getId();
            }
            boolean status = false;
            User user = UserUtils.getUser();
            String comId = user.getComId();
            if (comId.equals("1")){
                status = true;
            }
            Workappshow workappshow = new Workappshow();
            workappshow.setUserId(userId);
            workappshow.setDelFlag("0");
            workappshow.setCompanyId(UserUtils.get(userId).getComId());
            List<Workappshow> list = workappshowService.findList(workappshow);
            if(!status && list==null){
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_2005);
                j.setMsg("获取用户APP端信息展示失败");
                j.put("data", new HashMap<>());
            }else{
                Workappshow workappshow1 = new Workappshow();
                Map map = new HashMap();
                if (list.size()==0){
                    Workappshow appshow = new Workappshow();
                    if (status){
                        appshow.setUserId(userId);
                        appshow.setDelFlag("1");
                        appshow.setAuditStatus("1");
                        appshow.setCalendarStatus("1");
                        appshow.setCompanyRuleStatus("1");
                        appshow.setNotifyStatus("1");
                        appshow.setSignInStatus("1");
                        appshow.setReportStatus("1");
                        appshow.setMeetingStatus("1");
                        appshow.setBusinessStatus("1");
                        appshow.setUserId(userId);
                        appshow.setCompanyId(UserUtils.getSelectCompany().getId());
                        appshow.setManageCalendarStatus("1");
                    }else {
                        appshow.setUserId(userId);
                        appshow.setDelFlag("0");
                        appshow.setAuditStatus("0");
                        appshow.setCalendarStatus("0");
                        appshow.setCompanyRuleStatus("0");
                        appshow.setNotifyStatus("0");
                        appshow.setSignInStatus("0");
                        appshow.setReportStatus("0");
                        appshow.setMeetingStatus("0");
                        appshow.setBusinessStatus("0");
                        appshow.setUserId(userId);
                        appshow.setCompanyId(UserUtils.getSelectCompany().getId());
                        if (UserUtils.isManager()) {
                            appshow.setManageCalendarStatus("0");
                        } else {
                            appshow.setManageCalendarStatus("1");
                        }
                        workappshowService.save(appshow);
                    }
                    list.add(appshow);
                }
                if (list.size()!=0){
                    workappshow1 = list.get(0);
                    map.put("notifyStatus",workappshow1.getNotifyStatus());
                    map.put("companyRuleStatus",workappshow1.getCompanyRuleStatus());
                    map.put("reportStatus",workappshow1.getReportStatus());
                    map.put("calendarStatus",workappshow1.getCalendarStatus());
                    map.put("auditStatus",workappshow1.getAuditStatus());
                    map.put("signInStatus",workappshow1.getSignInStatus());
                    map.put("businessStatus",workappshow1.getBusinessStatus());
                    map.put("companyName",UserUtils.getSelectCompany().getName());
                    map.put("companyId",UserUtils.getSelectCompany().getId());
                    if (UserUtils.isManager()){
                        map.put("manageCalendarStatus",workappshow1.getManageCalendarStatus());
                        map.put("isManager","1");
                    }else {
                        map.put("isManager","0");
                    }
                }
                j.put("data",map);
                j.setMsg("获取用户APP端信息展示成功");
                j.setErrorCode(ErrorCode.code_1004);
            }
        }catch (Exception e){
            logger.info("Exception = "+e.getMessage());
            j.setMsg("获取用户APP端信息展示失败");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
        }finally {
            lock.unlock();
        }
        return j;
    }

    /**
     * 获取用户APP端信息展示
     * @return json数据
     */
    @Transactional
    @RequestMapping(value = "getAppShowNew", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getAppShowNew(String userId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (userId == null || userId.equals("")){
            userId = UserUtils.getUser().getId();
        }
        boolean lockStatus = false;
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            if (jedis.get(userId)==null){
                jedis.set(userId,userId);
            }else {
                jedis.del(userId);
                lock.lock();
                lockStatus = true;
            }
            /*if (request.getSession().getServletContext().getAttribute(userId)==null){
                request.getSession().getServletContext().setAttribute(userId, userId);
                //logger.info("--------------------------------uId="+request.getSession().getServletContext().getAttribute(userId));
            }else {
                request.getSession().getServletContext().removeAttribute(userId);
                //logger.info("--------------------------------userId="+request.getSession().getServletContext().getAttribute(userId));
                lock.lock();
                lockStatus = true;
             }*/
            boolean status = false;
            User user = UserUtils.getUser();
            String comId = user.getComId();
            if (comId.equals("1")){
                status = true;
            }
            Workappshow workappshow = new Workappshow();
            workappshow.setUserId(userId);
            workappshow.setDelFlag("0");
            workappshow.setCompanyId(UserUtils.get(userId).getComId());
            List<Workappshow> list = workappshowService.findList(workappshow);
            if(!status && list==null){
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_2005);
                j.setMsg("获取用户APP端信息展示失败");
                j.put("data", new HashMap<>());
            }else{
                Workappshow workappshow1 = new Workappshow();
                Map map = new HashMap();
                if (list.size()==0){
                    Workappshow appshow = new Workappshow();
                    if (status){
                        appshow.setUserId(userId);
                        appshow.setDelFlag("1");
                        appshow.setAuditStatus("1");
                        appshow.setCompanyRuleStatus("1");
                        appshow.setCalendarStatus("1");
                        appshow.setNotifyStatus("1");
                        appshow.setReportStatus("1");
                        appshow.setSignInStatus("1");
                        appshow.setMeetingStatus("1");
                        appshow.setBusinessStatus("1");
                        appshow.setUserId(userId);
                        appshow.setCompanyId(UserUtils.getSelectCompany().getId());
                        appshow.setManageCalendarStatus("1");
                    }else {
                        appshow.setUserId(userId);
                        appshow.setDelFlag("0");
                        appshow.setAuditStatus("0");
                        appshow.setCalendarStatus("0");
                        appshow.setCompanyRuleStatus("0");
                        appshow.setReportStatus("0");
                        appshow.setNotifyStatus("0");
                        appshow.setSignInStatus("0");
                        appshow.setMeetingStatus("0");
                        appshow.setBusinessStatus("0");
                        appshow.setUserId(userId);
                        appshow.setCompanyId(UserUtils.getSelectCompany().getId());
                        if (UserUtils.isManager()) {
                            appshow.setManageCalendarStatus("0");
                        } else {
                            appshow.setManageCalendarStatus("1");
                        }
                        workappshowService.save(appshow);
                    }
                    list.add(appshow);
                }
                if (list.size()!=0){
                    workappshow1 = list.get(0);
                    map.put("notifyStatus",workappshow1.getNotifyStatus());
                    map.put("companyRuleStatus",workappshow1.getCompanyRuleStatus());
                    map.put("reportStatus",workappshow1.getReportStatus());
                    map.put("calendarStatus",workappshow1.getCalendarStatus());
                    map.put("auditStatus",workappshow1.getAuditStatus());
                    map.put("signInStatus",workappshow1.getSignInStatus());
                    map.put("meetingStatus",workappshow1.getMeetingStatus()==null?"1":workappshow1.getMeetingStatus());
                    map.put("businessStatus",workappshow1.getBusinessStatus()==null?"1":workappshow1.getBusinessStatus());
                    map.put("companyName",UserUtils.getSelectCompany().getName());
                    map.put("companyId",UserUtils.getSelectCompany().getId());
                    if (UserUtils.isManager()){
                        map.put("manageCalendarStatus",workappshow1.getManageCalendarStatus());
                        map.put("isManager","1");
                    }else {
                        map.put("isManager","0");
                    }
                }
                j.put("data",map);
                j.setMsg("获取用户APP端信息展示成功");
                j.setErrorCode(ErrorCode.code_1004);
            }
        }catch (Exception e){
            logger.info("Exception = "+e.getMessage());
            j.setMsg("获取用户APP端信息展示失败");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
        }finally {
            if (lockStatus){
                lock.unlock();
            }else {
                //request.getSession().getServletContext().removeAttribute(userId);
                jedis.del(userId);
            }
            JedisUtils.returnResource(jedis);
        }
        return j;
    }

    /**
     * 查看用户公告信息
     * @return json数据
     */
    @RequestMapping(value = "createAppShow", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson createAppShow(String userId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (userId == null || userId.equals("")){
                userId = UserUtils.getUser().getId();
            }
            Workappshow appshow = new Workappshow();
            appshow.setDelFlag("0");
            appshow.setUserId(userId);
            List<Workappshow> list = workappshowService.findList(appshow);
            if (list!=null && list.size()!=0){
                j.setMsg("添加用户APP端信息展示失败,信息已存在");
                j.setErrorCode(ErrorCode.code_1009);
                j.setSuccess(true);
                return j;
            }
            Workappshow workappshow = new Workappshow();
            workappshow.setUserId(userId);
            workappshow.setDelFlag("0");
            workappshow.setAuditStatus("0");
            workappshow.setCalendarStatus("0");
            workappshow.setCompanyRuleStatus("0");
            workappshow.setNotifyStatus("0");
            workappshow.setReportStatus("0");
            workappshow.setMeetingStatus("0");
            workappshow.setSignInStatus("0");
            workappshow.setBusinessStatus("0");
            workappshow.setUserId(userId);
            if (UserUtils.isManager()){
                workappshow.setManageCalendarStatus("0");
            }else {
                workappshow.setManageCalendarStatus("1");
            }
            workappshowService.save(workappshow);
        }catch (Exception e){
            logger.info("Exception = "+e.getMessage());
            j.setMsg("添加用户APP端信息展示失败");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
        }
         return j;
    }

    /**
     * 查看用户公告信息
     * @return json数据
     */
    @RequestMapping(value = "updateAppShow", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson updateAppShow(String userId,String auditStatus,String notifyStatus,String companyRuleStatus,String calendarStatus,
                                  String reportStatus,String signInStatus,String manageCalendarStatus,String businessStatus,
                                  HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            lock.lock();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (userId == null || userId.equals("")){
                userId = UserUtils.getUser().getId();
            }
            Workappshow appshow = new Workappshow();
            appshow.setDelFlag("0");
            appshow.setUserId(userId);
            appshow.setCompanyId(UserUtils.getSelectCompany().getId());
            List<Workappshow> list = workappshowService.findList(appshow);
            if (list!=null && list.size()!=0){
                Workappshow workappshow = list.get(0);
                workappshow.setUserId(userId);
                workappshow.setDelFlag("0");
                workappshow.setAuditStatus(auditStatus);
                workappshow.setCalendarStatus(calendarStatus);
                workappshow.setCompanyRuleStatus(companyRuleStatus);
                workappshow.setNotifyStatus(notifyStatus);
                workappshow.setReportStatus(reportStatus);
                workappshow.setSignInStatus(signInStatus);
                workappshow.setBusinessStatus(businessStatus);
                workappshow.setMeetingStatus("1");
                if (UserUtils.isManager()){
                    workappshow.setManageCalendarStatus("0");
                }else {
                    workappshow.setManageCalendarStatus("1");
                }
                if (manageCalendarStatus!=null && !manageCalendarStatus.equals("")){
                    workappshow.setManageCalendarStatus(manageCalendarStatus);
                }
                workappshowService.save(workappshow);
            }else {
                j.setMsg("修改用户APP端信息展示失败，用户信息不存在");
                j.setErrorCode(ErrorCode.code_2005);
                j.setSuccess(false);
            }
        }catch (Exception e){
            logger.info("Exception = "+e.getMessage());
            j.setMsg("修改用户APP端信息展示失败");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
        }finally {
            lock.unlock();
        }
        return j;
    }


    /**
     * 查看用户公告信息
     * @return json数据
     */
    @RequestMapping(value = "updateAppShowNew", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson updateAppShowNew(String userId,String auditStatus,String notifyStatus,String companyRuleStatus,String calendarStatus,
                                  String reportStatus,String signInStatus,String meetingStatus,String manageCalendarStatus,String businessStatus,
                                  HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            lock.lock();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (userId == null || userId.equals("")){
                userId = UserUtils.getUser().getId();
            }
            Workappshow appshow = new Workappshow();
            appshow.setDelFlag("0");
            appshow.setUserId(userId);
            appshow.setCompanyId(UserUtils.getSelectCompany().getId());
            List<Workappshow> list = workappshowService.findList(appshow);
            if (list!=null && list.size()!=0){
                Workappshow workappshow = list.get(0);
                workappshow.setUserId(userId);
                workappshow.setDelFlag("0");
                workappshow.setAuditStatus(auditStatus);
                workappshow.setCalendarStatus(calendarStatus);
                workappshow.setCompanyRuleStatus(companyRuleStatus);
                workappshow.setNotifyStatus(notifyStatus);
                workappshow.setReportStatus(reportStatus);
                workappshow.setMeetingStatus(meetingStatus==null?"1":meetingStatus);
                workappshow.setBusinessStatus(businessStatus==null?"1":businessStatus);
                workappshow.setSignInStatus(signInStatus);
                if (UserUtils.isManager()){
                    workappshow.setManageCalendarStatus("0");
                }else {
                    workappshow.setManageCalendarStatus("1");
                }
                if (manageCalendarStatus!=null && !manageCalendarStatus.equals("")){
                    workappshow.setManageCalendarStatus(manageCalendarStatus);
                }
                workappshowService.save(workappshow);
            }else {
                j.setMsg("修改用户APP端信息展示失败，用户信息不存在");
                j.setErrorCode(ErrorCode.code_2005);
                j.setSuccess(false);
            }
        }catch (Exception e){
            logger.info("Exception = "+e.getMessage());
            j.setMsg("修改用户APP端信息展示失败");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
        }finally {
            lock.unlock();
        }
        return j;
    }

}
