
package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.ShopDetailService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import com.yami.shop.common.util.R;

/**
 * 门店详细信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-11-26
 */
@RestController
@AllArgsConstructor
@RequestMapping("/platform/shopDetail")
public class ShopDetailController {

    private final ShopDetailService shopDetailService;

    /**
     * 分页获取门店详细列表
     */
    @GetMapping("/page")
    public R<IPage<ShopDetail>> page(@ModelAttribute PageParam pageParam,
                                      @ModelAttribute ShopDetail shopDetail ) {
        IPage<ShopDetail> page = shopDetailService.page(pageParam,new LambdaQueryWrapper<ShopDetail>()
                .like(ObjectUtils.isNotEmpty(shopDetail.getShopName()),ShopDetail::getShopName, shopDetail.getShopName())
                .like(ObjectUtils.isNotEmpty(shopDetail.getHbStationNo()),ShopDetail::getHbStationNo, shopDetail.getHbStationNo()));
        return R.SUCCESS(page);
    }

    /**
     * 获取所有的门店
     */
    @GetMapping("/list")
    public R<List<ShopDetail>> list() {
        List<ShopDetail> list = shopDetailService.list();
        return R.SUCCESS(list);
    }

    /**
     * 修改门店拆单信息
     */
    @PutMapping("/updateShopDetail")
    public R updateShopDetail(@RequestBody ShopDetail shopDetail) {
        if (shopDetail.getShopId()==null){
            throw new GlobalException("店铺id不能为空");
        }
        shopDetailService.updateById(shopDetail);
        return R.SUCCESS();
    }



//    /**
//     * 通过活动id获取下线信息
//     */
//    @GetMapping("/getOfflineHandleEventByShopId/{shopId}")
//    @PreAuthorize("@pms.hasPermission('shop:shopAuditing:info')")
//    public R<OfflineHandleEvent> getOfflineHandleEventByShopId(@PathVariable("shopId") Long shopId) {
//        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SHOP.getValue(), shopId);
//        return R.SUCCESS(offlineHandleEvent);
//    }

//    /**
//     * 下线活动
//     */
//    @PostMapping("/offline")
//    @PreAuthorize("@pms.hasPermission('shop:shopAuditing:audit')")
//    public R offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
//        Long sysUserId = SecurityUtils.getSysUser().getUserId();
//        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(offlineHandleEvent.getHandleId());
//        if (shopDetail == null) {
//            throw new GlobalException("未找到该店铺信息");
//        }
//        if (!Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
//            throw new GlobalException("店铺不处于营业状态,不能进行下线");
//        }
//        shopDetailService.offline(shopDetail, offlineHandleEvent.getOfflineReason(), sysUserId);
//
//        // 清除用户登陆token
//        User user = userService.getUserByUserId(shopDetail.getUserId());
//        if (!Objects.isNull(user)) {
//            List<AppConnect> appConnects = appConnectService.list(new LambdaQueryWrapper<AppConnect>().eq(AppConnect::getUserId, user.getUserId()));
//            if (CollectionUtils.isNotEmpty(appConnects)) {
//                for (AppConnect appConnect : appConnects) {
//                    // 移除登录成功的验证缓存
//                    Map<String, String> values = new LinkedHashMap<>();
//                    values.put("username", appConnect.getAppId() + StrUtil.COLON + appConnect.getBizUserId());
//                    values.put("client_id", "null");
//                    values.put("scope", "");
//                    String key = SecurityConstants.YAMI_OAUTH_PREFIX + "auth_to_access:" + generateKey(values);
//                    RedisUtil.del(key);
//                    // 移除token校验的缓存
//                    Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientIdAndUserName(StrUtil.NULL, appConnect.getAppId() + StrUtil.COLON + appConnect.getBizUserId());
//                    for (OAuth2AccessToken token : tokens) {
//                        RedisUtil.del(SecurityConstants.YAMI_OAUTH_PREFIX + "access:" + token.getValue());
//                    }
//                }
//            }
//        }
//        return R.SUCCESS();
//    }
//
//    /**
//     * 店铺审核重新开店
//     */
//    @PostMapping("/auditShop")
//    @PreAuthorize("@pms.hasPermission('shop:shopAuditing:audit')")
//    public R auditOfflineShop(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
//        Long sysUserId = SecurityUtils.getSysUser().getUserId();
//        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(offlineHandleEventAuditParam.getHandleId());
//        if (shopDetail == null) {
//            throw new GlobalException("未找到店铺信息");
//        }
//        shopDetailService.auditOfflineShop(offlineHandleEventAuditParam, sysUserId);
//
//        return R.SUCCESS();
//    }
//
//    private String generateKey(Map<String, String> values) {
//        MessageDigest digest;
//        try {
//            digest = MessageDigest.getInstance("MD5");
//            byte[] bytes = digest.digest(values.toString().getBytes(StandardCharsets.UTF_8));
//            return String.format("%032x", new BigInteger(1, bytes));
//        } catch (NoSuchAlgorithmException nsae) {
//            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).", nsae);
//        }
//    }

}
