package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
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.utils.ResponseMsgUtil;
import com.hfkj.common.utils.StreamUtil;
import com.hfkj.entity.BsPayQrCode;
import com.hfkj.entity.BsStore;
import com.hfkj.entity.BsStoreDiscountActivity;
import com.hfkj.model.ResponseData;
import com.hfkj.service.BsPayQrCodeService;
import com.hfkj.service.BsStoreDiscountActivityService;
import com.hfkj.service.BsStoreService;
import com.hfkj.sysenum.PayQrCodeStatusEnum;
import com.hfkj.sysenum.StoreDiscountActivityStatusEnum;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/payQrCode")
@Api(value = "支付二维码")
public class BsPayQrCodeController {

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

    @Resource
    private BsPayQrCodeService payQrCodeService;

    @Resource
    private BsStoreService storeService;

    @Resource
    private BsStoreDiscountActivityService storeDiscountActivityService;

    @RequestMapping(value = "/getQrCodeDetail", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询二维码详情")
    public ResponseData getQrCodeDetail(@RequestBody JSONObject body) {
        try {

            if (StringUtils.isBlank(body.getString("serialNumber"))) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询二维码
            BsPayQrCode qrCode = payQrCodeService.getDetailBySN(body.getString("serialNumber"));
            if (qrCode == null) {
                log.error("BsPayQrCodeController error!","未找到支付码信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到支付码信息");
            }

            if (qrCode.getStoreId() == null) {
                log.error("BsPayQrCodeController error!","支付码未绑定门店");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付码未绑定门店");
            }

            if (!qrCode.getStatus().equals(PayQrCodeStatusEnum.status1.getNumber())) {
                log.error("BsPayQrCodeController error!","支付码已被停用");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付码已被停用");
            }

            // 门店
            BsStore store = storeService.getStoreById(qrCode.getStoreId());
            if (store == null) {
                log.error("BsPayQrCodeController error!","支付码已被停用");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付码已被停用");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("qrCode", qrCode);

            Map<String, Object> storeMap = new HashMap<>();
            storeMap.put("storeNo", store.getStoreNo());
            storeMap.put("storeName", store.getName());
            param.put("store", storeMap);

            List<BsStoreDiscountActivity> discountActivityList = new ArrayList<>();

            // 门店优惠
            Map<String, Object> activityParam = new HashMap<>();
            activityParam.put("storeId", store.getId());
            activityParam.put("partakeWay", 1);
            activityParam.put("status", StoreDiscountActivityStatusEnum.status2.getNumber());
            discountActivityList.addAll(storeDiscountActivityService.getActivityList(activityParam));

            activityParam.clear();
            // 商户优惠
            activityParam.put("partakeWay", 1);
            activityParam.put("merId", store.getMerId());
            activityParam.put("storeIdNull", 0);
            activityParam.put("status", StoreDiscountActivityStatusEnum.status2.getNumber());
            discountActivityList.addAll(storeDiscountActivityService.getActivityList(activityParam));

            // 用户优惠
            if (StringUtils.isNotBlank(body.getString("phone"))) {
                List<BsStoreDiscountActivity> userDiscountActivityList = new ArrayList<>();
                List<BsStoreDiscountActivity> userDiscountActivity = storeDiscountActivityService.getUseDiscountListByPhone(body.getString("phone"));
                userDiscountActivityList.addAll(userDiscountActivity.stream().filter(o -> o.getMerId().equals(store.getMerId())).collect(Collectors.toList()));
                userDiscountActivityList.addAll(userDiscountActivity.stream().filter(o -> o.getStoreId().equals(store.getId())).collect(Collectors.toList()));
                discountActivityList.addAll(userDiscountActivityList);
            }

            // 优惠活动
            param.put("discountActivity", discountActivityList.stream().filter(StreamUtil.distinctByKey(b -> b.getId())).collect(Collectors.toList()));
            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value="/bindStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑定门店")
    public ResponseData bindStore(@RequestBody JSONObject body) {
        try {

            if ((body.getLong("qrCodeId") == null && StringUtils.isBlank(body.getString("serialNumber"))) || body.getLong("storeId") == null) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            Long qrCodeId = body.getLong("qrCodeId");

            if (StringUtils.isNotBlank(body.getString("serialNumber"))) {
                BsPayQrCode payQrCode = payQrCodeService.getDetailBySN(body.getString("serialNumber"));
                if (payQrCode == null)  {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的支付码");
                }
                qrCodeId = payQrCode.getId();
            }
            payQrCodeService.bindStore(body.getLong("storeId"),qrCodeId);

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

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

    @RequestMapping(value="/unbindStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "解绑门店")
    public ResponseData unbindStore(@RequestBody JSONObject body) {
        try {

            if (body.getLong("qrCodeId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            payQrCodeService.unbindStore(body.getLong("qrCodeId"));

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

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

    @RequestMapping(value="/getSalesmanQrCodeList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询业务员设备列表")
    public ResponseData getSalesmanQrCodeList(@RequestParam(name = "salesmanId", required = true) Long salesmanId,
                                              @RequestParam(name = "isAssignStore", required = false) Boolean isAssignStore,
                                              @RequestParam(name = "serialNumber", required = false) String serialNumber,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("salesmanId", salesmanId);
            param.put("isAssignStore", isAssignStore);
            param.put("serialNumber", serialNumber);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(payQrCodeService.getQrCodeList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getStoreQrCodeList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询门店设备列表")
    public ResponseData getStoreQrCodeList(@RequestParam(name = "storeId", required = true) Long storeId,
                                           @RequestParam(name = "serialNumber", required = false) String serialNumber,
                                           @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                           @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("storeId", storeId);
            param.put("serialNumber", serialNumber);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(payQrCodeService.getQrCodeList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
