package com.liquidnet.client.admin.web.controller.zhengzai.kylin;

import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.annotation.Log;
import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.core.page.TableDataInfo;
import com.liquidnet.client.admin.common.enums.BusinessType;
import com.liquidnet.service.kylin.dao.KylinArtistAssociationStatusDto;
import com.liquidnet.service.kylin.dao.KylinArtistDao;
import com.liquidnet.service.kylin.dao.KylinArtistOperationLogDao;
import com.liquidnet.service.kylin.dao.KylinArtistPerformanceDao;
import com.liquidnet.service.kylin.dto.param.ArtistParam;
import com.liquidnet.service.kylin.dto.param.ArtistSearchParam;
import com.liquidnet.service.kylin.dto.vo.ArtistVo;
import com.liquidnet.service.kylin.service.admin.IKylinArtistOperationLogService;
import com.liquidnet.service.kylin.service.admin.IKylinArtistPerformanceService;
import com.liquidnet.service.kylin.service.admin.IKylinArtistService;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 艺人管理 后端管理控制器
 * </p>
 *
 * @author liquidnet
 * @since 2026-02-04
 */
@Api(tags = "艺人管理")
@Controller
@RequestMapping("/kylin/artist")
public class KylinArtistController extends BaseController {

    private final String prefix = "zhengzai/kylin/artist";

    @Value("${liquidnet.client.admin.platformUrl}")
    private String platformUrl;

    @Autowired
    private IKylinArtistService kylinArtistService;

    @Autowired
    private IKylinArtistOperationLogService operationLogService;

    @Autowired
    private IKylinArtistPerformanceService artistPerformanceService;


    @GetMapping("/create")
    @RequiresPermissions("kylin:artist:create")
    public String create(ModelMap mmap) {
        mmap.put("platformUrl", platformUrl);
        return prefix + "/create";
    }

    @GetMapping("/update/{artistId}")
    @RequiresPermissions("kylin:artist:update")
    public String update(@PathVariable("artistId") String artistId, ModelMap mmap) {
        ArtistVo result = kylinArtistService.detail(artistId);
        mmap.put("ArtistVo", result);
        mmap.put("platformUrl", platformUrl);
        return prefix + "/update";
    }

    @RequiresPermissions("kylin:artist:list")
    @GetMapping()
    public String artists() {
        return prefix + "/artists";
    }

    @RequiresPermissions("kylin:artist:detail")
    @GetMapping("/detail/{artistId}")
    public String detail(@PathVariable("artistId") String artistId, ModelMap mmap) {
        ArtistVo result = kylinArtistService.detail(artistId);
        mmap.put("ArtistVo", result);
        return prefix + "/detail";
    }

    @RequiresPermissions("kylin:artist:list")
    @PostMapping("list")
    @ResponseBody
    public TableDataInfo artistList(ArtistSearchParam param) {
        PageInfo<KylinArtistDao> result = kylinArtistService.artistList(param);
        return getDataTable(result.getList());
    }

    @Log(title = "创建艺人", businessType = BusinessType.INSERT)
    @RequiresPermissions("kylin:artist:create")
    @PostMapping("create")
    @ResponseBody
    public AjaxResult createSave(ArtistParam param, String albumImagesJson) {
        // 校验艺人名称是否已存在
        Boolean exists = kylinArtistService.checkArtistNameExists(param.getArtistName(), null);
        if (exists) {
            return error("艺人名称已存在，不可重复创建");
        }

        // 解析相册图片JSON数组
        if (albumImagesJson != null && !albumImagesJson.isEmpty() && !albumImagesJson.equals("[]")) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                List<String> albumImages = mapper.readValue(albumImagesJson,
                        mapper.getTypeFactory().constructCollectionType(List.class, String.class));
                param.setAlbumImages(albumImages);
            } catch (Exception e) {
                return error("相册图片数据格式错误");
            }
        }

        Boolean res = kylinArtistService.create(param);
        if (res) {
            return success();
        } else {
            return error("添加艺人失败");
        }
    }


    @Log(title = "修改艺人", businessType = BusinessType.UPDATE)
    @RequiresPermissions("kylin:artist:update")
    @PostMapping("update")
    @ResponseBody
    public AjaxResult updateSave(ArtistParam param, String albumImagesJson) {
        // 校验艺人名称是否已被其他艺人使用
        Boolean exists = kylinArtistService.checkArtistNameExists(param.getArtistName(), param.getArtistId());
        if (exists) {
            return error("艺人名称已被其他艺人使用");
        }

        // 解析相册图片JSON数组
        if (albumImagesJson != null && !albumImagesJson.isEmpty() && !albumImagesJson.equals("[]")) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                List<String> albumImages = mapper.readValue(albumImagesJson,
                        mapper.getTypeFactory().constructCollectionType(List.class, String.class));
                param.setAlbumImages(albumImages);
            } catch (Exception e) {
                return error("相册图片数据格式错误");
            }
        }

        Boolean res = kylinArtistService.update(param);
        if (res) {
            return success();
        } else {
            return error("修改艺人失败");
        }
    }


    @Log(title = "删除艺人", businessType = BusinessType.DELETE)
    @RequiresPermissions("kylin:artist:delete")
    @PostMapping("delete")
    @ResponseBody
    public AjaxResult delete(ArtistParam param) {
        List<String> artistIds = param.getIds();
        Boolean result = kylinArtistService.delete(artistIds);
        if (result) {
            return success("删除成功");
        } else {
            return error("删除失败");
        }
    }

    /**
     * 检查艺人名称是否存在
     */
    @PostMapping("checkName")
    @ResponseBody
    public AjaxResult checkArtistName(String artistName, String artistId) {
        Boolean exists = kylinArtistService.checkArtistNameExists(artistName, artistId);
        if (exists) {
            return error("艺人名称已存在");
        }
        return success();
    }

    /**
     * 艺人操作记录页面
     */
    @RequiresPermissions("kylin:artist:detail")
    @GetMapping("/operationLog/{artistId}")
    public String operationLog(@PathVariable("artistId") String artistId, ModelMap mmap) {
        // 获取艺人基本信息
        ArtistVo artistVo = kylinArtistService.detail(artistId);
        mmap.put("artistId", artistId);
        mmap.put("artistName", artistVo != null ? artistVo.getArtistName() : "");
        return prefix + "/operationLog";
    }

    /**
     * 获取艺人操作记录列表
     */
    @RequiresPermissions("kylin:artist:detail")
    @PostMapping("/operationLogList")
    @ResponseBody
    public TableDataInfo operationLogList(String artistId, Integer pageNum, Integer pageSize) {
        PageInfo<KylinArtistOperationLogDao> result =
                operationLogService.getOperationLogs(artistId, pageNum, pageSize);
        return getDataTable(result.getList());
    }

    /**
     * 获取指定场次的艺人阵容
     */
    @GetMapping("/getSessionArtists")
    @ResponseBody
    public AjaxResult getSessionArtists(String performancesId, String timesId) {
        try {
            if (performancesId == null || timesId == null) {
                return error("参数不能为空");
            }
            List<KylinArtistPerformanceDao> artists = artistPerformanceService.getSessionArtists(performancesId, timesId);
            return AjaxResult.success(artists);
        } catch (Exception e) {
            return error("获取艺人阵容失败: " + e.getMessage());
        }
    }

    /**
     * 更新艺人排序
     */
    @Log(title = "更新演出艺人排序", businessType = BusinessType.UPDATE)
    @PostMapping("/updateArtistOrder")
    @ResponseBody
    public AjaxResult updateArtistOrder(@RequestBody Map<String, Object> params) {
        try {
            String performancesId = (String) params.get("performancesId");
            String timesId = (String) params.get("timesId");
            List<Map<String, Object>> orderData = (List<Map<String, Object>>) params.get("orderData");

            if (orderData == null || orderData.isEmpty()) {
                return error("排序数据不能为空");
            }
            boolean updateResult = artistPerformanceService.updateArtistOrder(performancesId, orderData);
            return success("排序更新成功");
        } catch (Exception e) {
            return error("更新排序失败: " + e.getMessage());
        }
    }

    /**
     * 删除演出艺人关联
     */
    @Log(title = "删除演出艺人", businessType = BusinessType.DELETE)
    @PostMapping("/deletePerformanceArtist")
    @ResponseBody
    public AjaxResult deletePerformanceArtist(Long mid, String performancesId, String timesId) {
        try {
            if (mid == null) {
                return error("参数错误");
            }
            int result = artistPerformanceService.deletePerformanceArtist(mid, performancesId);
            if (result > 0) {
                return success("删除成功");
            } else {
                return error("删除失败");
            }
        } catch (Exception e) {
            return error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有艺人
     */
    @GetMapping("/getAllArtists")
    @ResponseBody
    public AjaxResult getAllArtists(String performancesId, String timesId, String keyword) {
        try {
            List<KylinArtistAssociationStatusDto> resultList = artistPerformanceService.getAllArtists(performancesId, timesId, keyword);
            return AjaxResult.success(resultList);
        } catch (Exception e) {
            return error("获取艺人列表失败: " + e.getMessage());
        }
    }

    /**
     * 修改艺人关联
     *
     * @param payload
     * @return
     */
    @PostMapping("/updateArtistAssociations")
    @ResponseBody
    public AjaxResult updateArtistAssociations(@RequestBody Map<String, Object> payload) {
        try {
            String performancesId = (String) payload.get("performancesId");
            String timesId = (String) payload.get("timesId");
            List<Map<String, Object>> artistOrders = (List<Map<String, Object>>) payload.get("artistOrders");
            boolean result = artistPerformanceService.updateArtistAssociations(performancesId, timesId, artistOrders);
            return success("关联更新成功");
        } catch (Exception e) {
            logger.error("error", e);
            return error("更新关联失败: " + e.getMessage());
        }
    }

}
