package com.huiju.estateagents.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.TaGoods;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaPersonBuilding;
import com.huiju.estateagents.service.ITaBuildingService;
import com.huiju.estateagents.service.ITaGoodsService;
import com.huiju.estateagents.service.ITaPersonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.invoke.ConstantCallSite;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
    * 商品表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-07-25
 */
@RestController
@RequestMapping("/api")
@Api(value = "商品", tags = "商品")
public class TaGoodsController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaGoodsController.class);

    @Autowired
    public ITaGoodsService iTaGoodsService;

    @Autowired
    public ITaBuildingService iTaBuildingService;

    @Autowired
    public ITaPersonService taPersonService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "后台商品列表", notes = "后台商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNumber", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "goodsName", paramType = "query",value = "商品名称"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "priceLesser", paramType = "query",value = "价格小"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "priceGreater", paramType = "query",value = "价格大"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "status", paramType = "query",value = "状态")
    })
    @RequestMapping(value="/admin/taGoods",method= RequestMethod.GET)
    public ResponseBean taGoodsList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNum,
                                    @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "goodsName",required = false) String goodsName,
                                    @RequestParam(value = "buildingId",required = false) String buildingId,
                                    @RequestParam(value ="priceLesser",required = false) Integer priceLesser,
                                    @RequestParam(value ="priceGreater",required = false) Integer priceGreater,
                                    @RequestParam(value ="status",required = false) Integer status,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            List<TaPersonBuilding> taPersonBuildingListByUserId = getTaPersonBuildingListByUserId(request);

            //使用分页插件
		    IPage<TaGoods> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(goodsName),"goods_name",goodsName);
            queryWrapper.lt(null!=priceGreater,"point_price",priceGreater);
            queryWrapper.gt(null != priceLesser,"point_price",priceLesser);
            queryWrapper.eq(null != status,"status",status);
            queryWrapper.eq("org_id",getOrgId(request));
            queryWrapper.eq(!StringUtils.isEmpty(buildingId),"building_id",buildingId);
            queryWrapper.in(taPersonBuildingListByUserId.size()>0,"building_id",taPersonBuildingListByUserId.stream().map(TaPersonBuilding::getBuildingId).collect(Collectors.toList()));
            queryWrapper.orderByDesc("create_date");

            IPage<TaGoods> result = iTaGoodsService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taGoods 实体对象
     * @return
     */
    @ApiOperation(value = "后台商品保存", notes = "后台商品保存")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaGoods", name = "taGoods", paramType = "body",value = "商品详细数据")
    })
    @RequestMapping(value="/admin/taGoods/add",method= RequestMethod.POST)
    public ResponseBean taGoodsAdd(@RequestBody TaGoods taGoods,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            Integer cityId = iTaBuildingService.getCityById(taGoods.getBuildingId());
            taGoods.setCityId(cityId);
            taGoods.setOrgId(getOrgId(request));
            if (iTaGoodsService.save(taGoods)){
                responseBean.addSuccess(taGoods);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taGoods/{id}", method= RequestMethod.DELETE)
    public ResponseBean taGoodsDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaGoodsService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param taGoods 实体对象
     * @return
     */
    @ApiOperation(value = "后台商品修改", notes = "后台商品修改")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaGoods", name = "taGoods", paramType = "body",value = "商品详细数据")
    })
    @RequestMapping(value="/admin/taGoods",method= RequestMethod.PUT)
    public ResponseBean taGoodsUpdate(@RequestBody TaGoods taGoods,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            Integer cityId = iTaBuildingService.getCityById(taGoods.getBuildingId());
            taGoods.setCityId(cityId);
            taGoods.setOrgId(getOrgId(request));
            if (iTaGoodsService.updateById(taGoods)){
                responseBean.addSuccess(taGoods);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 修改对象
     * @param taGoods 实体对象
     * @return
     */
    @ApiOperation(value = "后台商品状态变更", notes = "后台商品状态变更")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaGoods", name = "taGoods", paramType = "body",value = "商品详细数据")
    })
    @RequestMapping(value="/admin/taGoods/change",method= RequestMethod.PUT)
    public ResponseBean taGoodsChange(@RequestBody TaGoods taGoods,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(null != taGoods.getStatus() && taGoods.getStatus().equals(CommConstant.STATUS_NORMAL)){
                taGoods.setStatus(CommConstant.STATUS_UNACCALIMED);
            }else {
                taGoods.setStatus(CommConstant.STATUS_NORMAL);
            }
            taGoods.setOrgId(getOrgId(request));
            if (iTaGoodsService.updateById(taGoods)){
                responseBean.addSuccess(taGoods);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "后台商品详情", notes = "后台商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "商品id")
    })
    @RequestMapping(value="/admin/taGoods/{id}",method= RequestMethod.GET)
    public ResponseBean taGoodsGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaGoodsService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    @ApiOperation(value = "微信 查询有商品的项目", notes = "微信 查询有商品的项目")
    @GetMapping(value = "/wx/goodsToBuilding")
    public ResponseBean wxGoodsToBuilding(@RequestParam(value = "cityId", required = false) Integer cityId, HttpServletRequest request) {
        return iTaBuildingService.getBuildingListById(getOrgId(request),cityId);
    }

    /**
     * 分页查询列表
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "微信商品列表", notes = "微信商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id")
    })
    @RequestMapping(value="/wx/goods",method= RequestMethod.GET)
    public ResponseBean wxGoodsList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                    @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "buildingId",required = false) String buildingId,
                                    @RequestParam(value = "cityId", required = false) Integer cityId,
                                    HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try {
            //使用分页插件
            IPage<TaGoods> pg = new Page<>(pageNumber, pageSize);
            QueryWrapper<TaGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            if (!StringUtils.isEmpty(buildingId)){
                queryWrapper.eq("building_id", buildingId);
            }
            if (null != orgId){
                queryWrapper.eq("org_id", orgId);
            }
            if (null != cityId){
                queryWrapper.eq("city_id", cityId);
            }
            queryWrapper.orderByDesc("order_no");
            queryWrapper.orderByDesc("create_date");
            
            IPage<TaGoods> result = iTaGoodsService.page(pg, queryWrapper);
            Map<String,Object> data = new HashMap<>();
            data.put("goods",result);
            data.put("person",person);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    
    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "微信商品详情", notes = "微信商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "商品id")
    })
    @RequestMapping(value="/wx/goods/{id}",method= RequestMethod.GET)
    public ResponseBean wxGoodsGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaGoodsService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsGet -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 兑换商品接口
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "微信兑换商品接口", notes = "微信兑换商品接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "商品id")
    })
    @RequestMapping(value="/wx/goods/exchange/{id}",method= RequestMethod.POST)
    public ResponseBean wxExchangeGoods(@PathVariable Integer id, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            String openid = getOpenId(request);
            //兑换商品
            String state = iTaGoodsService.exchangeGoods(id,openid);
            if (state.equals(CommConstant.SUCCESS)){
                TaGoods taGoods = iTaGoodsService.getById(id);
                responseBean.addSuccess(taGoods);
            }else{
                responseBean.addError(state);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taGoodsGet -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
