package com.bweb.controller.goods;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.SessionObject;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.OrderUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.goods.GoodsModelSpecs;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.audit.AuditMsgService;
import com.hfkj.service.goods.*;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
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.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value="/goods")
@Api(value="商品信息")
public class GoodsController {

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

    @Resource
    private GoodsMsgService goodsMsgService;

    @Resource
    private GoodsBrandService goodsBrandService;

    @Resource
    private GoodsSpecsService goodsSpecsService;

    @Resource
    private GoodsTypeService goodsTypeService;

    @Resource
    private GoodsVpdService goodsVpdService;

    @Resource
    private AuditMsgService auditMsgService;

    @Resource
    private UserCenter userCenter;

    @Resource
    private GoodsUserAddressService deliveryAddressService;

    @Resource
    private GoodsJumpService goodsJumpService;

    @RequestMapping(value="/editGoodsMsg",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑商品信息")
    public ResponseData editGoodsMsg(@RequestBody GoodsMsg body, HttpServletRequest request) {

        try {


            SessionObject sessionObject = userCenter.getSessionObject(request);
            SecUserSessionObject userModel = (SecUserSessionObject) sessionObject.getObject();

            if (body == null
                    || body.getGoodsBrand() == null
                    || body.getGoodsType() == null
                    || body.getType() == null
                    || StringUtils.isBlank(body.getListImg())
                    || StringUtils.isBlank(body.getBannerImg())
                    || StringUtils.isBlank(body.getDetailImg())
                    || StringUtils.isBlank(body.getTitle())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            GoodsMsg goodsMsg;

            if (body.getId() != null) {
                // 查询品牌
                goodsMsg = goodsMsgService.queryDetail(body.getId());
                if (goodsMsg == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.CONTENT_NOT_FOUND, "");
                }
            } else {
                goodsMsg = new GoodsMsg();
                goodsMsg.setCreateTime(new Date());
                goodsMsg.setSaleNum(0);
                goodsMsg.setMerId(userModel.getAccount().getObjectId());
                goodsMsg.setMerName(userModel.getAccount().getUserName());
                body.setStatus(2);
            }

            GoodsType goodsType = goodsTypeService.queryDetail(body.getGoodsType());

            if (goodsType.getParentId() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "一级分类不可选择！");
            }
            goodsMsg.setUpdateTime(new Date());
            goodsMsg.setGoodsBrandName(goodsBrandService.findGoodsBrandName(body.getGoodsBrand()));
            goodsMsg.setGoodsTypeName(goodsTypeService.findGoodsType(body.getGoodsType()));
            goodsMsg.setGoodsType(body.getGoodsType());
            goodsMsg.setGoodsTypeParent(goodsType.getParentId());
            goodsMsg.setGoodsTypeParentName(goodsTypeService.findGoodsType(goodsType.getParentId()));
            goodsMsg.setType(body.getType());
            goodsMsg.setGoodsBrand(body.getGoodsBrand());
            goodsMsg.setStatus(body.getStatus());
            goodsMsg.setTitle(body.getTitle());
            goodsMsg.setGoodsExplain(body.getGoodsExplain());
            goodsMsg.setGoodsLabel(body.getGoodsLabel());
            goodsMsg.setListImg(body.getListImg());
            goodsMsg.setBannerImg(body.getBannerImg());
            goodsMsg.setDetailImg(body.getDetailImg());

            if (body.getId() != null) {
                goodsMsgService.update(goodsMsg);
            } else {
                goodsMsgService.create(goodsMsg);
            }

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

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

    }

    @RequestMapping(value="/editGoodsSpecs",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑商品规格")
    public ResponseData editGoodsSpecs(@RequestBody GoodsModelSpecs body, HttpServletRequest request) {



        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            SecUserSessionObject userModel = (SecUserSessionObject) sessionObject.getObject();

//            if (userModel.getAccount().getObjectType() != SecUserObjectTypeEnum.type2.getCode()) {
//                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
//            }

            if (body == null
                    || body.getGoodsId() == null
                    || body.getOriginalPrice() == null
                    || body.getSalePrice() == null
//                    || body.getPurLimit() == null
                    || body.getStock() == null
                    || body.getSalesEndTime() == null
                    || StringUtils.isBlank(body.getShowImg())
                    || StringUtils.isBlank(body.getName())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            GoodsMsg goodsMsg = goodsMsgService.queryDetail(body.getGoodsId());

            if (goodsMsg == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.CONTENT_NOT_FOUND, "");
            }

            GoodsSpecs goodsSpecs;
            GoodsVpd goodsVpd;
            GoodsJump goodsJump;

            if (body.getId() != null) {
                // 查询规格
                goodsSpecs = goodsSpecsService.queryDetail(body.getSpecsId());
                if (goodsSpecs == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.CONTENT_NOT_FOUND, "");
                }
            } else {
                goodsSpecs = new GoodsSpecs();
                goodsSpecs.setCreateTime(new Date());
            }

            goodsSpecs.setUpdateTime(new Date());
            goodsSpecs.setGoodsId(body.getGoodsId());
            goodsSpecs.setOriginalPrice(body.getOriginalPrice());
            goodsSpecs.setSalePrice(body.getSalePrice());
            goodsSpecs.setPurLimit(body.getPurLimit());
            goodsSpecs.setStock(body.getStock());
            goodsSpecs.setSalesEndTime(body.getSalesEndTime());
            goodsSpecs.setShowImg(body.getShowImg());
            goodsSpecs.setName(body.getName());
            goodsSpecs.setStatus(1);

            if (goodsSpecs.getId() != null) {
                goodsSpecsService.update(goodsSpecs);
            } else {
                goodsSpecsService.create(goodsSpecs);
            }

            // 判断产品是否是实物产品
            if (goodsMsg.getType() == 1) {
                // 判断必填项
                if ( goodsSpecs.getId() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }

                // 查询实物产品跳转内容
                goodsJump = goodsJumpService.queryDetailBySpecsId(goodsSpecs.getId());
                if (goodsJump == null) {
                    goodsJump = new GoodsJump();
                    goodsJump.setCreateTime(new Date());
                }

                goodsJump.setSpecsId(goodsSpecs.getId());
                goodsJump.setBtnName(body.getBtnName());
                goodsJump.setJumpType(body.getJumpType());
                goodsJump.setJumpUrl(body.getJumpUrl());
                goodsJump.setAppid(body.getAppid());
                goodsJump.setUpdateTime(new Date());

                if (goodsJump.getId() != null) {
                    goodsJumpService.update(goodsJump);
                } else {
                    goodsJumpService.create(goodsJump);
                }
            }

            // 判断当前商品是否是虚拟商品
            if(goodsMsg.getType() == 2) {
                // 判断必填项
                if ( goodsSpecs.getId() == null
                        || body.getValidDay() == null
                        || body.getType() == null
                        || body.getSource() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }

                // 查询虚拟产品
                goodsVpd = goodsVpdService.queryDetailBySpecsId(goodsSpecs.getId());

                if (goodsVpd == null) {
                    goodsVpd = new GoodsVpd();
                    goodsVpd.setCreateTime(new Date());
                }

                goodsVpd.setSpecsId(goodsSpecs.getId());
                goodsVpd.setValidDay(body.getValidDay());
                goodsVpd.setType(body.getType());
                goodsVpd.setJumpType(body.getJumpType());
                goodsVpd.setJumpUrl(body.getJumpUrl());
                goodsVpd.setAppid(body.getAppid());
                goodsVpd.setKey(body.getKey());
                goodsVpd.setSalesEndTime(body.getSalesEndTime());
                goodsVpd.setSource(body.getSource());
                goodsVpd.setUpdateTime(new Date());

                if (goodsVpd.getId() != null) {
                    goodsVpdService.update(goodsVpd);
                } else {
                    goodsVpdService.create(goodsVpd);
                }
            }

            goodsMsg.setStatus(2);
            goodsMsgService.update(goodsMsg);

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

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

    @RequestMapping(value="/getListGoods",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData getListGoods(@RequestParam(value = "title" , required = false) String title,
                                     @RequestParam(value = "goodsType" , required = false) Long goodsType,
                                     @RequestParam(value = "goodsBrand" , required = false) Long goodsBrand,
                                     @RequestParam(value = "type" , required = false) Integer type,
                                     @RequestParam(value = "merId" , required = false) Long merId,
                                     @RequestParam(value = "status" , required = false) Integer status,
                                     @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                     @RequestParam(value = "pageSize" , required = true) Integer pageSize, HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            SecUserSessionObject userModel = (SecUserSessionObject) sessionObject.getObject();

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

            if (goodsType != null) {
                GoodsType goodsType1 = goodsTypeService.queryDetail(goodsType);

                if (goodsType1.getParentId() == null) {
                    map.put("goodsTypeParent", goodsType);
                } else {
                    map.put("goodsType", goodsType);
                }
            }

            map.put("goodsBrand", goodsBrand);

            if (userModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())) {
                map.put("merId", userModel.getAccount().getObjectId());
            } else {
                map.put("merId", merId);
            }

            map.put("type", type);
            map.put("status", status);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(goodsMsgService.getList(map)));

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

    @RequestMapping(value="/getGoodsSpecsList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品规格列表")
    public ResponseData getGoodsSpecsList(@RequestParam(value = "id" , required = false) Long id) {
        try {

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

            List<GoodsSpecs> goodsSpecs = goodsSpecsService.getList(map);

            List<GoodsModelSpecs> goodsModelSpecs = new ArrayList<>();

            for (GoodsSpecs goodsSpec : goodsSpecs) {
                GoodsModelSpecs goodsModelSpec = new GoodsModelSpecs();
                BeanUtils.copyProperties(goodsSpec, goodsModelSpec);
                GoodsVpd goodsVpd = goodsVpdService.queryDetailBySpecsId(goodsSpec.getId());
                if (goodsVpd != null) {
                    BeanUtils.copyProperties(goodsVpd, goodsModelSpec);
                }
                GoodsJump goodsJump = goodsJumpService.queryDetailBySpecsId(goodsSpec.getId());
                if (goodsJump != null) {
                    BeanUtils.copyProperties(goodsJump, goodsModelSpec);
                }
                goodsModelSpec.setSpecsId(goodsSpec.getId());
                goodsModelSpecs.add(goodsModelSpec);
            }

            return ResponseMsgUtil.success(goodsModelSpecs);

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

    @RequestMapping(value="/getGoodsSpecsListAll",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品规格列表")
    public ResponseData getGoodsSpecsListAll() {
        try {
            Map<String , Object> map = new HashMap<>();
            map.put("status" , 1);
            List<GoodsMsg> goodsMsgList = goodsMsgService.getList(new HashMap<>());

            List<GoodsModelSpecs> goodsModelSpecs = new ArrayList<>();

            for (GoodsMsg goodsMsg : goodsMsgList) {
                Map<String , Object> mapGoods = new HashMap<>();
                mapGoods.put("goodsId" , goodsMsg.getId());

                List<GoodsSpecs> goodsSpecs = goodsSpecsService.getList(mapGoods);
                for (GoodsSpecs goodsSpec : goodsSpecs) {
                    GoodsModelSpecs goodsModelSpec = new GoodsModelSpecs();
                    BeanUtils.copyProperties(goodsSpec, goodsModelSpec);
                    goodsModelSpec.setGoodsName(goodsMsg.getTitle());
                    goodsModelSpec.setSpecsId(goodsSpec.getId());
                    goodsModelSpecs.add(goodsModelSpec);
                }

            }

            return ResponseMsgUtil.success(goodsModelSpecs);

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

    @RequestMapping(value="/deleteGoods",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除")
    public ResponseData deleteGoods(@RequestParam(value = "id" , required = false) Long id) {
        try {

            goodsMsgService.delete(id , false);

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

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

    @RequestMapping(value="/deleteGoodsSpecs",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除规格")
    public ResponseData deleteGoodsSpecs(@RequestParam(value = "id" , required = false) Long id) {
        try {


            goodsSpecsService.delete(id , false);

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

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

    @RequestMapping(value="/goodsAudit",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "商品上下架")
    public ResponseData goodsAudit(@RequestParam(value = "id" , required = false) Long id, HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            SecUserSessionObject userModel = (SecUserSessionObject) sessionObject.getObject();

            GoodsMsg goodsMsg = goodsMsgService.queryDetail(id);

            if (goodsMsg.getStatus() == 1) {
                goodsMsg.setStatus(2);
                goodsMsg.setUpdateTime(new Date());
            } else if (goodsMsg.getStatus() == 2) {
                goodsMsg.setStatus(3);
                goodsMsg.setUpdateTime(new Date());

                AuditMsg auditMsg = new AuditMsg();
                auditMsg.setSubmitObjectId(goodsMsg.getId());
                auditMsg.setSubmitObjectName(goodsMsg.getTitle());
                auditMsg.setSubmitOpId(userModel.getAccount().getId());
                auditMsg.setSubmitOpName(userModel.getAccount().getUserName());
                auditMsg.setType(1);
                auditMsg.setAuditSerialNo(OrderUtil.generateOrderNo());
                auditMsg.setStatus(2);
                auditMsg.setUpdateTime(new Date());
                auditMsg.setCreateTime(new Date());

                auditMsgService.create(auditMsg);

            } else if (goodsMsg.getStatus() == 3) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态不可操作！");
            }

            goodsMsgService.update(goodsMsg);

            return ResponseMsgUtil.success("成功");

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


    @RequestMapping(value = "/findDeliveryAddressById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询收货地址详情")
    public ResponseData findDeliveryAddressById(
            @RequestParam(value = "id", required = true) Long id
    ) {
        try {

            GoodsUserAddress deliveryAddress = deliveryAddressService.queryDetail(id);

            if (deliveryAddress == null) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到相信息");
            }

            return ResponseMsgUtil.success(deliveryAddress);

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
