package com.cweb.controller.group;

import com.alibaba.fastjson.JSONArray;
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.security.UserCenter;
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.ResponseData;
import com.hfkj.model.UserInfoModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Api(value = "门店产品管理")
@RequestMapping(value = "/storeGroup")
public class BsStoreGroupController {

    private static Logger log = LoggerFactory.getLogger(BsStoreImgController.class);

    @Resource
    private BsStoreGroupProductService storeGroupProductService;

    @Resource
    private BsStoreGroupService storeGroupService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/insertGroupContent",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增门店团购内容")
    public ResponseData insertGroupContent(@RequestBody BsStoreGroupContent storeGroupContent) {
        try {

            if (storeGroupContent == null
                    || storeGroupContent.getStoreId() == null
                    || storeGroupContent.getAstrict() == null
                    || storeGroupContent.getName() == null
                    || storeGroupContent.getPrice() == null
                    || storeGroupContent.getOriginalPrice() == null
                    || storeGroupContent.getValidity() == null
                    || StringUtils.isBlank(storeGroupContent.getImg())

            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getSalesman() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色暂无权限");
            }

            storeGroupContent.setStatus(2);
            storeGroupContent.setCreateTime(new Date());
            storeGroupContent.setUpdateTime(new Date());
            storeGroupContent.setOpId(userInfoModel.getSalesman().getId());
            storeGroupContent.setOpName(userInfoModel.getSalesman().getName());

            storeGroupProductService.insertStoreGroupContent(storeGroupContent);

            return ResponseMsgUtil.success(storeGroupContent);

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

    @RequestMapping(value="/editGroupContent",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改门店团购内容")
    public ResponseData editGroupContent(@RequestBody BsStoreGroupContent storeGroupContent) {
        try {

            if (storeGroupContent == null
                    || storeGroupContent.getId() == null
                    || storeGroupContent.getStoreId() == null
                    || storeGroupContent.getAstrict() == null
                    || storeGroupContent.getName() == null
                    || storeGroupContent.getPrice() == null
                    || storeGroupContent.getOriginalPrice() == null
                    || storeGroupContent.getValidity() == null
                    || StringUtils.isBlank(storeGroupContent.getImg())

            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getSalesman() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色暂无权限");
            }

            BsStoreGroupContent bsStoreGroupContent = storeGroupProductService.findStoreGroupContent(storeGroupContent.getId());
            if (bsStoreGroupContent.getStatus() == 1) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "当前状态不可编辑！");
            }

            storeGroupContent.setStatus(bsStoreGroupContent.getStatus());
            storeGroupContent.setUpdateTime(new Date());
            storeGroupContent.setOpId(userInfoModel.getSalesman().getId());
            storeGroupContent.setOpName(userInfoModel.getSalesman().getName());

            storeGroupProductService.editStoreGroupContent(storeGroupContent);

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/editGroupContentDetail",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑门店团购内容详情")
    public ResponseData editGroupContentDetail(@RequestBody JSONObject object) {
        try {

            if (object == null
                    || object.getLong("groupId") == null
                    || object.getString("name") == null
                    || object.getJSONArray("details") == null

            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getSalesman() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色暂无权限");
            }

            JSONArray objects = object.getJSONArray("details");
            BsStoreGroupDetail storeGroupDetail;
            for (Object o : objects) {
                JSONObject data = (JSONObject) o;

                storeGroupDetail = storeGroupProductService.findGroupDetail(data.getString("productId") , object.getLong("groupId"));

                BsStoreProduct storeProduct = storeGroupService.findStoreProduct(data.getLong("productId"));

                if (storeProduct != null) {
                    if (storeGroupDetail == null) {
                        storeGroupDetail = new BsStoreGroupDetail();
                        storeGroupDetail.setGroupId(object.getLong("groupId"));
                        storeGroupDetail.setCount(data.getInteger("count"));
                        storeGroupDetail.setName(object.getString("name"));
                        storeGroupDetail.setProductImg(storeProduct.getImg());
                        storeGroupDetail.setProductName(storeProduct.getName());
                        storeGroupDetail.setProductSpec(data.getInteger("count") + storeProduct.getSpec());
                        storeGroupDetail.setStoreProductId(data.getString("productId"));
                        storeGroupDetail.setCreateTime(new Date());
                        storeGroupDetail.setStatus(1);
                        storeGroupDetail.setUpdateTime(new Date());
                        storeGroupDetail.setOpId(userInfoModel.getSalesman().getId());
                        storeGroupDetail.setOpName(userInfoModel.getSalesman().getName());

                        storeGroupProductService.insertGroupDetail(storeGroupDetail);
                    } else {
                        storeGroupDetail.setCount(data.getInteger("count"));
                        storeGroupProductService.editGroupDetail(storeGroupDetail);
                    }
                }


            }

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/deleteGroupDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除团购内容详情")
    public ResponseData deleteGroupDetail(@RequestParam(value = "id" , required = true) Long id) {
        try {

            storeGroupProductService.deleteGroupDetail(id);

            return ResponseMsgUtil.success("删除成功");

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

    @RequestMapping(value="/editGroupServeRule",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑门店团购使用规则")
    public ResponseData editGroupServeRule(@RequestBody BsStoreGroupServeRule storeGroupServeRule) {
        try {

            if (storeGroupServeRule == null
                    || storeGroupServeRule.getGroupId() == null
                    || storeGroupServeRule.getContent() == null
            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);

            BsStoreGroupServeRule bsStoreGroupServeRule = storeGroupProductService.findGroupServeRuleByGroup(storeGroupServeRule.getGroupId());

            if (bsStoreGroupServeRule == null) {
                storeGroupServeRule.setStatus(1);
                storeGroupServeRule.setCreateTime(new Date());
                storeGroupServeRule.setUpdateTime(new Date());
                storeGroupServeRule.setOpId(userInfoModel.getSalesman().getId());
                storeGroupServeRule.setOpName(userInfoModel.getSalesman().getName());
                storeGroupProductService.insertGroupServeRule(storeGroupServeRule);
            } else {
                bsStoreGroupServeRule.setContent(storeGroupServeRule.getContent());
                bsStoreGroupServeRule.setUpdateTime(new Date());
                storeGroupProductService.editGroupServeRule(bsStoreGroupServeRule);
            }

            if (userInfoModel == null || userInfoModel.getSalesman() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色暂无权限");
            }



            return ResponseMsgUtil.success("操作成功");

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



    @RequestMapping(value="/upDownGroup",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "上下架团购")
    public ResponseData upDownGroup(@RequestParam(value = "id" , required = true) Long id) {
        try {

            BsStoreGroupContent bsStoreGroupContent = storeGroupProductService.findStoreGroupContent(id);
            if (bsStoreGroupContent.getStatus() == 0) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "当前状态错误！");
            }

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null || userInfoModel.getSalesman() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色暂无权限");
            }


            bsStoreGroupContent.setStatus(bsStoreGroupContent.getStatus() == 1 ? 2:1);
            bsStoreGroupContent.setUpdateTime(new Date());
            bsStoreGroupContent.setOpId(userInfoModel.getSalesman().getId());
            bsStoreGroupContent.setOpName(userInfoModel.getSalesman().getName());
            storeGroupProductService.editStoreGroupContent(bsStoreGroupContent);

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/getStoreGroupList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询门店团购列表")
    public ResponseData getStoreGroupList(@RequestParam(value = "storeId" , required = true) Long storeId) {
        try {


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

            return ResponseMsgUtil.success(storeGroupProductService.getStoreGroupContentByList(map));

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


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

            return ResponseMsgUtil.success(storeGroupProductService.findStoreGroupContent(groupId));

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

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

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

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

            Map<String, List<BsStoreGroupDetail>> collect = list.stream().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());

            return ResponseMsgUtil.success(groupDetails);

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

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

            return ResponseMsgUtil.success(storeGroupProductService.findGroupServeRuleByGroup(groupId));

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


    @RequestMapping(value="/editStoreExtMsg",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑门店扩展字段")
    public ResponseData editStoreExtMsg(@RequestBody BsStoreExtMsg storeExtMsg) {
        try {

            if (storeExtMsg == null
                    || storeExtMsg.getAddress() == null
                    || storeExtMsg.getStoreTag() == null
                    || storeExtMsg.getOpeningHours() == null
                    || storeExtMsg.getStoreLabel() == null
                    || storeExtMsg.getStoreId() == null
            ) {
                log.error("configStore error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);

            BsStoreExtMsg bsStoreExtMsg = storeGroupService.findStoreExtMsgByStoreId(storeExtMsg.getStoreId());

            if (bsStoreExtMsg == null) {
                storeExtMsg.setStatus(1);
                storeExtMsg.setCreateTime(new Date());
                storeExtMsg.setUpdateTime(new Date());
                storeExtMsg.setOpId(userInfoModel.getSalesman().getId());
                storeExtMsg.setOpName(userInfoModel.getSalesman().getName());
                storeGroupService.insertStoreExtMsg(storeExtMsg);
            } else {
                storeExtMsg.setId(bsStoreExtMsg.getId());
                storeExtMsg.setStatus(bsStoreExtMsg.getStatus());
                storeExtMsg.setUpdateTime(new Date());
                storeExtMsg.setOpId(userInfoModel.getSalesman().getId());
                storeExtMsg.setOpName(userInfoModel.getSalesman().getName());
                storeGroupService.editStoreExtMsg(storeExtMsg);
            }


            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/findStoreExtMsgByStoreId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询门店拓展信息")
    public ResponseData findStoreExtMsgByStoreId(@RequestParam(value = "storeId" , required = true) Long storeId) {
        try {

            return ResponseMsgUtil.success(storeGroupService.findStoreExtMsgByStoreId(storeId));

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


}
