package com.bweb.controller.Goods;


import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.ResponseMsgUtil;

import com.hai.entity.GoodsDetail;
import com.hai.entity.GoodsLogistics;
import com.hai.entity.HighApprove;
import com.hai.entity.HighGoodsType;
import com.hai.enum_type.ApproveType;
import com.hai.goods.service.GoodsDetailService;
import com.hai.goods.service.GoodsLogisticsService;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighApproveService;
import com.hai.service.HighGoodsTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/goods")
@Api(value = "商品")
public class GoodsDetailController {
    Logger log = LoggerFactory.getLogger(GoodsDetailController.class);

    @Resource
    private GoodsDetailService goodsDetailService;

    @Resource
    private HighGoodsTypeService highGoodsTypeService;

    @Resource
    private HighApproveService highApproveService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private GoodsLogisticsService logisticsService;

    @RequestMapping(value = "/getListGoodsDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品列表")
    public ResponseData getListGoodsDetail(
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "goodsLabel", required = false) String goodsLabel,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize
            , HttpServletRequest request
    ) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            map.put("title", title);
            map.put("status", status);
            map.put("goodsLabel", goodsLabel);
            map.put("companyId", userInfoModel.getBsCompany().getId());

            if (userInfoModel.getSecUser().getExt3() != null) {
                map.put("opId" , userInfoModel.getSecUser().getId());
            }

            PageHelper.startPage(pageNum,pageSize);

            List<GoodsDetail> list = goodsDetailService.getGoodsDetailList(map);
            return ResponseMsgUtil.success(new PageInfo<>(list));

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

    @RequestMapping(value = "/insertGoods", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增产品")
    public ResponseData insertGoods(@RequestBody GoodsDetail goodsDetail, HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (goodsDetail == null ||
                    goodsDetail.getName() == null ||
                    goodsDetail.getGoodsType() == null ||
                    goodsDetail.getListImg() == null ||
                    goodsDetail.getBannerImg() == null ||
                    goodsDetail.getDetailImg() == null

            ) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighGoodsType goodsType = highGoodsTypeService.findById(goodsDetail.getGoodsType().intValue());

            goodsDetail.setOpId(userInfoModel.getSecUser().getId());
            goodsDetail.setStatus(2);
            goodsDetail.setCompanyId(userInfoModel.getBsCompany().getId());
            goodsDetail.setOpName(userInfoModel.getSecUser().getLoginName());
            goodsDetail.setCreateTime(new Date());
            goodsDetail.setGoodsTypeName(goodsType.getTitle());
            goodsDetail.setUpdateTime(new Date());

            goodsDetailService.insertGoodsDetail(goodsDetail);

            return ResponseMsgUtil.success("新增成功");

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

    @RequestMapping(value = "/updateGoods", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改产品")
    public ResponseData updateGoods(@RequestBody GoodsDetail goodsDetail, HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (goodsDetail == null ||
                    goodsDetail.getId() == null ||
                    goodsDetail.getName() == null ||
                    goodsDetail.getGoodsType() == null ||
                    goodsDetail.getListImg() == null ||
                    goodsDetail.getBannerImg() == null ||
                    goodsDetail.getDetailImg() == null

            ) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            GoodsDetail goods = goodsDetailService.findGoodsDetailById(goodsDetail.getId());

            HighGoodsType goodsType = highGoodsTypeService.findById(goodsDetail.getGoodsType().intValue());


            goodsDetail.setStatus(goods.getStatus());
            goodsDetail.setCreateTime(goods.getCreateTime());
            goodsDetail.setOpName(goods.getOpName());
            goodsDetail.setOpId(goods.getOpId());
            goodsDetail.setUpdateTime(new Date());
            goodsDetail.setGoodsTypeName(goodsType.getTitle());
            goodsDetail.setCompanyId(userInfoModel.getBsCompany().getId());

            goodsDetailService.updateGoodsDetail(goodsDetail);

            return ResponseMsgUtil.success("修改成功");


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

    @RequestMapping(value = "/findGoodsDetailById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商品")
    public ResponseData findGoodsDetailById(
            @RequestParam(value = "id", required = true) Long id
    ) {
        try {

            GoodsDetail goodsDetail = goodsDetailService.findGoodsDetailById(id);

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

            return ResponseMsgUtil.success(goodsDetail);

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

    @RequestMapping(value = "/deleteGoods", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除商品")
    public ResponseData deleteGoods(
            @RequestParam(value = "id", required = true) Long id
            , HttpServletRequest request
    ) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            GoodsDetail goodsDetail = goodsDetailService.findGoodsDetailById(id);

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

            if (goodsDetail.getStatus() == 1) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态错误，不可删除");
            }

            goodsDetail.setStatus(0);
            goodsDetail.setUpdateTime(new Date());
            goodsDetail.setOpId(userInfoModel.getSecUser().getId());
            goodsDetail.setOpName(userInfoModel.getSecUser().getLoginName());
            goodsDetailService.updateGoodsDetail(goodsDetail);

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

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

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

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            GoodsDetail goodsDetail = goodsDetailService.findGoodsDetailById(id);

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

            if (goodsDetail.getStatus() == 0) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态错误，无法操作！");
            }

            if (goodsDetail.getStatus() == 2) {
                HighApprove approve = new HighApprove();
                approve.setObjectType(ApproveType.GOODS_UP_SHELF_APPROVE.getType());
                approve.setObjectId(id);
                approve.setObjectName(goodsDetail.getName());
                approve.setApproveSerialNo(DateUtil.date2String(new Date(), "yyyyMMddHHmmss"));
                approve.setStatus(1);
                approve.setCreateTime(new Date());
                approve.setUpdateTime(new Date());
                approve.setSubmitOperatorId(userInfoModel.getSecUser().getId());
                approve.setSubmitOperatorName(userInfoModel.getSecUser().getUserName());
                approve.setExt1(userInfoModel.getBsCompany().getId().toString());

                // 增加审批
                highApproveService.insertApprove(approve);
            }

            goodsDetail.setStatus(goodsDetail.getStatus() == 1 ? 2:3);
            goodsDetail.setUpdateTime(new Date());
            goodsDetailService.updateGoodsDetail(goodsDetail);

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

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

    @RequestMapping(value = "/getLogisticsMsg", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据快递单号查询物流信息")
    public ResponseData getLogisticsMsg(@RequestParam(name = "orderId", required = false) Long orderId) {
        try {

            GoodsLogistics logistics = (GoodsLogistics) logisticsService.getLogisticsMsg(orderId);
            JSONArray object = JSONArray.parseArray(logistics.getLogisticsTraceDetails());
            return ResponseMsgUtil.success(object);

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

}

