package com.jpsoft.shinestar.modules.mobile.controller;

 import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
 import com.jpsoft.shinestar.modules.common.dto.MessageResult;
 import com.jpsoft.shinestar.modules.common.utils.StringUtils;
 import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
 import org.joda.time.DateTime;
 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.ZSetOperations;
 import org.springframework.web.bind.annotation.*;

 import javax.servlet.http.HttpServletRequest;
 import java.util.*;
 import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/mobile/companyInfoApi")
@Slf4j
public class CompanyInfoApiController {
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private SchoolServeService schoolServeService;
    @Autowired
    private PersonPopedomService personPopedomService;
    @Autowired
    private PersonRoleInfoService personRoleInfoService;
    @Autowired
    private CompanyContactsService companyContactsService;
    @Autowired
    private ZSetOperations<String, Object> zSetOperations;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("rank")
    @ApiOperation(value = "查看网络连接情况")
    public MessageResult<Object> rank() {
        MessageResult<Object> messageResult = new MessageResult<>();

        try {
            DateTime now = DateTime.now();
            String key = "visitors_" + now.toString("yyyy-MM-dd");

            Set<ZSetOperations.TypedTuple<Object>> set = zSetOperations.reverseRangeWithScores(key,0,50);

            messageResult.setData(set);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    public String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-ip");
        }

        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    @GetMapping("link")
    @ApiOperation(value = "用于测试网络连接的方法 get 请求")
    public MessageResult<Boolean> link(HttpServletRequest request) {
        MessageResult<Boolean> messageResult = new MessageResult<>();

        try {
            DateTime now = DateTime.now();
            String key = "visitors_" + now.toString("yyyy-MM-dd");

            String remoteIP = getRemoteHost(request);

            if(!redisTemplate.hasKey(key)) {
                zSetOperations.add(key, remoteIP, 1);
                redisTemplate.expire(key, 1 , TimeUnit.DAYS);
            }
            else {
                zSetOperations.incrementScore(key, remoteIP, 1);
            }

            messageResult.setData(true);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("schoolServeList")
    @ResponseBody
    @ApiOperation(value = "学校开通的服务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolId", value = "学校id（管理端）", required = false, paramType = "query"),
      })
    public MessageResult<List<SchoolServe>> schoolServe(String schoolId) {
        MessageResult<List<SchoolServe>> messageResult = new MessageResult<>();

        try {
            List<SchoolServe> schoolServes = new ArrayList<>();

            Map<String,Object> searchParams = new HashMap<>();
            searchParams.put("status",1);
            schoolServes= schoolServeService.searchParams(searchParams);

            messageResult.setData(schoolServes);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("companyContactsList")
    @ResponseBody
    @ApiOperation(value = "公司联系方式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> companyContactsList(String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            Map<String,Object> map = new HashMap<>();
            PersonInfo personInfo = personInfoService.get(new Long(subject));
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            if (personPopedom == null){
                throw new Exception("用户角色数据错误");
            }

            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(companyInfo.getRelationCompanyId())){
                List<CompanyContacts> companyContactsList = companyContactsService.findByCompanyId(companyInfo.getRelationCompanyId());
                map.put("list",companyContactsList);
            }


            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("serviceCompanyIdList")
    @ResponseBody
    @ApiOperation(value = "居家养老服务公司列表")
    public MessageResult<Map> serviceCompanyIdList() {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            Map<String,Object> map = new HashMap<>();

            List<CompanyInfo> list = companyInfoService.findBySceneIdAndType("1","4");
            map.put("list",list);


            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
