package com.mcwl.web.controller.resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.mcwl.common.core.controller.BaseController;
import com.mcwl.common.core.domain.AjaxResult;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.myInvitation.domain.Consume;
import com.mcwl.myInvitation.service.ConsumeService;
import com.mcwl.pay.domain.ModelPurchaseRecord;
import com.mcwl.pay.mapper.ModelPurchaseRecordMapper;
import com.mcwl.resource.domain.ModelProduct;
import com.mcwl.resource.domain.ModelVersion;
import com.mcwl.resource.domain.dto.ModelImagePageRes;
import com.mcwl.resource.domain.request.RequestModel;
import com.mcwl.resource.domain.response.ResponseModelProduct;
import com.mcwl.resource.domain.vo.PageVo;
import com.mcwl.resource.mapper.ModelVersionMapper;
import com.mcwl.resource.service.ModelService;
import com.mcwl.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 模型
 *
 * @Author：ChenYan
 * @Project：McWl
 * @Package：com.mcwl.web.controller.resource
 * @Filename：MallProductController
 * @Description 商品
 * @Date：2024/12/31 10:48
 */
@Api(tags = "模型")
@RestController
@RequestMapping("/model")
public class MallProductController extends BaseController {

    @Autowired
    private ModelPurchaseRecordMapper modelPurchaseRecordMapper;

    @Autowired
    private ModelService modelService;

    @Autowired
    private ModelVersionMapper modelVersionMapper;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private ConsumeService consumeService;


    /**
     * 模型列表
     */
    @ApiOperation(value = "模型列表")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody ModelImagePageRes imagePageRes) {

        return modelService.listByPage(imagePageRes);
    }


    @ApiOperation(value = "模型详情")
    @GetMapping("finbyid")
    public AjaxResult finbyid(@Valid @NotNull(message = "模型id不能为空") @RequestParam Long id) {

        RequestModel requestModel = new RequestModel();

        ModelProduct modelVersion1 = modelService.getById(id);
        Set<Long> productIdSet = consumeService.lambdaQuery()
                .eq(Consume::getUserId, SecurityUtils.getUserId())
                .eq(Consume::getType, 0)
                .list()
                .parallelStream()
                .map(Consume::getProductId)
                .collect(Collectors.toSet());

        Optional.ofNullable(modelVersion1)
                .filter(m -> productIdSet.contains(m.getId()))
                .ifPresent(m -> m.setIsBuy(1));

        LambdaQueryWrapper<ModelVersion> modelVersionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        modelVersionLambdaQueryWrapper.eq(ModelVersion::getModelId, id);
        modelVersionLambdaQueryWrapper.eq(ModelVersion::getDelFlag, "0");
        List<ModelVersion> modelVersions = modelVersionMapper.selectList(modelVersionLambdaQueryWrapper);

        requestModel.setModelProduct(modelVersion1);
        requestModel.setModelVersionList(modelVersions);
        return AjaxResult.success(requestModel);
    }


    @ApiOperation(value = "添加模型")
    @PostMapping("/insert")
    public R<String> addupdateModel(@RequestBody RequestModel requestModel) {
        ModelProduct modelProduct = requestModel.getModelProduct();
        Long userId = SecurityUtils.getUserId();
        modelProduct.setUserId(userId);
        return modelService.addModel(requestModel);
    }

    @ApiOperation(value = "修改模型")
    @PostMapping("/update")
    public AjaxResult updateModel(@RequestBody RequestModel requestModel) {


//        for (ModelVersion modelVersion : requestModel.getModelVersionList()) {
//
//            //校验名字
//            ModelVersion modelVersion1 = modelVersionMapper.selectByFileName(modelVersion.getFileName());
//            if (modelVersion1 != null) {
//
//                return AjaxResult.error(HttpStatus.SHOW_ERROR_MSG,"文件名字重复");
//            }
//            //校验hash
//            ModelVersion modelVersion2 = modelVersionMapper.selectByHash(modelVersion.getFileHash());
//            if (modelVersion2 != null){
//
//                return AjaxResult.error(HttpStatus.SHOW_ERROR_MSG,"文件内容重复");
//            }
//        }

        ModelProduct modelProduct = requestModel.getModelProduct();

        Long userId = SecurityUtils.getUserId();
        modelProduct.setUserId(userId);
        modelService.updaModel(requestModel);

        return AjaxResult.success("修改成功");
    }


    @ApiOperation(value = "删除模型")
    @GetMapping("delete")
    public AjaxResult delete(@Valid @NotNull(message = "模型id不能为空") @RequestParam Long id) {
        modelService.removeById(id);
        return AjaxResult.success();
    }

    /**
     * 查询模型详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询模型详情")
    @GetMapping("/selectModelById")
    public R<ModelProduct> selectModelById(@Valid @NotNull(message = "模型id不能为空") @RequestParam Long id) {

        R<ModelProduct> modelProductR = modelService.selectModelById(id);
        ModelProduct data = modelProductR.getData();
        if (Objects.nonNull(data)) {
            Long userIdMax = SecurityUtils.getUserIdMax();
            if (userIdMax != 0){
                LambdaQueryWrapper<ModelPurchaseRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(ModelPurchaseRecord::getUserId, userIdMax)
                        .eq(ModelPurchaseRecord::getProductId, id)
                        .eq(ModelPurchaseRecord::getProductType, 0);
                ModelPurchaseRecord modelPurchaseRecord = modelPurchaseRecordMapper.selectOne(wrapper);
                data.setIsBuy(1);
                if (Objects.isNull(modelPurchaseRecord)) {
                    data.setIsBuy(0);
                }
            }
            data.setIsBuy(0);
            modelProductR.setData(data);
        }
        return modelProductR;
    }


    /**
     * 设置模型置顶状态
     *
     * @param id
     * @param isTop
     * @return
     */
    @ApiOperation(value = "设置模型置顶状态")
    @GetMapping("/{id}/top")
    public AjaxResult setModelTop(@PathVariable Long id, @RequestParam boolean isTop) {
        modelService.setModelTop(id, isTop);
        return AjaxResult.success();
    }


    /**
     * 获取置顶的模型列表
     *
     * @return
     */
    @ApiOperation(value = "获取置顶的模型列表")
    @GetMapping
    public R<List<ModelProduct>> fetchModelsSortedByTopStatus() {
        List<ModelProduct> models = modelService.fetchModelsSortedByTopStatus();
        return R.ok(models);
    }

    /**
     * 模型广场
     */
    @ApiOperation(value = "模型广场列表")
    @PostMapping("/modelSquare")
    public R modelSquare(@RequestBody PageVo pageVo) {
        PageInfo<ResponseModelProduct> modelProductPage = modelService.modelSquare(pageVo);
        return R.ok(modelProductPage);
    }

    /**
     * 校验模型名字是否唯一
     *
     * @param name
     * @return
     */
    @ApiOperation(value = "校验模型名字是否唯一")
    @GetMapping("/selectModelByName")
    public R selectModelByName(@RequestParam String name) {

        return modelService.selectModelByName(name);
    }

    @ApiOperation(value = "个人中心更改背景")
    @GetMapping("/updateBackgroundImg")
    public R updateBackgroundImg(@RequestParam Long id, String path) {

        sysUserService.updateBackgroundImg(id, path);

        return R.ok();
    }

}
