package com.cweb.controller.group;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.CoordCommonUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.service.group.BsStoreGroupProductService;
import com.hfkj.service.group.BsStoreGroupService;
import com.hfkj.model.OpenStoreModel;
import com.hfkj.model.ResponseData;
import com.hfkj.service.BsMerService;
import com.hfkj.service.BsStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Api(value = "团购对外接口")
@RequestMapping(value = "/openGroup")
public class OpenGroupController {

    Logger log = LoggerFactory.getLogger(OpenGroupController.class);

    @Resource
    private BsStoreService storeService;

    @Resource
    private BsStoreService bsStoreService;

    @Resource
    private BsStoreGroupService storeGroupService;

    @Resource
    private BsStoreGroupProductService storeGroupProductService;

    @Resource
    private BsMerService merService;

    @RequestMapping(value="/getStoreList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户查询门店列表")
    public ResponseData getStoreListByMer(@RequestBody JSONObject body) {
        try {

            String longitude = body.getString("longitude");
            String latitude = body.getString("latitude");

            List<OpenStoreModel> list = storeService.getStoreList(body.getString("name") , body.getLong("childId") , body.getLong("parentId"));

            for (OpenStoreModel storeModel : list) {
                Map<String , Object > map = new HashMap<>();
                map.put("storeId" , storeModel.getStoreId());
                map.put("status" , 1);
                List<BsStoreGroupContent> storeGroupContent = storeGroupProductService.getStoreGroupContentByList(map);
                if (longitude != null && latitude != null && storeModel.getLatitude() != null && storeModel.getLongitude() != null) {
                    double distance = CoordCommonUtil.getDistance(Double.valueOf(storeModel.getLatitude()), Double.valueOf(storeModel.getLongitude()), Double.valueOf(latitude), Double.valueOf(longitude));
                    double storeDistance = Math.round(distance/100d)/10d;
                    storeModel.setDistance(storeDistance);
                    if (distance < 1000) {
                        storeModel.setDistances(distance < 1 ? "1" : (int) distance + "m");
                    } else {
                        storeModel.setDistances((int) storeDistance + "km");
                    }

                }
                storeModel.setStoreGroupContentList(storeGroupContent);
                storeModel.setBsStoreExtMsg(storeGroupService.findStoreExtMsgByStoreId(Long.valueOf(storeModel.getStoreId())));
            }

            list = list.stream().filter(data -> !data.getStoreGroupContentList().isEmpty()).sorted(Comparator.comparing(OpenStoreModel::getDistance)).collect(Collectors.toList());

            return ResponseMsgUtil.success(list);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGroupContent",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询团购内容")
    public ResponseData getGroupContent(@RequestParam(value = "groupId" , required = true) Long groupId) {
        try {

            Map<String , Object > map = new HashMap<>();
            map.put("groupId" , groupId);

            BsStoreGroupContent storeGroupContent = storeGroupProductService.findStoreGroupContent(groupId);

            List<BsStoreGroupDetail> list = storeGroupProductService.getGroupDetailByList(map);

            Map<String, List<BsStoreGroupDetail>> collect = list.stream().sorted(Comparator.comparing(BsStoreGroupDetail::getCreateTime)).collect(Collectors.groupingBy(BsStoreGroupDetail::getName));

            List<JSONObject> groupDetails = collect.keySet().stream().map(key -> {
                JSONObject detailObject = new JSONObject(true);
                detailObject.put("name",key.toUpperCase());
                detailObject.put("list",collect.get(key));
                return detailObject;
            }).collect(Collectors.toList());

            storeGroupContent.setGroupDetails(groupDetails);
            storeGroupContent.setStoreGroupServeRule(storeGroupProductService.findGroupServeRuleByGroup(groupId));

            return ResponseMsgUtil.success(storeGroupContent);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getStoreMsg",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询团购内容")
    public ResponseData getStoreMsg(@RequestParam(value = "storeId" , required = true) Long storeId) {
        try {

            Map<String , Object > map = new HashMap<>();
            map.put("storeId" , storeId);
            map.put("status" , 1);

            BsStore bsStore = bsStoreService.getStoreById(storeId);

            if (bsStore == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未查询到门店信息！");
            }

            bsStore.setStoreGroupContentList(storeGroupProductService.getStoreGroupContentByList(map));
            bsStore.setBsStoreExtMsg(storeGroupService.findStoreExtMsgByStoreId(storeId));
            bsStore.setBsStoreImg(storeGroupService.getBsStoreImgByList(map));

            BsMer bsMer = merService.getMerDetail(bsStore.getMerId());
            bsStore.setMerchantNo(bsMer.getMerNo());

            return ResponseMsgUtil.success(bsStore);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getBsStoreImgByList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询门店图片列表")
    public ResponseData getBsStoreImgByList(@RequestBody JSONObject body) {
        try {
            Map<String , Object> map = new HashMap<>();
            map.put("storeId" , body.getLong("storeId"));
            map.put("type" , body.getLong("type"));

            return ResponseMsgUtil.success(storeGroupService.getBsStoreImgByList(map));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getMerNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取订单号")
    public ResponseData getMerNo(@RequestParam(value = "storeId" , required = true) Long storeId) {
        try {

            Map<String , Object > map = new HashMap<>();
            map.put("storeId" , storeId);

            BsStore bsStore = bsStoreService.getStoreById(storeId);

            if (bsStore == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未查询到门店信息！");
            }

            BsMer bsMer = merService.getMerDetail(bsStore.getMerId());

            if (bsMer == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未查询到商户信息！");
            }


            return ResponseMsgUtil.success(bsMer.getMerNo());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
