package com.starry.admin.modules.shop.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.clerk.module.entity.PlayClerkLevelInfoEntity;
import com.starry.admin.modules.clerk.service.IPlayClerkLevelInfoService;
import com.starry.admin.modules.shop.module.entity.PlayCommodityAndLevelInfoEntity;
import com.starry.admin.modules.shop.module.entity.PlayCommodityInfoEntity;
import com.starry.admin.modules.shop.module.vo.PlayCommodityInfoAddVo;
import com.starry.admin.modules.shop.module.vo.PlayCommodityInfoReturnVo;
import com.starry.admin.modules.shop.service.IPlayCommodityAndLevelInfoService;
import com.starry.admin.modules.shop.service.IPlayCommodityInfoService;
import com.starry.common.annotation.Log;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import com.starry.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * 服务项目Controller
 *
 * @author admin
 * @since 2024-03-31
 */
@Api(tags = "服务项目管理", description = "服务项目信息管理相关接口，包括查询、新增、修改和删除等操作")
@RestController
@RequestMapping("/shop/commodity")
public class PlayCommodityInfoController {
    @Resource
    private IPlayCommodityInfoService playCommodityInfoService;

    @Resource
    private IPlayClerkLevelInfoService playClerkLevelInfoService;

    @Resource
    private IPlayCommodityAndLevelInfoService playCommodityAndLevelInfoService;

    @ApiOperation(value = "获取表头信息", notes = "获取店员等级表头信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @GetMapping("/getTableName")
    public R getTableName() {
        List<Map<String, String>> result = new ArrayList<>();
        List<PlayClerkLevelInfoEntity> levelInfoEntities = playClerkLevelInfoService.selectAll();
        for (PlayClerkLevelInfoEntity levelInfoEntity : levelInfoEntities) {
            HashMap<String, String> item = new HashMap<>();
            item.put("prop", levelInfoEntity.getId());
            item.put("name", levelInfoEntity.getName());
            result.add(item);
        }
        return R.ok(result);
    }

    /**
     * 查询服务项目类型
     */
    @ApiOperation(value = "查询所有服务项目", notes = "查询所有服务项目类型及其子项目")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @GetMapping("/listAll")
    public R queryCommodityType() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<PlayCommodityInfoEntity> list = playCommodityInfoService.selectByType();
        for (PlayCommodityInfoEntity entity : list) {
            List<Map<String, Object>> itemCommodityInfo = new ArrayList<>();
            Map<String, Object> map = BeanUtil.beanToMap(entity);
            List<PlayCommodityInfoReturnVo> commodityInfoEntities = ConvertUtil.entityToVoList(
                    playCommodityInfoService.selectByPId(entity.getId()), PlayCommodityInfoReturnVo.class);
            for (PlayCommodityInfoReturnVo commodityInfoEntity : commodityInfoEntities) {
                Map<String, Object> item = BeanUtil.beanToMap(commodityInfoEntity);
                for (PlayClerkLevelInfoEntity playClerkLevelInfoEntity : playClerkLevelInfoService.selectAll()) {
                    PlayCommodityAndLevelInfoEntity entity1 = playCommodityAndLevelInfoService
                            .queryById(commodityInfoEntity.getId(), playClerkLevelInfoEntity.getId());
                    item.put(playClerkLevelInfoEntity.getId(), entity1 == null ? "未设置价格" : entity1.getPrice());
                }
                itemCommodityInfo.add(item);
            }
            map.put("children", itemCommodityInfo);
            result.add(map);
        }
        return R.ok(result);
    }

    /**
     * 修改服务项目类型
     */
    @ApiOperation(value = "更新服务项目价格", notes = "根据不同店员等级修改服务项目价格")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "更新失败，包含详细错误信息")})
    @PostMapping("/updateInfo")
    public R updateInfo(@ApiParam(value = "价格信息JSON", required = true) @RequestBody String s) {
        JSONObject jsonObject = JSON.parseObject(s);
        if (!jsonObject.containsKey("id")) {
            throw new CustomException("请求参数错误,id不能为空");
        }
        System.out.println(s);
        for (PlayClerkLevelInfoEntity playClerkLevelInfoEntity : playClerkLevelInfoService.selectAll()) {
            if (!jsonObject.containsKey(playClerkLevelInfoEntity.getId())) {
                throw new CustomException("请求参数错误");
            }
            String rawPrice = jsonObject.getString(playClerkLevelInfoEntity.getId());
            if (rawPrice == null || rawPrice.trim().isEmpty()) {
                continue;
            }
            double price = 0.0;
            try {
                price = Double.parseDouble(rawPrice);
            } catch (RuntimeException e) {
                throw new CustomException("请求参数错误,价格格式为空");
            }
            PlayCommodityAndLevelInfoEntity entity = playCommodityAndLevelInfoService
                    .queryById(jsonObject.getString("id"), playClerkLevelInfoEntity.getId());
            if (entity == null) {
                entity = new PlayCommodityAndLevelInfoEntity();
                entity.setCommodityId(jsonObject.getString("id"));
                entity.setLevelId(playClerkLevelInfoEntity.getId());
            }
            entity.setPrice(new BigDecimal(price));
            this.playCommodityAndLevelInfoService.saveOrUpdate(entity);
        }
        return R.ok("成功");
    }

    /**
     * 获取服务项目详细信息
     */
    @ApiOperation(value = "获取服务项目详情", notes = "根据ID获取服务项目详细信息")
    @ApiImplicitParam(name = "id", value = "服务项目ID", required = true, paramType = "path", dataType = "String", example = "1")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = PlayCommodityInfoEntity.class)})
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        return R.ok(playCommodityInfoService.selectPlayCommodityInfoById(id));
    }

    /**
     * 新增服务项目
     */
    @ApiOperation(value = "新增服务项目", notes = "新增服务项目信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "添加失败，包含详细错误信息")})
    @Log(title = "服务项目", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R create(@ApiParam(value = "服务项目信息", required = true) @RequestBody PlayCommodityInfoAddVo vo) {
        PlayCommodityInfoEntity entity = ConvertUtil.entityToVo(vo, PlayCommodityInfoEntity.class);
        boolean success = playCommodityInfoService.create(entity);
        if (success) {
            return R.ok();
        }
        return R.error("添加失败");
    }

    /**
     * 修改服务项目
     */
    @ApiOperation(value = "修改服务项目", notes = "修改服务项目信息")
    @ApiImplicitParam(name = "id", value = "服务项目ID", required = true, paramType = "path", dataType = "String", example = "1")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "修改失败，包含详细错误信息")})
    @Log(title = "服务项目", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/{id}")
    public R update(@PathVariable String id,
            @ApiParam(value = "服务项目信息", required = true) @RequestBody PlayCommodityInfoEntity playCommodityInfo) {
        playCommodityInfo.setId(id);
        boolean success = playCommodityInfoService.update(playCommodityInfo);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 删除服务项目
     */
    @ApiOperation(value = "删除服务项目", notes = "根据ID批量删除服务项目信息")
    @ApiImplicitParam(name = "ids", value = "服务项目ID数组", required = true, paramType = "path", dataType = "String[]", example = "1,2,3")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @Log(title = "服务项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.ok(playCommodityInfoService.deletePlayCommodityInfoByIds(ids));
    }
}
