package com.palmnest.webapp.controller.api;

import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.dto.input.AirConditionerAddTimeInputDto;
import com.palmnest.application.dto.input.AirSelectCompanyInputDto;
import com.palmnest.model.*;
import com.palmnest.service.AppUserService;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.FloorInfoManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.estateserve.airconditioner.ConditionerAddTimeService;
import com.palmnest.service.redis.BaseRedisService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping(value = "/api/air")
public class ApiAirConditionerAddTimeController {


    @Autowired
    private ConditionerAddTimeService conditionerAddTimeService;
    @Autowired
    private UserManager userManager;
    @Autowired
    private BaseRedisService baseRedisService;
    @Autowired
    private FloorInfoManager floorInfoManager;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private VirtualArchManager virtualArchManager;

    /**
     * @param request
     * @return 空调加时列表
     */
    @RequestMapping(value = "/auditList")
    @ResponseBody
    public AppResultDto auditList(HttpServletRequest request) {

        log.info("ApiAirConditionerAddTimeController list======");

        try {

            String userName = baseRedisService.get(request.getHeader("token"));
            log.info("ApiAirConditionerAddTimeController list======token={},userName={}", request.getHeader("token"), userName);
            if (userName == null) {
                return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
            }
            User user = userManager.getUserByUsername2(userName);

            // User userAir21 = userManager.findByFunctionAndUser(CodeConstants.CSP21_PERMISSION, user.getId());
            // User userAir22 = userManager.findByFunctionAndUser(CodeConstants.CSP22_PERMISSION, user.getId());
            // User userAir23 = userManager.findByFunctionAndUser(CodeConstants.CSP23_PERMISSION, user.getId());

            String isQueryMarchInside = request.getParameter("isQueryMarchInside");// 是否查询以前及将来三个月内订单
            if (StringUtils.isEmpty(isQueryMarchInside)) {
                isQueryMarchInside = "0";
            }

            Integer airSwitchUserId = null;// 空调开关人员Id
            String airswitchPermission = request.getParameter("airswitchPermission");// 空调加时开发权限
            if (StringUtils.isEmpty(isQueryMarchInside)) {
                airswitchPermission = "0";
            }


            // 空调加时审批权限
			/*String airAuditPermission = "0";//待审批的数据
			String airAuditRoleId     = "0";
			if (userAir21 != null) {
				airAuditPermission = GoodsCodeConstants.AIR_AUDITKE.toString();
				Role role = userManager.findRoleByFunctionAndUser(CodeConstants.CSP21_PERMISSION, user.getId());
				airAuditRoleId = role.getId().toString();
			}
			if (userAir22 != null) {
				//airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITKEL.toString();
				airAuditPermission = GoodsCodeConstants.AIR_AUDITKEL.toString();

				Role role = userManager.findRoleByFunctionAndUser(CodeConstants.CSP22_PERMISSION, user.getId());
				airAuditRoleId = role.getId().toString();
			}
			if (userAir23 != null) {
				//airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITGZL.toString();
				airAuditPermission = GoodsCodeConstants.AIR_AUDITGZL.toString();

				Role role = userManager.findRoleByFunctionAndUser(CodeConstants.CSP23_PERMISSION, user.getId());
				airAuditRoleId = role.getId().toString();
			}*/

			/*String                     roleToFloorIds = "";
			List<AppUserFloorRelation> userFloorList  = userManager.getAppUserFloorByUserId(Integer.parseInt(user.getId().toString()), Integer.parseInt(airAuditRoleId));
			if (userFloorList != null && userFloorList.size() > 0) {
				for (int i = 0; i < userFloorList.size(); i++) {
					AppUserFloorRelation userFloor = userFloorList.get(i);
					if (null != userFloor.getFloor_id()) {
						roleToFloorIds += userFloor.getFloor_id().toString() + ",";
					}
				}
			}
			if (StringUtils.isNotEmpty(roleToFloorIds)) {
				roleToFloorIds = roleToFloorIds.replaceAll("[,]$", "");
			}*/


            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            int pageNo = Integer.parseInt(request.getParameter("pageNo"));
            Map<String, Object> params = new HashMap<String, Object>();
            String status = request.getParameter("status");
            String floorId = request.getParameter("floorId");// 楼层id 只过滤一层楼


            String applyTime = request.getParameter("applyTime");// 2018-09-08 //申请时间

            String isAppManageBook = request.getParameter("isAppManageBook");
            String preBookUserId = "";// 代订人ID
            if (StringUtils.isNotEmpty(isAppManageBook) && "1".equals(isAppManageBook)) {
                preBookUserId = user.getId().toString();
            }
            if (StringUtils.isNotEmpty(airswitchPermission) && "1".equals(airswitchPermission)) {
                airSwitchUserId = user.getId().intValue();
            }


            // 还要根据管员角色 对应楼层 及审批的状态来过滤
            // TODO
            params.put("status", status);
            // params.put("airAuditPermission", airAuditPermission);
            // params.put("roleToFloorIds", roleToFloorIds);
            params.put("applyTime", applyTime);
            params.put("floorId", floorId);
            params.put("preBookUserId", preBookUserId);
            params.put("airSwitchUserId", airSwitchUserId);
            params.put("isQueryMarchInside", isQueryMarchInside);
            // params.put("virtualId", virtualId);

            // appuser 对应项目ID
            String organizationId = "#";
            List<AppUserOrgnizationRelation> orgList = userManager.getAppUserOrgByUserId(Integer.parseInt(user.getId().toString()));
            if (orgList != null && orgList.size() > 0) {
                AppUserOrgnizationRelation orgRe = orgList.get(0);
                if (orgRe != null) {
                    organizationId = orgRe.getOrgId().toString();
                }
            }
            params.put("organizationId", organizationId);


            Page page = conditionerAddTimeService.findPageBy(params, pageSize, pageNo);
            return AppResultUtil.createSuccesDto(page);
        } catch (Exception e) {
            log.error("ApiAirConditionerAddTimeController list error", e);
            return AppResultUtil.createErrorDto(AppConstants.REPAIR_BILL_LIST_ERROR, "查询列表失败" + LogExceptionStackUtil.LogExceptionStack(e));
        }
    }


    /**
     * @param request
     * @return 查找维修单详情
     */
    @RequestMapping(value = "/getDetail")
    @ResponseBody
    public AppResultDto getDetail(@RequestParam("id") Long id) {
        log.info("ApiAirConditionerAddTimeController getDetail======");

        return AppResultUtil.createSuccesDto(conditionerAddTimeService.findById(id));
    }

    /**
     * 同意放行
     */
    @RequestMapping(value = "/audit")
    @ResponseBody
    public AppResultDto audit(@ModelAttribute("airConditionerAddTimeInputDto") AirConditionerAddTimeInputDto dto, HttpServletRequest request) {
        log.info("ApiAirConditionerAddTimeController agree======");

        dto.setBillFrom(CodeConstants.ANDROID);
        return conditionerAddTimeService.audit(dto, request);
    }

    /**
     * 同意放行
     */
    @RequestMapping(value = "/cancel")
    @ResponseBody
    public AppResultDto cancel(@ModelAttribute("airConditionerAddTimeInputDto") AirConditionerAddTimeInputDto dto, HttpServletRequest request) {
        log.info("ApiAirConditionerAddTimeController agree======");

        dto.setBillFrom(CodeConstants.ANDROID);
        return conditionerAddTimeService.cancel(dto, request);
    }

    /**
     * 空调开关人员
     * @param request
     * @return
     */
    @RequestMapping(value = "/getAirSwitchUser")
    @ResponseBody
    public AppResultDto getAirSwitchUser(HttpServletRequest request) {

        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        User tokenUser = userManager.getUserByUsername2(userName);

        // appuser 对应项目ID
        Integer organizationId = 0;
        List<AppUserOrgnizationRelation> orgList = userManager.getAppUserOrgByUserId(Integer.parseInt(tokenUser.getId().toString()));
        if (orgList != null && orgList.size() > 0) {
            AppUserOrgnizationRelation orgRe = orgList.get(0);
            if (orgRe != null) {
                organizationId = orgRe.getOrgId();
            }
        }

        // 空调开关人员
        List<User> users = userManager.findByFunctionGeneral(organizationId, CodeConstants.AIRSWITCH_PERMISSION);

        List<JSONObject> usersList = new ArrayList<JSONObject>();
        for (User user : users) {
            JSONObject usrsMap = new JSONObject();
            usrsMap.put("switchUserId", user.getId().toString());
            usrsMap.put("name", user.getFullName());
            usrsMap.put("telephone", user.getTelephone());
            usersList.add(usrsMap);
        }

        return AppResultUtil.createSuccesDto(usersList);
    }


    /**
     * 物品放行
     * 选择公司
     * @throws Exception
     */
    @RequestMapping(value = "/selectCompany")
    @ResponseBody
    public AppResultDto selectCompany(@ModelAttribute("airSelectCompanyInputDto") AirSelectCompanyInputDto dto, HttpServletRequest request) throws Exception {

        dto.setAir(true);
        dto.setBillFrom(CodeConstants.ANDROID);
        return conditionerAddTimeService.selectCompany(dto, request);
    }

    /**
     * 空调加时申请确认
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getRoomsAndAreaByVirtualId")
    @ResponseBody
    public AppResultDto getRoomsAndAreaByVirtualId(@ModelAttribute("airConditionerAddTimeInputDto") AirConditionerAddTimeInputDto dto, HttpServletRequest request) throws Exception {

        log.info("WxAirConditionerAddTimeController getRoomsAndAreaByVirtualId======");
        return conditionerAddTimeService.getRoomsAndAreaByVirtualId(dto, request);
    }


    /**
     * 空调加时申请
     * @param request
     * @return
     */
    @RequestMapping(value = "/apply")
    @ResponseBody
    public AppResultDto apply(@ModelAttribute("airConditionerAddTimeInputDto") AirConditionerAddTimeInputDto dto, HttpServletRequest request) {

        log.info("ApiAirConditionerAddTimeController apply======");
        dto.setBillSource("1");// 空调加时
        dto.setBillFrom(CodeConstants.ANDROID);
        dto.setIsAppManageBook(1);
        return conditionerAddTimeService.apply(dto, request);
    }

    /**
     * 空调加时申请确认
     * @param request
     * @return
     */
    @RequestMapping(value = "/applyConfirm")
    @ResponseBody
    public AppResultDto applyConfirm(HttpServletRequest request) {

        log.info("ApiAirConditionerAddTimeController applyConfirm======");
        return conditionerAddTimeService.applyConfirm(request);
    }

    /**
     * 获取用户所管理的楼层
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getFloorNosByUserId")
    @ResponseBody
    public AppResultDto getFloorNosByUserId(HttpServletRequest request, HttpServletResponse response) {

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        String userName = baseRedisService.get(request.getHeader("token"));
        if (userName == null) {
            return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
        }
        User user = userManager.getUserByUsername2(userName);
        Role role21 = userManager.findRoleByFunctionAndUser(CodeConstants.CSP21_PERMISSION, user.getId());
        Role role22 = userManager.findRoleByFunctionAndUser(CodeConstants.CSP22_PERMISSION, user.getId());
        Role role23 = userManager.findRoleByFunctionAndUser(CodeConstants.CSP23_PERMISSION, user.getId());

        // 空调加时审批权限
        String airAuditRoleId = "0";
        if (role21 != null) {
            airAuditRoleId = role21.getId().toString();
        }
        if (role22 != null && StringUtils.isNotEmpty(airAuditRoleId)) {
            // airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITKEL.toString();
            airAuditRoleId = role22.getId().toString();
        }
        if (role23 != null && StringUtils.isNotEmpty(airAuditRoleId)) {
            // airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITGZL.toString();
            airAuditRoleId = role23.getId().toString();
        }


        try {
            List<AppUserFloorRelation> userFloorList = userManager.getAppUserFloorByUserId(Integer.parseInt(user.getId().toString()), Integer.parseInt(airAuditRoleId));
            if (userFloorList != null && userFloorList.size() > 0) {
                for (int i = 0; i < userFloorList.size(); i++) {
                    AppUserFloorRelation userFloor = userFloorList.get(i);
                    Map<String, Object> map = new HashMap<String, Object>();
                    FloorInfo floor = floorInfoManager.get(userFloor.getFloor_id());
                    map.put("floorName", floor.getName() + "楼");
                    map.put("floorId", floor.getId() == null ? "" : floor.getId());
                    list.add(map);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取楼层失败" + e.getMessage());
        }

        return AppResultUtil.createSuccesDto(list);
    }

}
