/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.multishop.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.yami.shop.bean.app.dto.ShopHeadInfoDto;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.SmsType;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.ShopDetailParam;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.delivery.comment.api.paotui.PaoTuiApi;
import com.yami.shop.delivery.comment.api.paotui.model.request.StoreAddRequest;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SmsLogService;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 * @author lgh on 2018/08/29.
 */
@Controller
@RequestMapping("/shop/shopDetail")
public class ShopDetailController {

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
    private MapperFacade mapperFacade;

//    @Autowired
//    private ShopAuditingService shopAuditingService;

    @Autowired
    private OfflineHandleEventService offlineHandleEventService;

    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private PaoTuiApi paoTuiApi;


    /**
     * 修改分销开关
     */
    @PutMapping("/isDistribution")
    public ResponseEntity<Void> updateIsDistribution(@RequestParam Integer isDistribution) {
        ShopDetail shopDetail = new ShopDetail();
        shopDetail.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDetail.setIsDistribution(isDistribution);
        shopDetailService.updateById(shopDetail);
        // 更新完成后删除缓存
        shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId());
        return ResponseEntity.ok().build();
    }

    /**
     * 获取信息
     */
    @GetMapping("/info")
    public ResponseEntity<ShopDetail> info() {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(SecurityUtils.getShopUser().getShopId());
        return ResponseEntity.ok(shopDetail);
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<ShopDetail>> page(PageParam<ShopDetail> page) {
        ShopDetail shopDetail = new ShopDetail();
        shopDetail.setUserId(SecurityUtils.getShopUser().getUserId());
        IPage<ShopDetail> shopDetails = shopDetailService.page(page,
                new LambdaQueryWrapper<ShopDetail>()
                        .like(StrUtil.isNotBlank(shopDetail.getShopName()), ShopDetail::getShopName, shopDetail.getShopName())
                        .eq(shopDetail.getUserId() != null, ShopDetail::getUserId, shopDetail.getUserId())
                        .orderByDesc(ShopDetail::getShopId));
        return ResponseEntity.ok(shopDetails);
    }

    /**
     * 修改店铺信息
     */
    @PutMapping
    public ResponseEntity<Void> update(@Valid @RequestBody ShopDetailParam shopDetailParam) {
        ShopDetail dbShopDetail = shopDetailService.getShopDetailByShopId(SecurityUtils.getShopUser().getShopId());
        ShopDetail shopDetail = mapperFacade.map(shopDetailParam, ShopDetail.class);
        try {
            StoreAddRequest storeAddRequest = new StoreAddRequest();
            storeAddRequest.setOrigin_id(dbShopDetail.getShopId());
            storeAddRequest.setName(shopDetail.getShopName());
            storeAddRequest.setPhone(shopDetail.getTel());
            storeAddRequest.setCity(shopDetail.getCityId());
            storeAddRequest.setDistrict(shopDetail.getAreaId());
            storeAddRequest.setAddress(shopDetail.getProvince() + shopDetail.getCity() + shopDetail.getArea() + shopDetail.getShopAddress());
            storeAddRequest.setLongitude(shopDetail.getShopLng());
            storeAddRequest.setLatitude(shopDetail.getShopLat());
            storeAddRequest.setCategory(shopDetail.getCategory());
            String s = paoTuiApi.shopAdd(storeAddRequest);
            shopDetail.setShopCode(s);
            shopDetail.setSync(true);

        } catch (Exception e) {
            e.printStackTrace();
        }


        shopDetail.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDetail.setUpdateTime(new Date());
        shopDetailService.updateShopDetail(shopDetail, dbShopDetail);


        return ResponseEntity.ok().build();
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineHandleEventByShopId/{shopId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByShopId(@PathVariable("shopId") Long shopId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SHOP.getValue(), shopId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(offlineHandleEventAuditParam.getHandleId());
        if (shopDetail == null) {
            throw new GlobalException("未找到该店铺信息");
        }
        shopDetailService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        return ResponseEntity.ok().build();
    }

    /**
     * 发送验证码接口
     */
    @PostMapping("/sendCode")
    public ResponseEntity<String> sendLoginCode() {
        ShopDetail shopDetail = shopDetailService.getById(SecurityUtils.getShopUser().getShopId());
//        if(Objects.equals(shopDetail.getShopId(), Constant.MAIN_SHOP)){
//            throw  new YamiShopBindException("自营店无法提现");
//        }
        // 每个ip每分钟只能发十个注册的验证码，免得接口被利用
        if (Objects.equals(shopDetail.getShopId(), Constant.MAIN_SHOP)) {
            throw new GlobalException("自营店无法提现");
        }
        smsLogService.sendSms(SmsType.VALID, shopDetail.getShopId().toString(), shopDetail.getMobile(), Maps.newHashMap());
        return ResponseEntity.ok(shopDetail.getMobile());
    }

    @GetMapping("/headInfo")
    @ApiOperation(value = "店铺头部信息", notes = "获取的店铺头部信息")
    public ResponseEntity<ShopHeadInfoDto> getShopHeadInfo(Long shopId) {
        ShopHeadInfoDto shopHeadInfoDto = new ShopHeadInfoDto();
        // 粉丝数量
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if(!Objects.equals(shopDetail.getShopStatus(),1)){
            shopHeadInfoDto.setShopStatus(shopDetail.getShopStatus());
            return ResponseEntity.ok(shopHeadInfoDto);
        }
        shopHeadInfoDto.setShopId(shopId);
        shopHeadInfoDto.setShopLogo(shopDetail.getShopLogo());
        shopHeadInfoDto.setShopName(shopDetail.getShopName());
        shopHeadInfoDto.setIntro(shopDetail.getIntro());
        shopHeadInfoDto.setTel(shopDetail.getTel());
        shopHeadInfoDto.setThirdPartyCode(shopDetail.getThirdPartyCode());
        return ResponseEntity.ok(shopHeadInfoDto);
    }

}
