package com.fjs.scenic.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fjs.scenic.entity.user.LinkMan;
import com.fjs.scenic.service.good.GoodsService;
import com.fjs.scenic.service.scenic.ScenicIndexService;
import com.fjs.scenic.service.user.LinkManService;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.ReturnResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


@RestController
@RequestMapping("/api/index")
public class IndexController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ScenicIndexService scenicIndexService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private LinkManService linkManService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @ApiOperation(value = "景区首页", notes = "景区首页")
    @GetMapping("/top")
    @ResponseBody
    public ReturnResult top(String flag) {
    	//null 0门票。，1是车票索道
    	return scenicIndexService.scenic(flag);
//        String token = request.getHeader(Cons.TOKEN.WECHAT);
//        Integer userId = (Integer) redisTemplate.opsForValue().get(token);
//        log.info("userid={}", userId);


      /*  ReturnResult indexTopData = (ReturnResult) redisTemplate.opsForValue().get("indexTopData");
        if (indexTopData != null) {
            return indexTopData;
        } else {
            ReturnResult newIndexTopData = scenicIndexService.scenic();
            redisTemplate.opsForValue().set("indexTopData", newIndexTopData);
            return newIndexTopData;
        }*/
    }

    @ApiOperation(value = "查询价格日历", notes = "查询价格日历")
    @GetMapping("/goodsOrderPrice/{goodsId}")
    @ResponseBody
    public ReturnResult goodsOrderPrice(@ApiParam(value = "门票id", required = true) @PathVariable("goodsId") Integer goodsId) {
        return goodsService.goodsOrderPrice(goodsId);
    }

    @ApiOperation(value = "查询时间区间", notes = "查询时间区间")
    @GetMapping("/goodsDateList/{priceRuleId}")
    @ResponseBody
    public ReturnResult goodsDateList(@ApiParam(value = "价格规则id", required = true) @PathVariable("priceRuleId") Integer priceRuleId) {
        return goodsService.getGoodsStock(priceRuleId);
    }


    @ApiOperation(value = "游客列表分页", notes = "游客列表分页")
    @GetMapping("/listLinkMan")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "int", paramType = "query")
    })
    public ReturnResult listLinkMan(HttpServletRequest request, LinkMan linkMan, int currentPage, int pageSize) {
        currentPage = (currentPage == 0) ? 1 : currentPage;
        pageSize = (pageSize == 0) ? 1 : pageSize;
        PageHelper.startPage(currentPage, pageSize);
        String token = request.getHeader(Cons.TOKEN.WECHAT);
        Integer userId = (Integer) redisTemplate.opsForValue().get(token);
        linkMan.setUserId(userId);
        List<LinkMan> linkManList = linkManService.select(linkMan);
        PageInfo<LinkMan> pageInfo = new PageInfo<>(linkManList);
        return ReturnResult.ok(pageInfo);
    }

    @ApiOperation(value = "获取默认游客", notes = "获取默认游客")
    @GetMapping("/getDefaultPerson")
    @ResponseBody
    public ReturnResult getDefaultPerson(HttpServletRequest request) {
        String token = request.getHeader(Cons.TOKEN.WECHAT);
        Integer userId = (Integer) redisTemplate.opsForValue().get(token);
        LinkMan linkMan = new LinkMan();
        linkMan.setUserId(userId);
        linkMan.setIsDefalt("1");
        List<LinkMan> linkManList = linkManService.select(linkMan);
        //List<LinkMan> linkManList = linkManService.selectByParam(null, " user_id=" + userId + " and is_defalt  = 1");
        return ReturnResult.ok(linkManList.size() > 0 ? linkManList.get(0) : null);
    }

    @ApiOperation(value = "新增/修改游客，废弃接口", notes = "新增/修改游客，废弃接口")
    @PostMapping("/CULinkMan2")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "联系人id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "证件类型", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDefalt", value = "是否默认", required = true, dataType = "string", paramType = "query")
    })
    public ReturnResult insertLinkMan(HttpServletRequest request, LinkMan linkMan) {

        String token = request.getHeader(Cons.TOKEN.WECHAT);
        Integer userId = (Integer) redisTemplate.opsForValue().get(token);

        linkMan.setUserId(userId);

        if (linkMan.getType() == null) {
            linkMan.setType("1");
        }

        //当新增的 为 默认的话，其他游客  设置为不是默认
        if (linkMan.getIsDefalt().equals("1")) {
            linkManService.updateByParam(" is_defalt=0 where user_id = " + userId);
        }

        int cu;

        LinkMan repeatMan = new LinkMan();
        repeatMan.setIdCard(linkMan.getIdCard());
        repeatMan.setUserId(userId);
        //检验当前用户下该身份证 是否已存在
        List<LinkMan> repeatInsert = linkManService.select(repeatMan);

        //id不为空 则为修改，反之则是删除
        if (linkMan.getId() != null) {

            List<LinkMan> repeatUpdate = linkManService.select(new LinkMan(linkMan.getId()));

            if (!repeatInsert.isEmpty() && !repeatUpdate.get(0).getIdCard().equals(linkMan.getIdCard())) {
                return ReturnResult.build(200, "该游客存在!");
            }

            cu = linkManService.update(linkMan);
        } else {

            if (!repeatInsert.isEmpty()) {
                return ReturnResult.build(200, "该游客已绑定!");
            }
            cu = linkManService.insert(linkMan);
        }

        return ReturnResult.ok(cu);
    }
    
    
    @ApiOperation(value = "新增游客", notes = "新增游客")
    @PostMapping("/CULinkMan")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "证件类型", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDefalt", value = "是否默认", required = true, dataType = "string", paramType = "query")
    })
    public ReturnResult addLinkMan(HttpServletRequest request, LinkMan linkMan) {

        String token = request.getHeader(Cons.TOKEN.WECHAT);
        Integer userId = (Integer) redisTemplate.opsForValue().get(token);
        if(userId==null){
        	return ReturnResult.OK("非法請求");
        }
        linkMan.setUserId(userId);
        if (linkMan.getType() == null) {
            linkMan.setType("1");
        }
        
       return linkManService.addLinkMan(linkMan);
    }
    

    @ApiOperation(value = "删除游客信息", notes = "删除游客信息")
    @PostMapping("/deleteLinkMan")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "联系人id", required = true, dataType = "int", paramType = "query")
    })
    public ReturnResult deleteLinkMan(Integer id) {
        /*int insert = linkManService.deleteByPrimaryKey(id);
        if(insert<=0){
        	return ReturnResult.error("删除失败，联系人至少保存180天");
        }
        return ReturnResult.ok(insert);*/
    	return linkManService.delete180(id);
    }

    @ApiOperation(value = "获取单个/多个游客信息", notes = "获取单个/多个游客信息")
    @PostMapping("/getLinkManForId")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "联系人id", required = true, dataType = "string", paramType = "query")
    })
    public ReturnResult getLinkManForId(String id) {
        if (id.contains(",")) {
            return ReturnResult.ok(linkManService.selectByParam(null, " id in (" + id + ")"));
        } else {
            return ReturnResult.ok(linkManService.select(new LinkMan(Integer.parseInt(id))));
        }

    }

    /**
     * 天气接口
     *
     * @return
     */
    @ApiOperation(value = "获取实况天气", notes = "获取实况天气")
    @GetMapping("/getWeather")
    public ReturnResult getWeather() {

        return scenicIndexService.getWeather
                ("https://free-api.heweather.net/s6/weather/now?location=CN101260601&key=6ec7909f65a44d70a107dbd1b81a811c");
    }
}
