package com.yonge.cooleshow.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.dayaedu.cbs.common.enums.music.EMusicAvailableType;
import com.dayaedu.cbs.openfeign.client.MusicFeignClientService;
import com.dayaedu.cbs.openfeign.properties.OpenFeignClientConfigProperties;
import com.dayaedu.cbs.openfeign.service.CbsMusicSheetService;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetApplicationExtendClientWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetCategoryWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetExtendWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.microsvc.toolkit.common.webportal.exception.BizException;
import com.yonge.cooleshow.biz.dal.dto.PageUtil;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.wrapper.MusicSheetWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.admin:}/musicSheetApplicationExtend")
@Api(tags = "曲目应用拓展表")
public class MusicSheetApplicationExtendController {

    @Resource
    private MusicFeignClientService musicFeignClientService;


    @Resource
    private CbsMusicSheetService cbsMusicSheetService;

    @Resource
    private OpenFeignClientConfigProperties openFeignClientConfigProperties;

    @Resource
    private MusicSheetService musicSheetService;

    @PreAuthorize("@pcs.hasPermissions('musicSheetApplicationExtend/pageByApplication')")
    @PostMapping({"/pageByApplication"})
    public R<PageInfo<CbsMusicSheetWrapper.MusicSheetApplication>> musicSheetPageByApplication(@RequestBody CbsMusicSheetWrapper.MusicSheetApplicationQuery var1) {
        var1.setApplicationId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
        try {
            PageInfo<CbsMusicSheetWrapper.MusicSheetApplication> feignedData = this.musicFeignClientService.musicSheetPageByApplication(var1).feignData();
            List<CbsMusicSheetWrapper.MusicSheetApplication> rows = feignedData.getRows();
            if (CollectionUtils.isEmpty(rows)) {
                return R.from(feignedData);
            }
            List<Long> cbsMusicIds = rows.stream().map(CbsMusicSheetWrapper.MusicSheetApplication::getId).collect(Collectors.toList());
            List<MusicSheet> musicSheetList = musicSheetService.lambdaQuery().in(MusicSheet::getCbsMusicSheetId, cbsMusicIds).eq(MusicSheet::getDelFlag, false).list();

            Map<Long, MusicSheet> map = musicSheetList.stream().collect(Collectors.toMap(MusicSheet::getCbsMusicSheetId, o -> o, (o1, o2) -> o1));

            for (CbsMusicSheetWrapper.MusicSheetApplication row : rows) {
                MusicSheet musicSheet = map.get(row.getId());
                if (Objects.nonNull(musicSheet)) {
                    row.setBizId(musicSheet.getId());
                }
            }
            feignedData.setRows(rows);
            return R.from(feignedData);
        } catch (Exception e) {
            log.error("查询曲目应用拓展表异常", e);
            if (e instanceof BizException) {
                throw e;
            }
            throw BizException.from("内容平台服务异常");
        }
    }


    @PreAuthorize("@pcs.hasPermissions('musicSheetApplicationExtend/page')")
    @PostMapping({"/page"})
    public R<PageInfo> musicSheetPage(@RequestBody CbsMusicSheetWrapper.MusicSheetQuery var1) {
        var1.setAddAppId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
        try {
            PageInfo<CbsMusicSheetWrapper.MusicSheet> info = this.musicFeignClientService.musicSheetPage(var1).feignData();
            if (CollectionUtils.isNotEmpty(info.getRows())) {
                List<MusicSheetWrapper.CbsMusicSheet> result = new ArrayList<>();
                for (CbsMusicSheetWrapper.MusicSheet row : info.getRows()) {
                    MusicSheetWrapper.CbsMusicSheet cbsMusicSheet = JSONObject.parseObject(JSONObject.toJSONString(row), MusicSheetWrapper.CbsMusicSheet.class);
                    cbsMusicSheet.setId(row.getId().toString());
                    if (Objects.nonNull(row.getBizId())) {
                        cbsMusicSheet.setBizId(row.getBizId().toString());
                    }
                    if (Objects.nonNull(row.getMusicCategoryId())) {
                        cbsMusicSheet.setMusicCategoryId(row.getMusicCategoryId().toString());
                    }
                    result.add(cbsMusicSheet);
                }
                return R.from(PageUtil.transPageInfo(info, result));
            }
            return R.from(info);
        } catch (Exception e) {
            log.error("查询曲目应用拓展表异常", e);
            if (e instanceof BizException) {
                throw e;
            }
            throw BizException.from("内容平台服务异常");
        }
    }


    @ApiOperation(value = "修改应用扩展信息", notes = "曲目应用拓展表- 传入 MusicSheetApplicationExtendWrapper.MusicSheetApplicationExtend")
    @PreAuthorize("@pcs.hasPermissions('musicSheetApplicationExtend/update')")
    @PostMapping("/update")
    public R<JSONObject> update(@RequestBody CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend addMusicSheetApplicationExtend) {

        // 更新数据
        addMusicSheetApplicationExtend.setApplicationId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
        try {

            musicFeignClientService.musicSheetApplicationExtendUpdate(addMusicSheetApplicationExtend).feignData();
        } catch (Exception e) {
            log.error("修改应用扩展信息异常", e);
            if (e instanceof BizException) {
                throw e;
            }
            throw BizException.from("内容平台服务异常");
        }

        return R.defaultR();
    }


    @ApiOperation(value = "启/停用", notes = "曲目应用拓展表- 传入 MusicSheetApplicationExtendWrapper.MusicSheetApplicationExtend")
    @PreAuthorize("@pcs.hasPermissions('musicSheetApplicationExtend/status')")
    @PostMapping("/status")
    public R<JSONObject> status(@Validated @RequestBody CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtendStatus status) {

        // 更新数据
        try {

            musicFeignClientService.musicSheetApplicationExtendStatus(status).feignData();
        } catch (Exception e) {
            log.error("启/停用异常", e);
            if (e instanceof BizException) {
                throw e;
            }
            throw BizException.from("内容平台服务异常");
        }

        return R.defaultR();
    }


    @ApiOperation(value = "批量保存扩展信息")
    @PreAuthorize("@pcs.hasPermissions('musicSheetApplicationExtend/saveBatch')")
    @PostMapping("/saveBatch")
    public R<JSONObject> saveBatch(@RequestBody List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> list) {

        if (CollectionUtils.isEmpty(list)) {
            throw BizException.from("参数错误");
        }
        for (CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend addMusicSheetApplicationExtend : list) {
            addMusicSheetApplicationExtend.setApplicationId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
            if(addMusicSheetApplicationExtend.getAvailableType() == null){
                addMusicSheetApplicationExtend.setAvailableType(EMusicAvailableType.ORG);
            }
        }
        // 更新数据
        try {

            musicFeignClientService.musicSheetApplicationExtendSaveBatch(list).feignData();
        } catch (Exception e) {
            log.error("批量保存扩展信息异常", e);
            if (e instanceof BizException) {
                throw e;
            }
            throw BizException.from("内容平台服务异常");
        }

        return R.defaultR();
    }


    @ApiOperation(value = "应用分类列表")
    @PostMapping("/categoryList")
    public R<List<CbsMusicSheetCategoryWrapper.MusicSheetCategory>> categoryList() {

        return R.from(cbsMusicSheetService.categoryList(new CbsMusicSheetCategoryWrapper.MusicSheetCategoryQuery()));

    }

    @ApiOperation(value = "所属人信息查询")
    @PostMapping("/ownerList")
    public R<PageInfo<CbsMusicSheetExtendWrapper.MusicSheetExtend>> ownerList(@RequestBody CbsMusicSheetExtendWrapper.MusicSheetExtendQuery queryInfo) {

        return R.from(cbsMusicSheetService.ownerList(queryInfo));
    }

    @ApiOperation(value = "查询曲目适用项目的扩展信息")
    @PostMapping("/applicationExtendInfo")
    public R<CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtend> applicationExtendInfo(@RequestBody @Validated CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtendQuery query) {
        if (query == null || query.getMusicSheetId() == null) {
            throw BizException.from("参数错误");
        }
        query.setApplicationId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
        R<List<CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtend>> listR = musicFeignClientService.musicSheetApplicationExtendApplicationExtendInfo(query);
        List<CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtend> data = listR.feignData();
        if (CollectionUtils.isNotEmpty(data)) {
            return R.from(data.get(0));
        } else {
            throw new BizException("扩展信息不存在");
        }
    }

}
