package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.bo.ShopBo;
import org.dromara.zhishu.domain.bo.XyBindBo;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.domain.vo.XyBindVo;
import org.dromara.zhishu.service.IShopService;
import org.dromara.zhishu.service.IXyBindService;
import org.dromara.zhishu.service.impl.XianYvQueryShopImpl;
import org.redisson.api.RList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xy/api")
public class XyBindController {

    private final IXyBindService xyBindService;
    private final IShopService shopService;
    private final XianYvQueryShopImpl xianYvQueryShop;

    @GetMapping("/list")
    public TableDataInfo<XyBindVo> listByCreateBy(XyBindBo bo, PageQuery pageQuery) {
        return xyBindService.queryPageList(bo, pageQuery);
    }

    @SaIgnore
    @GetMapping("/insertBlind/{appName}/{mallId}/{token}")
    public R<String> insertBlind(@PathVariable("appName") String appName,@PathVariable("mallId") Long mallId,@PathVariable("token") String token) {
        Long userId = LoginHelper.getUserId();
        XyBindBo bo = new XyBindBo();
        if(xyBindService.queryById(token) != null){
            return R.fail("您已绑定该店铺");
        } else {
            bo.setAppName(appName);
            bo.setMallId(mallId);
            bo.setToken(token);
            bo.setCreateBy(userId);

            xyBindService.insertByBo(bo);
            return R.ok("成功绑定店铺");
        }
    }

    @SaIgnore
    @GetMapping("/updateXyBind/{token}/{appName}")
    public R<String> updateXyBind(@PathVariable("token") String token, @PathVariable("appName") String appName) {
        Long userId = LoginHelper.getUserId();

        // 根据token查询绑定信息
        XyBindVo existingBind = xyBindService.queryById(token);
        if(existingBind == null){
            return R.fail("未找到对应的绑定信息");
        }

        // 更新appName
        XyBindBo bo = new XyBindBo();
        bo.setToken(token);
        bo.setAppName(appName);
        bo.setUpdateBy(userId);

        // 调用更新服务
        boolean success = xyBindService.updateByBo(bo);
        if(success) {
            return R.ok("成功更新闲管家名");
        } else {
            return R.fail("更新失败");
        }
    }

    @SaIgnore
    @GetMapping("/deleteXyBind/{token}")
    public R<String> deleteXyBind(@PathVariable("token") String token) {
        Long userId = LoginHelper.getUserId();

        // 根据token查询绑定信息
        XyBindVo existingBind = xyBindService.queryById(token);
        if(existingBind == null){
            return R.fail("未找到对应的绑定信息");
        }

        // 删除绑定信息
        boolean success = xyBindService.deleteByToken(token);
        if(success) {
            return R.ok("成功删除绑定信息");
        } else {
            return R.fail("删除失败");
        }
    }

    // 同步闲鱼店铺
    @SaIgnore
    @GetMapping("/syncShop/{appName}/{mallId}/{token}")
    public R<String> syncShop(@PathVariable("appName") String appName,@PathVariable("mallId") Long mallId,@PathVariable("token") String token) {
        Long userId = LoginHelper.getUserId();

        R<List<Map<String, String>>> shopResult = xianYvQueryShop.XianYvQueryShop(mallId.toString(), token);

        if ((shopResult.getCode() == 200) && shopResult.getData() != null && !shopResult.getData().isEmpty()) {
            List<Map<String, String>> xyUser = shopResult.getData();

            // 循环创建店铺，每个店铺名称创建一个店铺记录
            for (Map<String, String> userInfo : xyUser) {
                
                String userName = userInfo.get("user_name");
                String shopName = userInfo.get("shop_name");
                String expirationTime = userInfo.get("expiration_time");

                ShopVo shopVo = shopService.selectByGoofishShopKey(userName);
                ShopBo shopBo = new ShopBo();
                if (shopVo != null) {
                    shopBo.setId(shopVo.getId());
                    shopBo.setShopName(shopVo.getShopName());
                    shopBo.setMallId(Long.parseLong(mallId.toString()));
                    shopBo.setToken(token);
                    long timestamp = Long.parseLong(expirationTime) * 1000L;
                    shopBo.setExpirationTime(new Date(timestamp));
                    shopBo.setShopAliasName(shopVo.getShopName());
                    shopBo.setShopKey(shopVo.getShopKey());
                    shopBo.setShopGroup(appName);
                    long currentTimestamp = System.currentTimeMillis();
                    shopBo.setUpdateTime(new Date(currentTimestamp));
                    if (currentTimestamp < timestamp) {
                        shopBo.setShopAuthorize("1");
                    }

                    shopService.updateByBo(shopBo);
                } else {
                    // 创建咸鱼店铺
                    shopBo.setShopName(shopName);  // 使用接口返回的店铺名称
                    shopBo.setMallId(Long.parseLong(mallId.toString()));
                    shopBo.setToken(token);
                    shopBo.setShopKey(userName);
                    shopBo.setShopAliasName(shopName);  // 使用接口返回的店铺名称
                    long timestamp = Long.parseLong(expirationTime) * 1000L;
                    shopBo.setExpirationTime(new Date(timestamp));  // 使用接口返回的店铺过期时间
                    shopBo.setShopAuthorize("1");
                    shopBo.setShopGroup(appName);

                    shopBo.setShopType("5");
                    shopBo.setAddTime(DateUtils.parseDate(DateUtils.getTime()));
                    shopBo.setCreateBy(userId);
                    shopBo.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
                    shopBo.setTenant_id("000000");
                    shopBo.setShopAuthorize("1");
                    long currentTimestamp = System.currentTimeMillis();
                    shopBo.setUpdateTime(new Date(currentTimestamp));

                    shopService.insertByBo(shopBo);

                    // 可以添加日志记录
                    System.out.println("成功创建店铺: " + shopName);
                }
            }

            return R.ok("成功创建 " + xyUser.size() + " 个店铺");

        } else {
            return R.ok("账户店铺为空，无法添加");
        }
    }
}