package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.dto.StoreRenovationBrowseRequirementDto;
import shop.alien.entity.store.dto.StoreRenovationRequirementDto;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.StoreRenovationBrowseRecordService;
import shop.alien.store.service.StoreRenovationRequirementService;

import java.util.List;

/**
 * 装修需求动态表 Controller
 *
 * @author auto-generated
 * @since 2025-01-15
 */
@Slf4j
@Api(tags = {"装修需求动态"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/renovation/requirement")
@RequiredArgsConstructor
public class StoreRenovationRequirementController {

    private final StoreRenovationRequirementService requirementService;
    private final StoreRenovationBrowseRecordService browseRecordService;

    @ApiOperation("发布或更新装修需求")
    @ApiOperationSupport(order = 1)
    @PostMapping("/saveOrUpdate")
    public R<Boolean> saveOrUpdate(@RequestBody StoreRenovationRequirementDto dto) {
        log.info("StoreRenovationRequirementController.saveOrUpdate?dto={}", dto);
        try {
            boolean result = requirementService.saveOrUpdateRequirement(dto);
            if (result) {
                return R.success("操作成功");
            }
            return R.fail("操作失败");
        } catch (Exception e) {
            log.error("保存装修需求失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("获取装修需求详情")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需求ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getDetail")
    public R<StoreRenovationRequirementDto> getDetail(@RequestParam Integer id) {
        log.info("StoreRenovationRequirementController.getDetail?id={}", id);
        try {
            // 增加浏览数
            requirementService.incrementViewCount(id);
            
            StoreRenovationRequirementDto dto = requirementService.getRequirementDetail(id);
            if (dto == null) {
                return R.fail("装修需求不存在");
            }
            return R.data(dto);
        } catch (Exception e) {
            log.error("获取装修需求详情失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("分页查询装修需求列表")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "Integer", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "city", value = "城市", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "renovationType", value = "装修类型（1:新房装修, 2:旧房改造, 3:局部装修）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态（0:草稿, 1:已发布, 2:已下架）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "auditStatus", value = "审核状态（0:待审核, 1:审核通过, 2:审核失败）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "sortType", value = "排序类型（1:最新发布, 2:价格最高, 3:面积最大）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "requirementTitle", value = "需求标题（模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间（格式：yyyy-MM-dd，查询创建时间范围）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间（格式：yyyy-MM-dd，查询创建时间范围）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hasCommunicated", value = "是否已沟通（true:已沟通, false:未沟通）", dataType = "Boolean", paramType = "query")
    })
    @GetMapping("/getPage")
    public R<IPage<StoreRenovationRequirementDto>> getPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer storeId,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) Integer renovationType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false, defaultValue = "1") Integer sortType,
            @RequestParam(required = false) String requirementTitle,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Boolean hasCommunicated) {
        log.info("StoreRenovationRequirementController.getPage?page={}, size={}, storeId={}, city={}, renovationType={}, status={}, auditStatus={}, sortType={}, requirementTitle={}, startTime={}, endTime={}, hasCommunicated={}",
                page, size, storeId, city, renovationType, status, auditStatus, sortType, requirementTitle, startTime, endTime, hasCommunicated);
        try {
            Page<StoreRenovationRequirementDto> pageParam = new Page<>(page, size);
            IPage<StoreRenovationRequirementDto> result = requirementService.getRequirementPage(
                    pageParam, storeId, city, renovationType, status, auditStatus, sortType, requirementTitle, startTime, endTime, hasCommunicated);
            return R.data(result);
        } catch (Exception e) {
            log.error("分页查询装修需求失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("更新状态（草稿/发布/下架）")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需求ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "状态（0:草稿, 1:已发布, 2:已下架）", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/updateStatus")
    public R<Boolean> updateStatus(@RequestParam Integer id, @RequestParam Integer status) {
        log.info("StoreRenovationRequirementController.updateStatus?id={}, status={}", id, status);
        try {
            boolean result = requirementService.updateStatus(id, status);
            if (result) {
                return R.success("更新成功");
            }
            return R.fail("更新失败");
        } catch (Exception e) {
            log.error("更新状态失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("审核装修需求")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需求ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "auditStatus", value = "审核状态（1:审核通过, 2:审核失败）", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "auditReason", value = "审核原因（审核失败时必填）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "auditUserId", value = "审核人ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/audit")
    public R<Boolean> audit(@RequestParam Integer id,
                            @RequestParam Integer auditStatus,
                            @RequestParam(required = false) String auditReason,
                            @RequestParam Integer auditUserId) {
        log.info("StoreRenovationRequirementController.audit?id={}, auditStatus={}, auditReason={}, auditUserId={}",
                id, auditStatus, auditReason, auditUserId);
        try {
            boolean result = requirementService.auditRequirement(id, auditStatus, auditReason, auditUserId);
            if (result) {
                return R.success("审核成功");
            }
            return R.fail("审核失败");
        } catch (Exception e) {
            log.error("审核装修需求失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("删除装修需求")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需求ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/delete")
    public R<Boolean> delete(@RequestParam Integer id) {
        log.info("StoreRenovationRequirementController.delete?id={}", id);
        try {
            boolean result = requirementService.deleteRequirement(id);
            if (result) {
                return R.success("删除成功");
            }
            return R.fail("删除失败");
        } catch (Exception e) {
            log.error("删除装修需求失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("获取门店发布的装修需求列表")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getListByStoreId")
    public R<List<StoreRenovationRequirementDto>> getListByStoreId(@RequestParam Integer storeId) {
        log.info("StoreRenovationRequirementController.getListByStoreId?storeId={}", storeId);
        try {
            List<StoreRenovationRequirementDto> list = requirementService.getRequirementListByStoreId(storeId);
            return R.data(list);
        } catch (Exception e) {
            log.error("获取门店装修需求列表失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("增加咨询数（装修商家查看需求时调用）")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需求ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/incrementInquiryCount")
    public R<Boolean> incrementInquiryCount(@RequestParam Integer id) {
        log.info("StoreRenovationRequirementController.incrementInquiryCount?id={}", id);
        try {
            requirementService.incrementInquiryCount(id);
            return R.success("操作成功");
        } catch (Exception e) {
            log.error("增加咨询数失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @TrackEvent(
            eventType = "CONSULT",
            eventCategory = "INTERACTION",
            targetId = "#{#requirementId}",
            targetType = "STORE"
    )
    @ApiOperation("装修商铺咨询装修需求（记录浏览和咨询历史）")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requirementId", value = "装修需求ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/consultRequirement")
    public R<Boolean> consultRequirement(@RequestParam Integer requirementId) {
        log.info("StoreRenovationRequirementController.consultRequirement?requirementId={}", requirementId);
        try {
            boolean result = browseRecordService.recordInquiryByCurrentUser(requirementId);
            if (result) {
                return R.success("咨询记录成功");
            }
            return R.fail("咨询记录失败");
        } catch (Exception e) {
            log.error("记录咨询失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("查询装修商铺浏览过的普通商铺发布的装修需求列表")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "renovationStoreTel", value = "装修商铺电话（store_info.store_tel）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "normalStoreTel", value = "普通商铺电话（store_info.store_tel，发布装修需求的店铺）", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/getBrowsedRequirements")
    public R<List<StoreRenovationBrowseRequirementDto>> getBrowsedRequirements(
            @RequestParam String renovationStoreTel,
            @RequestParam String normalStoreTel) {
        log.info("StoreRenovationRequirementController.getBrowsedRequirements?renovationStoreTel={}, normalStoreTel={}", renovationStoreTel, normalStoreTel);
        try {
            List<StoreRenovationBrowseRequirementDto> list = browseRecordService.getBrowsedRequirementsByStoreTel(renovationStoreTel, normalStoreTel);
            return R.data(list);
        } catch (Exception e) {
            log.error("查询浏览过的装修需求失败: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }
}

