package shop.alien.storeplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartRequest;
import shop.alien.config.redis.BaseRedisService;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.StoreInfoDto;
import shop.alien.entity.store.vo.*;
import shop.alien.entity.storePlatform.StoreLicenseHistory;
import shop.alien.mapper.*;
import shop.alien.mapper.storePlantform.StoreLicenseHistoryMapper;
import shop.alien.storeplatform.service.StoreBusinessService;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 二期-门店信息Controller
 *
 * @author ssk
 * @since 2024-12-05
 */
@Slf4j
@Api(tags = {"商家平台-门店信息"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/store/info")
@RequiredArgsConstructor
public class StoreBusinessController {

    private final StoreBusinessService storeBusinessService;

    private final TagsMainMapper tagsMainMapper;

    private final WebAuditMapper webAuditMapper;

    private final BaseRedisService baseRedisService;

    private final StoreCommentSummaryInterestMapper storeCommentSummaryInterestMapper;

    /** 商户证照历史记录数据访问对象 */
    private final StoreLicenseHistoryMapper licenseHistoryMapper;

    private final StoreUserMapper storeUserMapper;

    private final StoreImgMapper storeImgMapper;

    @ApiOperation("获取所有门店")
    @ApiOperationSupport(order = 1)
    @GetMapping("/getAll")
    public R<List<StoreInfo>> getAll() {
        log.info("StoreInfoController.getAll");
        return R.data(storeBusinessService.list());
    }

    @ApiOperation("根据id获取门店")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "Long", paramType = "query", required = true)})
    @GetMapping("/getOne")
    public R<StoreInfo> getOne(Integer id) {
        log.info("StoreInfoController.getOne?id={}", id);
        return R.data(storeBusinessService.getById(id));
    }

    @ApiOperation("门店装修-编辑门店信息")
    @ApiOperationSupport(order = 3)
    @PostMapping("/saveOrUpdate")
    public R<StoreInfo> saveOrUpdate(@RequestBody StoreInfoDto storeInfo) {
        log.info("StoreInfoController.saveOrUpdate?storeInfo={}", storeInfo);
        try {
            int num = storeBusinessService.saveOrUpdateStoreInfo(storeInfo);
            if (num > 0) {
                return R.success("成功");
            }
            return R.fail("失败");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("web端新增门店")
    @ApiOperationSupport(order = 3)
    @PostMapping("/saveStoreInfo")
    public R saveStoreInfo(@RequestBody StoreInfoDto storeInfoDto) throws Exception {
        log.info("StoreInfoController.saveStoreInfo?storeInfoDto={}", storeInfoDto);
        StoreInfoVo storeInfoVo = storeBusinessService.saveStoreInfo(storeInfoDto);
        if (storeInfoVo != null) {
            return R.data(storeInfoVo);
        }
        return R.fail("失败");
    }

    @ApiOperation("新增门店草稿")
    @ApiOperationSupport(order = 3)
    @PostMapping("/saveStoreInfoDraft")
    public R<Boolean> saveStoreInfoDraft(@RequestBody StoreInfoDraft storeInfoDraft) {
        log.info("StoreInfoController.saveStoreInfoDraft?storeInfoDraft={}", storeInfoDraft);
        int num = storeBusinessService.saveStoreInfoDraft(storeInfoDraft);
        if (num > 0) {
            return R.data(true);
        }
        return R.fail("失败");
    }

    @ApiOperation("查询门店草稿")
    @ApiOperationSupport(order = 3)
    @GetMapping("/selectDraftByUserId")
    public R<StoreInfoDraft> selectDraftByUserId(int storeUserId) throws Exception {
        log.info("StoreInfoController.saveStoreInfoDraft?storeUserId={}", storeUserId);
        return R.data(storeBusinessService.selectDraftByUserId(storeUserId));
    }


    @ApiOperation("web端修改门店")
    @ApiOperationSupport(order = 3)
    @PostMapping("/editStoreInfo")
    public R editStoreInfo(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.editStoreInfo?storeInfoDto={}", storeInfoDto);
        StoreInfoVo storeInfoVo = storeBusinessService.editStoreInfo(storeInfoDto);
        if (storeInfoVo != null) {
            return R.data(storeInfoVo);
        }
        return R.fail("失败");
    }

    @ApiOperation("web修改门店抽成")
    @ApiOperationSupport(order = 3)
    @PostMapping("/updateStoreCommissionRate")
    public R updateStoreCommissionRate(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.updateStoreCommissionRate?storeInfoDto={}", storeInfoDto);
        if (storeBusinessService.editStoreCommissionRate(storeInfoDto) > 0) {
            return R.data("成功");
        }
        return R.fail("失败");
    }

    @ApiOperation("web端删除门店")
    @ApiOperationSupport(order = 3)
    @PostMapping("/deleteStoreInfo")
    public R deleteStoreInfo(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.deleteStoreInfo?storeInfoDto={}", storeInfoDto);
        String s;
        try {
            s = storeBusinessService.deleteStoreInfo(storeInfoDto);
        } catch (Exception e) {
            return R.fail("失败");
        }
        if ("成功".equals(s)) {
            return R.success(s);
        } else {
            return R.fail(s);
        }
    }

    @ApiOperation("web端重置商户及管理账户密码")
    @ApiOperationSupport(order = 3)
    @PostMapping("/restPassword")
    public R restPassword(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.restPassword?storeInfoDto={}", storeInfoDto);
        try {
            storeBusinessService.restPassword(storeInfoDto);
        } catch (Exception e) {
            return R.fail("失败");
        }
        return R.success("成功");
    }

    @ApiOperation(value = "删除门店")
    @ApiOperationSupport(order = 4)
    @PostMapping("/delete")
    public R<String> delete(@RequestBody List<Integer> ids) {
        log.info("StoreInfoController.delete?ids={}", ids);
        if (storeBusinessService.removeByIds(ids)) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @ApiOperation(value = "门店详细信息")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "Long", paramType = "query", required = true)})
    @GetMapping("/getDetail")
    public R<StoreMainInfoVo> getDetail(Integer id) {
        log.info("StoreInfoController.getDetail?id={}", id);
        return R.data(storeBusinessService.getDetail(id));
    }

    @ApiOperation(value = "门店信息-修改后展示")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "Long", paramType = "query", required = true)})
    @GetMapping("/getStoreInfo")
    public R<StoreMainInfoVo> getStoreInfo(Integer id) {
        log.info("StoreInfoController.getStoreInfo?id={}", id);
        return R.data(storeBusinessService.getStoreInfo(id));
    }

    /**
     * web-分页查询店铺信息
     *
     * @param pageNum      页码
     * @param pageSize     页容
     * @param storeName    门店名称
     * @param storeContact 联系人
     * @param storePhone   门店电话
     * @param storeType    门店类型
     * @return IPage<StoreInfoVo>
     */
    @ApiOperation("web-分页查询店铺信息")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "int", paramType = "query", required = true), @ApiImplicitParam(name = "storeName", value = "门店名称", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeContact", value = "门店联系人", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storePhone", value = "门店电话", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeType", value = "门店类型", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "expiredState", value = "过期状态", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "businessSection", value = "经营板块", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeApplicationStatus", value = "门店审核状态", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "jingdu", value = "jingdu", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "weidu", value = "weidu", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "renewContractStatus", value = "门店续签合同状态", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "foodLicenceStatus", value = "门店经营许可证状态", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "foodLicenceWhetherExpiredStatus", value = "门店经营许可证是否过期状态", dataType = "String", paramType = "query")})
    @GetMapping("/getStorePage")
    public R<IPage<StoreInfoVo>> getStoresPage(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize, @RequestParam(required = false) String storeName, @RequestParam(required = false) String storeContact, @RequestParam(required = false) String id, @RequestParam(required = false) String storePhone, @RequestParam(required = false) String storeType, @RequestParam(required = false) String expiredState, @RequestParam(required = false) String storeApplicationStatus, @RequestParam(required = false) String businessSection, @RequestParam(required = false) String storeStatus, @RequestParam(required = false) String jingdu, @RequestParam(required = false) String weidu, @RequestParam(required = false) String renewContractStatus, @RequestParam(required = false) String foodLicenceStatus, @RequestParam(required = false) String foodLicenceWhetherExpiredStatus) {
        log.info("StoreInfoController.getStoresPage?pageNum={},pageSize={},storeName={},storeContact={},id={},storePhone={},storeType={},expiredState={},storeApplicationStatus={},storeStatus={},businessSection={},jingdu={},weidu={},renewContractStatus={},foodLicenceStatus={},foodLicenceWhetherExpiredStatus={}", pageNum, pageSize, storeName, storeContact, id, storePhone, storeType, expiredState, storeApplicationStatus, storeStatus, businessSection, jingdu, weidu, renewContractStatus, foodLicenceStatus, foodLicenceWhetherExpiredStatus);
        return R.data(storeBusinessService.getStorePage(pageNum, pageSize, storeName, storeContact, id, storePhone, storeType, expiredState, storeApplicationStatus, storeStatus, businessSection, jingdu, weidu, renewContractStatus, foodLicenceStatus, foodLicenceWhetherExpiredStatus));
    }

    /**
     * web-重置门店密码
     *
     * @param storeId 门店id
     * @return R
     */
    @ApiOperation("web-重置门店密码")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({@ApiImplicitParam(name = "storeId", value = "门店id", dataType = "int", paramType = "query")})
    @GetMapping("/resetPassword")
    public R<Boolean> resetPassword(@RequestParam("storeId") String storeId) {
        log.info("StoreInfoController.resetPassword?id={}", storeId);
        if (storeBusinessService.resetPassword(storeId)) {
            return R.success("密码重置成功");
        }
        return R.fail("密码重置失败");
    }

    /**
     * web-修改门店状态
     *
     * @param storeId        门店id
     * @param businessStatus 营业状态
     * @return R
     */
    @ApiOperation("web-修改门店状态")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({@ApiImplicitParam(name = "storeId", value = "门店id", dataType = "int", paramType = "query"), @ApiImplicitParam(name = "businessStatus", value = "营业状态(0:正常营业, 1:暂停营业, 2:筹建中, 99:永久关门)", dataType = "int", paramType = "query")})
    @GetMapping("/setStoreState")
    public R<Boolean> setStoreState(@RequestParam("storeId") String storeId, @RequestParam("businessStatus") Integer businessStatus) {
        log.info("StoreInfoController.setStoreState?storeId={},storeState={}", storeId, businessStatus);
        if (storeBusinessService.setStoreState(storeId, businessStatus)) {
            return R.success("状态修改成功");
        }
        return R.fail("状态修改失败");
    }

    /**
     * web-新增店铺
     *
     * @param multipartRequest 文件请求
     * @param store            店铺信息
     * @return R
     */
    @ApiOperation("web-新增店铺")
    @ApiOperationSupport(order = 10)
    @PostMapping("/saveStore")
    public R<Boolean> saveStore(MultipartRequest multipartRequest, StoreInfo store) {
        Set<String> fileNameSet = multipartRequest.getMultiFileMap().keySet();
        log.info("StoreInfoController.saveStore?store={}&file={}", store.toString(), fileNameSet);
        if (storeBusinessService.saveStore(multipartRequest, store)) {
            return R.success("新增成功");
        }
        return R.fail("新增失败");
    }

    @ApiOperation("web-导出Excel")
    @ApiOperationSupport(order = 11)
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportToExcel() {
        log.info("StoreInfoController.exportToExcel");
        return storeBusinessService. exportToExcel();
    }

    @ApiOperation(value = "web端查询经营板块信息")
    @ApiOperationSupport(order = 6)
    @GetMapping("/getBusinessSection")
    public R<List<StoreDictionaryVo>> getBusinessSection() {
        log.info("StoreInfoController.getBusinessSection");
        return R.data(storeBusinessService.getBusinessSection());
    }

    @ApiOperation(value = "web端查询经营板块的经营种类信息")
    @ApiOperationSupport(order = 6)
    @GetMapping("/getBusinessSectionTypes")
    public R<List<StoreDictionaryVo>> getBusinessSectionTypes(@RequestParam("parentId") String parentId) {
        log.info("StoreInfoController.getBusinessSectionTypes?parentId={}", parentId);
        return R.data(storeBusinessService.getBusinessSectionTypes(parentId));
    }

    @ApiOperation(value = "web端查询未绑定店铺的商家端账号")
    @ApiOperationSupport(order = 6)
    @GetMapping("/getUnboundAccountList")
    public R<List<StoreUserVo>> getUnboundAccountList(@RequestParam(value = "id", required = false) String id) {
        log.info("StoreInfoController.getUnboundAccountList");
        return R.data(storeBusinessService.getUnboundAccountList(id));
    }

    @ApiOperation(value = "web端新增经营板块及经营类型")
    @ApiOperationSupport(order = 6)
    @PostMapping("/addBusinessSectionAndTypes")
    public R addBusinessSectionAndTypes(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.addBusinessSectionAndTypes");
        storeBusinessService.addBusinessSectionAndTypes(storeInfoDto);
        return R.success("新增成功");
    }

    @ApiOperation(value = "web端获取店铺明细详情")
    @ApiOperationSupport(order = 6)
    @GetMapping("/getStoreDetail")
    public R getStoreDetail(@RequestParam("id") String id, @RequestParam(value = "userId", required = false) String userId, @RequestParam(value = "jingdu", required = false) String jingdu, @RequestParam(value = "weidu", required = false) String weidu) {
        log.info("StoreInfoController.getStoreDetail?id={},userId={},jingdu={},weidu={}", id, jingdu, weidu);
        StoreInfoVo storeDetail = storeBusinessService.getStoreDetail(id, userId, jingdu, weidu);
        return R.data(storeDetail);
    }

    @ApiOperation(value = "web端审批店铺")
    @ApiOperationSupport(order = 6)
    @GetMapping("/approveStoreInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "approvalStatus", value = "审批状态（1：审批成功，2：审批失败）", dataType = "int", paramType = "query"), @ApiImplicitParam(name = "reason", value = "原因", dataType = "String", paramType = "query")})
    public R approveStoreInfo(@RequestParam("id") String id, @RequestParam("approvalStatus") Integer approvalStatus, @RequestParam(value = "reason", required = false) String reason) {
        log.info("StoreInfoController.approveStoreInfo?id={}&approvalStatus={}&reason={}", id, approvalStatus, reason);
        storeBusinessService.approveStoreInfo(id, approvalStatus, reason);
        return R.success("审批完成");
    }

    @ApiOperation(value = "web端导出店铺信息")
    @ApiOperationSupport(order = 6)
    @GetMapping("/exportExcel")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storePhone", value = "联系电话", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "businessSection", value = "经营板块", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeApplicationStatus", value = "审核状态", dataType = "String", paramType = "query"),})
    public R exportExcel(@RequestParam(value = "id", required = false) String id, @RequestParam(value = "storePhone", required = false) String storePhone, @RequestParam(value = "businessSection", required = false) String businessSection, @RequestParam(value = "storeApplicationStatus", required = false) String storeApplicationStatus) throws IOException {
        log.info("StoreInfoController.exportExcel");
        String excelPath = storeBusinessService.exportExcel(id, storePhone, businessSection, storeApplicationStatus);
        return R.data(excelPath);
    }

    @ApiOperation(value = "web端导出商铺到期时间信息")
    @ApiOperationSupport(order = 6)
    @GetMapping("/exportExcelExpirationTime")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storePhone", value = "联系电话", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "businessSection", value = "经营板块", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeApplicationStatus", value = "审核状态", dataType = "String", paramType = "query"),})
    public R exportExcelExpirationTime(@RequestParam(value = "id", required = false) String id, @RequestParam(value = "expiredState", required = false) String expiredState) throws IOException {
        log.info("StoreInfoController.exportExcelExpirationTime");
        String excelPath = storeBusinessService.exportExcelExpirationTime(id, expiredState);
        return R.data(excelPath);
    }

    @ApiOperation(value = "注销店铺")
    @ApiOperationSupport(order = 14)
    @PostMapping("/logoutStore")
    public R logoutStore(@RequestBody StoreInfoVo storeInfo) {
        log.info("StoreInfoController.logoutStore?storeInfo={}", storeInfo);
        // 2025-11-04 验证码-商家端注销店铺
        String cacheCode = baseRedisService.getString("verification_store_cancel_store_" + storeInfo.getStorePhone());
        if (null == cacheCode) {
            return R.fail("当验证码过期或未发送");
        }
        if (!cacheCode.trim().equals(storeInfo.getVerificationCode().trim())) {
            return R.fail("验证码错误，请重新输入");
        }
        try {
            storeBusinessService.logoutStore(storeInfo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.success("注销成功");
    }

    @ApiOperation(value = "取消注销店铺")
    @ApiOperationSupport(order = 15)
    @PostMapping("/cancelLogoutStore")
    public R cancelLogoutStore(@RequestBody StoreInfoVo storeInfo) {
        log.info("StoreInfoController.cancelLogoutStore?id={}", storeInfo.getId());
        try {
            storeBusinessService.cancelLogoutStore(storeInfo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.success("撤销注销成功");
    }

    /**
     * 八大类用户端筛选
     * 根据筛选条件获取门店信息列表
     *
     * @param screeningOfEightMajorCategoriesVO 筛选条件VO对象
     * @return R<IPage < StoreInfo>> 分页的门店信息列表
     */
    @ApiOperation("八大类用户端筛选")
    @PostMapping(value = "getScreening")
    public R<IPage<StoreInfo>> getScreening(@RequestBody ScreeningOfEightMajorCategoriesVO screeningOfEightMajorCategoriesVO) {
        // 参数校验
        if (screeningOfEightMajorCategoriesVO == null) {
            return R.fail("筛选参数不能为空");
        }
        // 记录请求日志
        log.info("八大类用户端筛选请求 - 参数: screeningId={}, lon={}, lat={}, distance={}, flag={}, pageNum={}, pageSize={}", screeningOfEightMajorCategoriesVO.getScreeningId(), screeningOfEightMajorCategoriesVO.getLon(), screeningOfEightMajorCategoriesVO.getLat(), screeningOfEightMajorCategoriesVO.getDistance(), screeningOfEightMajorCategoriesVO.getFlag(), screeningOfEightMajorCategoriesVO.getPageNum(), screeningOfEightMajorCategoriesVO.getPageSize());
        try {
            // 调用服务层获取筛选结果
            IPage<StoreInfo> result = storeBusinessService.getScreening(screeningOfEightMajorCategoriesVO);
            // 记录响应日志
            log.info("八大类用户端筛选响应 - 总记录数: {}, 当前页: {}, 页大小: {}", result.getTotal(), result.getCurrent(), result.getSize());
            return R.data(result);
        } catch (IllegalArgumentException e) {
            log.warn("八大类用户端筛选参数错误: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("八大类用户端筛选异常", e);
            return R.fail("筛选失败，请稍后重试");
        }
    }

    /**
     * 新八大类用户端筛选
     * 根据筛选条件获取门店信息列表
     *
     * @param screeningOfEightMajorCategoriesVO 筛选条件VO对象
     * @return R<IPage < StoreInfo>> 分页的门店信息列表
     */
    @ApiOperation("新八大类用户端筛选")
    @PostMapping(value = "getScreeningNew")
    public R<IPage<StoreInfoVo>> getScreeningNew(@RequestBody ScreeningOfEightMajorCategoriesVO screeningOfEightMajorCategoriesVO) {
        // 参数校验
        if (screeningOfEightMajorCategoriesVO == null) {
            return R.fail("筛选参数不能为空");
        }
        // 记录请求日志
        log.info("新八大类用户端筛选请求 - 参数: screeningId={}, lon={}, lat={}, distance={}, flag={}, pageNum={}, pageSize={}", screeningOfEightMajorCategoriesVO.getScreeningId(), screeningOfEightMajorCategoriesVO.getLon(), screeningOfEightMajorCategoriesVO.getLat(), screeningOfEightMajorCategoriesVO.getDistance(), screeningOfEightMajorCategoriesVO.getFlag(), screeningOfEightMajorCategoriesVO.getPageNum(), screeningOfEightMajorCategoriesVO.getPageSize());
        try {
            // 调用服务层获取筛选结果
            IPage<StoreInfoVo> result = storeBusinessService.getScreeningNew(screeningOfEightMajorCategoriesVO);
            // 记录响应日志
            log.info("新八大类用户端筛选响应 - 总记录数: {}, 当前页: {}, 页大小: {}", result.getTotal(), result.getCurrent(), result.getSize());

            return R.data(result);
        } catch (IllegalArgumentException e) {
            log.warn("新八大类用户端筛选参数错误: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("新八大类用户端筛选异常", e);
            return R.data(null);
            //return R.fail("筛选失败，请稍后重试");
        }
    }


    /**
     * 八大类用户端经营类型筛选
     *
     * @param businessTypesNames 经营类型名称，多个类型用逗号分隔
     * @return R<List < StoreInfo>> 筛选结果
     */
    @ApiOperation("八大类用户端经营类型筛选")
    @ApiOperationSupport(order = 13)
    @ApiImplicitParams({@ApiImplicitParam(name = "businessTypesNames", value = "经营类型名称，多个类型用逗号分隔", dataType = "String", paramType = "query")})
    @GetMapping(value = "getBusinessTypesName")
    public R<List<StoreInfo>> getBusinessTypesName(@RequestParam(value = "businessTypesNames", required = false) String businessTypesNames) {
        log.info("StoreInfoController.getBusinessTypesName?businessTypesNames={}", businessTypesNames);
        try {
            List<StoreInfo> result = storeBusinessService.getBusinessTypesName(businessTypesNames);
            return R.data(result);
        } catch (Exception e) {
            log.error("八大类用户端经营类型筛选失败", e);
            return R.fail("筛选失败：" + e.getMessage());
        }
    }

    /**
     * web-查询店铺信息根据门店电话
     *
     * @param storeTel 门店电话
     * @return R
     */
    @ApiOperation("web-查询店铺信息根据门店电话")
    @ApiOperationSupport(order = 14)
    @GetMapping("/getStoreInfoByStoreTel")
    public R<List<StoreInfo>> getStoreInfoByCreateUser(@RequestParam(value = "storeTel") String storeTel) {
        log.info("StoreInfoController.getStoreInfoByStoreTel?storeTel={}", storeTel);
        return R.data(storeBusinessService.getStoreInfoByStoreTel(storeTel));
    }

    /**
     * 商家端注销店铺效验
     *
     * @param id 门店id
     */
    @ApiOperation("商家端注销店铺效验")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "int", paramType = "query", required = true)})
    @GetMapping("/storeInfoVerification")
    public R<Map<String, String>> storeInfoVerification(int id) {
        log.info("StoreInfoController.storeInfoVerification?id={}", id);
        return R.data(storeBusinessService.storeInfoVerification(id));
    }

    /**
     * 手动删除店铺
     */
    @ApiOperation("手动删除店铺")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "int", paramType = "query", required = true)})
    @GetMapping("/deleteManualStoreInfo")
    public R<StoreUserVo> deleteManualStoreInfo(int id) {
        log.info("StoreUserController.deleteManualStoreInfo?id={}", id);
        storeBusinessService.deleteManualStoreInfo(id);
        return R.success("删除成功");
    }

    @ApiOperation(value = "门店装修-详细信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "Long", paramType = "query", required = true)})
    @GetMapping("/getDecorationDetail")
    public R<StoreMainInfoVo> getDecorationDetail(Integer id) {
        log.info("StoreInfoController.getDecorationDetail?id={}", id);
        return R.data(storeBusinessService.getDecorationDetail(id));
    }

    @ApiOperation(value = "门店装修-门店营业时间")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "Long", paramType = "query", required = true)})
    @GetMapping("/getStoreInfoBusinessHours")
    public R<List<StoreBusinessInfo>> getStoreInfoBusinessHours(Integer id) {
        log.info("StoreInfoController.getStoreInfoBusinessHours?id={}", id);
        return R.data(storeBusinessService.getStoreInfoBusinessHours(id));
    }

    @ApiOperation(value = "门店装修-续签合同")
    @PostMapping("/uploadRenewalContract")
    public R<String> uploadRenewalContract(@RequestBody List<StoreImg> storeImgList) {
        log.info("StoreInfoController.uploadRenewalContract?storeImgList={}", storeImgList);
        int num = storeBusinessService.uploadRenewalContract(storeImgList);
        if (num <= 0) {
            return R.fail("续签合同图片添加失败");
        }
        return R.success("续签合同图片添加成功");
    }

    @ApiOperation(value = "门店装修-续签合同状态及合同图片")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "int", paramType = "query", required = true)})
    @GetMapping("/getStoreContractStatus")
    public R<Map<String, Object>> getStoreContractStatus(int id) {
        log.info("StoreInfoController.getStoreContractStatus?id={}", id);
        return R.data(storeBusinessService.getStoreContractStatus(id));
    }

    @ApiOperation(value = "门店装修-审核续签合同状态")
    @PostMapping("/updateContractImageStatus")
    public R<String> updateContractImageStatus(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.updateContractImageStatus?storeInfoDto={}", storeInfoDto);
        StoreInfo storeInfo = storeBusinessService.getOne(new LambdaQueryWrapper<StoreInfo>().eq(StoreInfo::getId, storeInfoDto.getId()));
        if (storeInfo != null) {
            if (storeInfoDto.getRenewContractStatus() == 3) {
                storeInfo.setContractReason(storeInfoDto.getContractReason());
                storeInfo.setRenewContractStatus(storeInfoDto.getRenewContractStatus());
                boolean flag = storeBusinessService.updateById(storeInfo);
                if (flag) {
                    return R.success("拒绝审核成功");
                } else {
                    return R.fail("拒绝审核失败");
                }
            }
            storeInfo.setRenewContractStatus(storeInfoDto.getRenewContractStatus());
            storeInfo.setContractReason(storeInfoDto.getContractReason());
            boolean flag = storeBusinessService.updateById(storeInfo);
            if (flag) {
                //审核通过后删除原店铺合同 续签合同类型变为合同
                int num = storeBusinessService.conversionContract(storeInfoDto.getId());
                if (num > 0) {
                    return R.success("审核通过成功");
                } else {
                    return R.fail("审核通过失败");
                }
            }
        }
        return R.fail("审核失败 店铺不存在");
    }

    @ApiOperation(value = "门店装修-食品经营许可证")
    @PostMapping("/uploadfoodLicence")
    public R<String> uploadfoodLicence(@RequestBody StoreImg storeImg) {
        log.info("StoreInfoController.uploadfoodLicence?storeImg={}", storeImg);
        int num = storeBusinessService.uploadfoodLicence(storeImg);
        if (num > 0) {
            WebAudit webAudit = new WebAudit();
            webAudit.setStoreInfoId(storeImg.getStoreId().toString());
            webAudit.setType("7");
            webAudit.setStatus("0");
            webAudit.setContent("经营许可证");
            webAuditMapper.insert(webAudit);
            return R.success("食品经营许可证图片添加成功");
        }
        return R.fail("食品经营许可证图片添加失败");
    }

    @ApiOperation(value = "门店装修-食品经营许可证状态及合同图片")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "门店id", dataType = "int", paramType = "query", required = true)})
    @GetMapping("/getStoreFoodLicenceStatus")
    public R<Map<String, Object>> getStoreFoodLicenceStatus(int id) {
        log.info("StoreInfoController.getStoreFoodLicenceStatus?id={}", id);
        return R.data(storeBusinessService.getStoreFoodLicenceStatus(id));
    }

    @ApiOperation(value = "门店装修-审核食品经营许可证状态")
    @PostMapping("/updatefoodLicenceImageStatus")
    public R<String> updatefoodLicenceImageStatus(@RequestBody StoreInfoDto storeInfoDto) {
        log.info("StoreInfoController.updatefoodLicenceImageStatus?storeInfoDto={}", storeInfoDto);
        StoreInfo storeInfo = storeBusinessService.getOne(new LambdaQueryWrapper<StoreInfo>().eq(StoreInfo::getId, storeInfoDto.getId()));
        if (storeInfo != null) {
            if (storeInfoDto.getFoodLicenceStatus() == 3) {
                storeInfo.setFoodLicenceReason(storeInfoDto.getFoodLicenceReason());
                storeInfo.setFoodLicenceStatus(storeInfoDto.getFoodLicenceStatus());
                boolean flag = storeBusinessService.updateById(storeInfo);
                if (flag) {
                    // 审核拒绝时修改提交记录
                    LambdaUpdateWrapper<StoreLicenseHistory> wrapper = new LambdaUpdateWrapper<>();
                    wrapper.eq(StoreLicenseHistory::getStoreId, storeInfo.getId());
                    wrapper.eq(StoreLicenseHistory::getLicenseStatus, 2);
                    wrapper.set(StoreLicenseHistory::getLicenseExecuteStatus, 3);
                    wrapper.set(StoreLicenseHistory::getDeleteFlag, 1);
                    licenseHistoryMapper.update(null, wrapper);

                    //待审核状态变为已审核
                    WebAudit webAudit = webAuditMapper.selectOne(new LambdaQueryWrapper<WebAudit>().eq(WebAudit::getStoreInfoId, storeInfo.getId()).eq(WebAudit::getDeleteFlag, 0).eq(WebAudit::getType, "7"));
                    if (webAudit != null) {
                        webAudit.setStatus("1");
                        webAuditMapper.updateById(webAudit);
                    }
                    return R.success("拒绝审核成功");
                } else {
                    return R.fail("拒绝审核失败");
                }
            }
            storeInfo.setFoodLicenceReason(storeInfoDto.getFoodLicenceReason());
            storeInfo.setFoodLicenceStatus(storeInfoDto.getFoodLicenceStatus());
            boolean flag = storeBusinessService.updateById(storeInfo);
            if (flag) {
                int num = storeBusinessService.foodLicenceType(storeInfoDto.getId());
                if (num > 0) {
                    //待审核状态变为已审核
                    WebAudit webAudit = webAuditMapper.selectOne(new LambdaQueryWrapper<WebAudit>().eq(WebAudit::getStoreInfoId, storeInfo.getId()).eq(WebAudit::getDeleteFlag, 0).eq(WebAudit::getType, "7"));
                    if (webAudit != null) {
                        webAudit.setStatus("1");
                        webAuditMapper.updateById(webAudit);
                    }
                }
                return R.success("审核通过成功");
            } else {
                return R.fail("审核失败");
            }
        }
        return R.fail("审核失败 店铺不存在");
    }

    @ApiOperation(value = "AI服务-门店评价标签")
    @GetMapping("/getStoreEvaluateTags")
    @ApiImplicitParams({@ApiImplicitParam(name = "storeId", value = "门店id", dataType = "int", paramType = "query")})
    public R<List<TagsMainVo>> getStoreEvaluateTags(int storeId) {
        log.info("StoreInfoController.getStoreEvaluateTags?storeId={}", storeId);
        List<TagsMainVo> voList = tagsMainMapper.getStoreEvaluateTags(storeId);
        return R.data(voList);
    }

    @ApiOperation(value = "AI服务-门店趣味信息")
    @GetMapping("/getStoreInterestInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "int", paramType = "query")
    })
    public R<List<StoreCommentSummaryInterest>> getStoreInterestInfo(int storeId) {
        log.info("StoreInfoController.getStoreInterestInfo?storeId={}", storeId);
        List<StoreCommentSummaryInterest> list = storeCommentSummaryInterestMapper.selectList(new LambdaQueryWrapper<StoreCommentSummaryInterest>().eq(StoreCommentSummaryInterest :: getStoreId, storeId));
        return R.data(list);
    }



    @ApiOperation("删除标签经营类型关系")
    @ApiOperationSupport(order = 7)
    @PostMapping("/setStoreUserInfo")
    public R<Boolean> setStoreUserInfo(@RequestBody StoreInfoVo storeInfo) {
        log.info("StoreUserController.setStoreUserInfo?storeInfo={}", storeInfo);

        // 查询店铺图片信息
        LambdaQueryWrapper<StoreImg> queryWrapper = new LambdaQueryWrapper<StoreImg>().eq(StoreImg::getImgType, 10).eq(StoreImg::getStoreId, storeInfo.getId());
        StoreImg storeImg = storeImgMapper.selectOne(queryWrapper);

        // 如果查询到店铺图片信息，则更新图片 URL
        if (storeImg != null) {
            storeImg.setImgUrl(storeInfo.getImgUrl());
            int imgUpdateResult = storeImgMapper.updateById(storeImg);
            if (imgUpdateResult == 0) {
                return R.fail("修改失败");
            }
        } else {
            StoreImg storeImg1 = new StoreImg();
            storeImg1.setStoreId(storeInfo.getId());
            storeImg1.setImgType(10);
            storeImg1.setImgUrl(storeInfo.getImgUrl());
            storeImg1.setImgSort(0);
            int insert = storeImgMapper.insert(storeImg1);
            if (insert == 0) {
                return R.fail("添加失败");
            }
        }

        // 更新店铺信息
        boolean infoUpdateResult = storeBusinessService.updateById(storeInfo);
        if (!infoUpdateResult) {
            return R.fail("修改失败");
        }

        // 所有更新操作成功，返回成功信息
        return R.success("修改成功");

    }

    /**
     * web端查询用户列表
     */
    @ApiOperation("创建标签经营类型关系")
    @ApiOperationSupport(order = 7)
    @GetMapping("/getStoreUserList")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "int", paramType = "query", required = true), @ApiImplicitParam(name = "storeName", value = "门店名称", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeContact", value = "门店联系人", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storePhone", value = "门店电话", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "storeType", value = "门店类型", dataType = "String", paramType = "query")})
    public R<IPage<StoreUserVo>> getStoreUserList(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize, @RequestParam(required = false) String id, @RequestParam(required = false) String phone, @RequestParam(required = false) Integer status) {
        log.info("StoreInfoController.getStoreUserList?pageNum={},pageSize={},id={},phone={},status={}", pageNum, pageSize, id, phone, status);
        R<IPage<StoreUserVo>> storeUserVoR = storeBusinessService.getStoreUserList(pageNum, pageSize, id, phone, status);
        return storeUserVoR;
    }

    /**
     * 校验商户端账号是否禁用
     *
     * @param accountId
     * @return
     */
    @ApiOperation("获取经营类型标签信息")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({@ApiImplicitParam(name = "accountId", value = "账号id", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/checkAccount")
    private R<StoreUserVo> checkAccount(Integer accountId) {
        return storeUserMapper.selectById(accountId).getStatus() != 1 ? R.success("账号正常") : R.fail("账号禁用");
    }

    @ApiOperation("获取标签经营类型关系")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true), @ApiImplicitParam(name = "type", value = "修改类型 (pass:密码状态改为1, face:人脸状态改为2)", dataType = "String", paramType = "query", required = true)})
    @GetMapping("/updateUserStatus")
    public R<StoreUser> updateUserStatus(String phone, String type) {
        log.info("StoreUserController.updateUserStatus?phone={}&type={}", phone, type);
        if (storeBusinessService.updateUserStatus(phone, type)) {
            return R.success("修改成功");
        }
        return R.fail("修改失败");
    }

}
