package shop.alien.store.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreClockIn;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.store.vo.ClockInRecordValidateVo;
import shop.alien.entity.store.vo.StoreClockInDeleteFlagVo;
import shop.alien.entity.store.vo.StoreClockInVo;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.StoreClockInService;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.common.TokenInfo;
import springfox.documentation.annotations.ApiIgnore;

@Slf4j
@Api(tags = {"店铺打卡"})
@CrossOrigin
@RestController
@RequestMapping("/storeClockIn")
@RequiredArgsConstructor
public class StoreClockInController {

    private final StoreClockInService storeClockInService;

    @TrackEvent(
            eventType = "CHECKIN",
            eventCategory = "INTERACTION",
            storeId = "#{#storeClockIn.storeId}",
            targetType = "STORE",
            targetId = "#{#storeClockIn.id}"
    )
    @ApiOperation("打卡")
    @ApiOperationSupport(order = 1)
    @PostMapping("/addStoreClockIn")
    public R<StoreClockIn> addStoreClockIn(@RequestBody StoreClockIn storeClockIn) {
        log.info("StoreClockInController.addStoreClockIn?storeClockIn={}", storeClockIn.toString());
        return R.data(storeClockInService.addStoreClockIn(storeClockIn));
    }

    @ApiOperation("打卡列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "分页页数", dataType = "Integer", defaultValue = "1", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "Integer", defaultValue = "10", paramType = "query"),
            @ApiImplicitParam(name = "phoneId", value = "'user_' + 手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mySelf", value = "是否只查看自己（0-否  1-是）", dataType = "Integer", defaultValue = "0", paramType = "query"),
            @ApiImplicitParam(name = "storeId", value = "店铺id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份（取 store_clock_in.created_time 年份）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "month", value = "月份（1-12，取 store_clock_in.created_time 月份）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "city", value = "城市（store_info.administrative_region_city_name）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getStoreClockInList")
    public R<IPage<StoreClockInVo>> getStoreClockInList(Integer userId, int page, int size, String phoneId, int mySelf,
                                                        @RequestParam(required = false) Integer storeId,
                                                        @RequestParam(required = false) Integer year,
                                                        @RequestParam(required = false) Integer month,
                                                        @RequestParam(required = false) String city) {
        log.info("StoreClockInController.getStoreClockInList?userId={},page={},size={},phoneId={},mySelf={},storeId={},year={},month={},city={}",
                userId, page, size, phoneId, mySelf, storeId, year, month, city);
//        JSONObject data = JwtUtil.getCurrentUserInfo();
//        Integer loginUserId = data != null ? data.getInteger("userId") : null;
//        if (mySelf == 1 && loginUserId != null) {
//            // 查看“我的打卡”时，统一使用登录用户，避免前端误传 userId 导致查不到数据
//            userId = loginUserId;
//        } else if (userId == null) {
//            userId = loginUserId;
//        }
        return R.data(storeClockInService.getStoreClockInList(userId, page, size, phoneId, mySelf, storeId, year, month, city));
    }

    @ApiOperation("删除打卡记录")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键id", dataType = "Integer", paramType = "query")})
    @GetMapping("/deleteClockIn")
    public R<IPage<StoreClockInVo>> deleteClockIn(Integer id) {
        log.info("StoreClockInController.deleteClockIn?id={}", id);
        int result = storeClockInService.deleteClockIn(id);
        return 1 == result ? R.success("删除成功") : R.fail("删除失败");
    }

    @ApiOperation("设置权限")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户id", dataType = "int", paramType = "query"), @ApiImplicitParam(name = "id", value = "主键id", dataType = "Integer", paramType = "query"), @ApiImplicitParam(name = "permission", value = "权限  1-所有人可见  2-仅自己可见", dataType = "int", paramType = "query")})
    @GetMapping("/setPermission")
    public R<IPage<StoreClockInVo>> setPermission(int userId, Integer id, int permission) {
        log.info("StoreClockInController.setPermission?userId={},id={},permission={}", userId, id, permission);
        int result = storeClockInService.setPermission(userId, id, permission);
        return 1 <= result ? R.success("设置成功") : R.fail("设置失败");
    }

    @ApiOperation("设置图片和ai帮写内容")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "imgUrl", value = "打卡图片", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "maybeAiContent", value = "ai帮写内容", dataType = "String", paramType = "query")})
    @PostMapping("/setImgAndAiContent")
    public R<IPage<StoreClockInVo>>  setImgAndAiContent(@RequestBody StoreClockIn storeClockIn) {
        log.info("StoreClockInController.setImgAndAiContent?id={},img={},aiContent={}", storeClockIn.getId(), storeClockIn.getImgUrl(),storeClockIn.getMaybeAiContent());
        int result = storeClockInService.setImgAndAiContent(storeClockIn.getId(), storeClockIn.getImgUrl(),storeClockIn.getMaybeAiContent());
        return 1 == result ? R.success("设置成功") : R.fail("设置失败");
    }

    // 根据id查询打卡记录
    @ApiOperation("根据id查询打卡记录")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键id", dataType = "Integer", paramType = "query")})
    @GetMapping("/getStoreClockInById")
    public R<StoreClockInVo> getStoreClockInById(@ApiIgnore @TokenInfo UserLoginInfo userLoginInfo, Integer id) {
        Integer userId = userLoginInfo != null ? userLoginInfo.getUserId() : null;
        log.info("StoreClockInController.getStoreClockInById?userId={},id={}", userId, id);
        try {
            return R.data(storeClockInService.getStoreClockInById(id, userId));
        } catch (IllegalArgumentException e) {
            return R.failWithOkStatus(e.getMessage());
        }
    }

    @ApiOperation("打卡记录筛选校验（年份各月是否有打卡、可选城市过滤、用户打卡涉及城市列表）")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id（可空，空则从登录态解析）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份，用于返回该年1～12月是否打卡；不传则 months 为空列表", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "city", value = "行政区域市名称，传入后月份统计仅含该城市下的打卡；不传或空为不限城市", dataType = "String", paramType = "query")
    })
    @GetMapping("/getClockInRecordValidate")
    public R<ClockInRecordValidateVo> getClockInRecordValidate(Integer userId,
                                                               @RequestParam(required = false) Integer year,
                                                               @RequestParam(required = false) String city) {
        if (userId == null) {
            JSONObject data = JwtUtil.getCurrentUserInfo();
            if (null != data) {
                userId = data.getInteger("userId");
            }
        }
        if (userId == null) {
            return R.fail("用户未登录或缺少 userId");
        }
        log.info("StoreClockInController.getClockInRecordValidate?userId={},year={},city={}", userId, year, city);
        return R.data(storeClockInService.getClockInRecordValidate(userId, year, city));
    }

    @ApiOperation("根据主键查询删除标记及门店营业状态")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键id", dataType = "Integer", paramType = "query")})
    @GetMapping("/getDeleteFlagById")
    public R<StoreClockInDeleteFlagVo> getDeleteFlagById(Integer id) {
        log.info("StoreClockInController.getDeleteFlagById?id={}", id);
        return R.data(storeClockInService.getDeleteFlagById(id));
    }
}
