package com.bweb.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.utils.*;
import com.hfkj.entity.*;
import com.hfkj.meituan.MeiTuanService;
import com.hfkj.model.ResponseData;
import com.hfkj.model.goods.GoodsModel;
import com.hfkj.service.discount.CouponDiscountService;
import com.hfkj.service.goods.BsOrderGoodsService;
import com.hfkj.service.goods.GoodsMsgService;
import com.hfkj.service.goods.GoodsSpecsService;
import com.hfkj.service.goods.GoodsUserAddressService;
import com.hfkj.service.hlt.HltCanteenService;
import com.hfkj.service.hlt.HuiLianTongUnionCardService;
import com.hfkj.service.order.BsOrderChildService;
import com.hfkj.sysenum.order.OrderLogisticsStatusEnum;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value="/test")
@Api(value="测试")
public class TestController {
    private static Logger log = LoggerFactory.getLogger(TestController.class);

    @Resource
    private GoodsMsgService goodsMsgService;

    @Resource
    private GoodsSpecsService goodsSpecsService;

    @Resource
    private CouponDiscountService couponDiscountService;

    @Resource
    private BsOrderChildService orderChildService;
    @Resource
    private BsOrderGoodsService orderGoodsService;
    @Resource
    private BsOrderGoodsService bsOrderGoodsService;

    @Resource
    private GoodsUserAddressService addressService;

    @RequestMapping(value="/canteenConsume",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "食堂消费")
    public ResponseData canteenConsume(@RequestParam(value = "cardNo" , required = false) String cardNo,
                                      @RequestParam(value = "instCode" , required = false) String instCode,
                                      @RequestParam(value = "canteenId" , required = false) String canteenId) {
        try {

            String orderNo = OrderUtil.generateOrderNo();

            JSONObject cardInfo = HltCanteenService.canteenConsume(orderNo , cardNo , instCode , canteenId);
            if (StringUtils.isBlank(cardInfo.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求失败");
            }
            return ResponseMsgUtil.success(HuiLianTongUnionCardService.resolveResponse(cardInfo.getString("data")));

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

    @RequestMapping(value="/bindDiscountSpecs",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据类型绑定")
    public ResponseData bindDiscountSpecs(@RequestParam(value = "goodsType" , required = false) Integer goodsType ,
                                          @RequestParam(value = "discountId" , required = false) Long discountId) {
        try {

            Map<String , Object> map = new HashMap<>();
            map.put("goodsType" , goodsType);
            List<GoodsMsg> goodsMsg = goodsMsgService.getList(map);
            List<GoodsSpecs> specsList = goodsSpecsService.getList(map);

            List<CouponDiscountGoodsRel> goodsRelList = new ArrayList<>();
            for (GoodsMsg goods : goodsMsg) {
                List<GoodsSpecs> list = specsList.stream().filter(specs -> specs.getGoodsId().equals(goods.getId())).
                        collect(Collectors.toList());
                for (GoodsSpecs goodsSpecs : list) {
                    CouponDiscountGoodsRel goodsRel = new CouponDiscountGoodsRel();
                    goodsRel.setDiscountId(discountId);
                    goodsRel.setSpecsId(goodsSpecs.getId());
                    goodsRel.setCreateTime(new Date());
                    goodsRel.setStatus(1);
                    goodsRelList.add(goodsRel);

                }
            }
            couponDiscountService.insertGoodsRelBatch(goodsRelList);
            return ResponseMsgUtil.success("成功");

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

    @RequestMapping(value="/orderGoodsUpdate",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "商品更新")
    public ResponseData orderMsgUpdate() {
        try {


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

            map.put("status", 1);

            List<GoodsMsg> list = goodsMsgService.getList(map);

            List<GoodsSpecs> specsList = goodsSpecsService.getList(new HashMap<>());


            for (GoodsMsg goodsMsg : list) {
                List<GoodsSpecs> goodsSpecsList = specsList.stream().filter(s -> s.getGoodsId().equals(goodsMsg.getId())).collect(Collectors.toList());
                if (!goodsSpecsList.isEmpty()) {
                    goodsMsg.setSaleNum(CommonUtil.saleNumRandom(goodsSpecsList.get(0).getSalePrice()));
                }
                goodsMsgService.update(goodsMsg);
            }

            return ResponseMsgUtil.success("成功");

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

    @RequestMapping(value="/orderGoodsConfirmReceipt",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "商品确认收货")
    public ResponseData orderGoodsConfirmReceipt() {
        try {

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

            map.put("logisticsStatus" , "SIGN");
            map.put("status" , 2);

            List<BsOrderGoods> orderGoodsList = orderGoodsService.getList(map);

            for (BsOrderGoods goods : orderGoodsList) {

                // 判断时间是否是十天前

                if (DateUtil.differentDays(goods.getCreateTime() , new Date()) > 9) {
                    bsOrderGoodsService.confirmReceipt(goods.getId());
                    goods.setStatus(3);
                    goods.setUpdateTime(new Date());
                    orderGoodsService.update(goods);
                }
            }

            return ResponseMsgUtil.success("成功");

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

    @RequestMapping(value="/getLogisticsMsg",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询物流")
    public ResponseData getLogisticsMsg() {
        try {
            Map<String , Object> objectMap = new HashMap<>();

            objectMap.put("status" , 2);

            List<BsOrderGoods> orderGoodsList = orderGoodsService.getList(objectMap);

            for (BsOrderGoods goods : orderGoodsList) {

                if (goods == null) {
                    throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "暂无物流信息！");
                }

                GoodsUserAddress userAddress = addressService.queryDetail(goods.getDeliveryAddressId());

                if (userAddress == null) {
                    throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "暂无物流信息！");
                }

                if (goods.getLogisticsNo() != null) {
                    GoodsLogistics logistics = (GoodsLogistics) bsOrderGoodsService.getLogisticsMsg(goods.getLogisticsNo() , userAddress.getPhone());
                    if (logistics.getLogisticsStatus() != null) {
                        goods.setLogisticsStatus(logistics.getLogisticsStatus());
                        goods.setLogisticsStatusDesc(logistics.getLogisticsStatusDesc());
                    } else {
                        goods.setLogisticsStatus(OrderLogisticsStatusEnum.statusWAIT_ACCEPT.getCode());
                        goods.setLogisticsStatusDesc(OrderLogisticsStatusEnum.statusWAIT_ACCEPT.getName());
                    }

                    goods.setUpdateTime(new Date());

                    bsOrderGoodsService.update(goods);
                }

            }

            return ResponseMsgUtil.success("map");

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


    @RequestMapping(value = "/getHuiLianTongCardConsume", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡消费记录")
    public ResponseData getHuiLianTongCardConsume(@RequestParam(name = "businessType", required = true) String businessType,
                                                  @RequestParam(name = "cardNo", required = true) String cardNo) {
        try {


            JSONObject consumptionRecord = HuiLianTongUnionCardService.queryConsumptionRecordByBusiness(businessType, cardNo, 1661498490000L, 1882423290000L, 1, 10000);
            if (StringUtils.isBlank(consumptionRecord.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
            }

            JSONArray array = HuiLianTongUnionCardService.resolveResponse(consumptionRecord.getString("data")).getJSONArray(
                    "records");

            return ResponseMsgUtil.success(array);

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

    @RequestMapping(value = "/queryTransJournal", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡消费记录")
    public ResponseData queryTransJournal(@RequestParam(name = "tranType", required = true) String tranType,
                                          @RequestParam(name = "cardNo", required = true) String cardNo,
                                          @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                          @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {


            JSONObject consumptionRecord = HuiLianTongUnionCardService.queryTransJournal(cardNo , tranType);
            if (StringUtils.isBlank(consumptionRecord.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
            }

            JSONArray array = HuiLianTongUnionCardService.resolveResponse(consumptionRecord.getString("data")).getJSONArray(
                    "journals");

            List<JSONObject> list = new ArrayList<>();

            for (Object object : array) {
                JSONObject journal = (JSONObject) object;
                journal.put("tranAmount", journal.getBigDecimal("tranAmount").divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
                list.add(journal);
            }

            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, list.size(), pageSize, new PageInfo<>(list)));

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

    @RequestMapping(value = "/loginFree", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "H5免登接口")
    public ResponseData loginFree(@RequestParam(name = "staffPhone", required = true) String staffPhone,
                                          @RequestParam(name = "productType", required = true) String productType) {
        try {

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

            staffInfo.put("staffPhone", staffPhone);

            map.put("staffInfo", staffInfo);
            map.put("ts", new Date().getTime());
            map.put("entId", 104310L);
            map.put("productType", productType);
            map.put("nonce" , RandomStringGeneratorUtil.generateRandomString(36));
            return ResponseMsgUtil.success(MeiTuanService.loginFree(map));

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


}
