package com.xueyi.system.digitalmans.manager.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xueyi.common.core.constant.basic.OperateConstants;
import com.xueyi.common.web.entity.domain.SlaveRelation;
import com.xueyi.system.api.digitalmans.domain.dto.DmScreenIconDto;
import com.xueyi.system.api.digitalmans.domain.po.DmModelIconPo;
import com.xueyi.system.api.digitalmans.domain.po.DmScreenIconPo;
import com.xueyi.system.digitalmans.controller.DmQAndAController;
import com.xueyi.system.digitalmans.domain.dto.DmModelUploadDto;
import com.xueyi.system.api.digitalmans.domain.po.DmDigitalmanPo;
import com.xueyi.system.api.digitalmans.domain.po.DmModelPo;
import com.xueyi.system.api.digitalmans.domain.dto.DmModelDto;
import com.xueyi.system.api.digitalmans.domain.merge.DmModelIconMerge;
import com.xueyi.system.digitalmans.domain.model.DmScreenIconConverter;
import com.xueyi.system.digitalmans.domain.query.DmModelQuery;
import com.xueyi.system.digitalmans.domain.model.DmModelConverter;
import com.xueyi.system.digitalmans.mapper.DmDigitalmanMapper;
import com.xueyi.system.digitalmans.mapper.DmModelIconMapper;
import com.xueyi.system.digitalmans.mapper.DmModelMapper;
import com.xueyi.common.web.entity.manager.impl.BaseManagerImpl;
import com.xueyi.system.digitalmans.manager.IDmModelManager;
import com.xueyi.system.api.resource.domain.po.DmResourcesPo;
import com.xueyi.system.digitalmans.mapper.DmScreenIconMapper;
import com.xueyi.system.digitalmans.mapper.merge.DmModelIconMergeMapper;
import com.xueyi.system.resource.domain.po.DmBackgroundPo;
import com.xueyi.system.resource.domain.po.DmScreenOffPo;
import com.xueyi.system.resource.mapper.DmBackgroundMapper;
import com.xueyi.system.resource.mapper.DmResourcesMapper;
import com.xueyi.system.resource.mapper.DmScreenOffMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.xueyi.system.api.digitalmans.domain.merge.MergeGroup.Model_DmModelIcon_GROUP;


/**
 * 模型管理 数据封装层处理
 *
 * @author xueyi
 */
@Component
public class DmModelManager extends BaseManagerImpl<DmModelQuery, DmModelDto, DmModelPo, DmModelMapper, DmModelConverter> implements IDmModelManager {

    private static final Logger log = LoggerFactory.getLogger(DmModelManager.class);
    @Autowired
    DmResourcesMapper dmResourcesMapper;

    @Autowired
    DmModelMapper modelMapper;

    @Autowired
    DmScreenOffMapper screenOffMapper;

    @Autowired
    DmBackgroundMapper backgroundMapper;

    @Autowired
    DmDigitalmanMapper digitalmanMapper;

    @Autowired
    DmModelIconMapper dmModelIconMapper;

    @Autowired
    DmScreenIconMapper dmScreenIconMapper;

    @Autowired
    DmScreenIconConverter screenIconConverter;

//    @Override
//    protected List<SlaveRelation> subRelationInit() {
//        List result = new ArrayList<SlaveRelation>();
//        result.add(new SlaveRelation(Model_DmModelIcon_GROUP, DmModelIconMergeMapper.class, DmModelIconMerge.class, OperateConstants.SubOperateLimit.ONLY_DEL));
//        return result;
//    }

    @Override
    public DmModelDto selectById(Serializable id) {

        DmModelQuery query = new DmModelQuery();
        query.setManId(Long.parseLong(id.toString()));
        List<DmModelDto> items = super.selectList(query);
//        DmModelDto item = super.selectById(id);
//        if (item == null ){
//            return item;
//        }
        if (items == null || items.size() == 0) {
            return null;
        }
        DmModelDto modelDto = items.get(0);
        if (modelDto.getSuitContain().length() > 0) {
            modelDto.setRSuits(new ArrayList<>(modelDto.getSuitContain().split(",").length));
            Arrays.asList(modelDto.getSuitContain().split(",")).forEach(suitItem-> {
                modelDto.getRSuits().add(dmResourcesMapper.selectById(Long.parseLong(suitItem)));
            });
        }
        // 获取背景页
        List<DmBackgroundPo> backgroundPos = backgroundMapper.selectList(null);
        List<DmResourcesPo> bResourcesPos = new ArrayList<>();
        backgroundPos.forEach(rpo->bResourcesPos.add(dmResourcesMapper.selectById(rpo.getResourceId())));
        modelDto.setRBackgrounds(bResourcesPos);


        /** 新业务 需求变更，代码暂时保留
        if (modelDto.getBackgroundContain() != null && modelDto.getBackgroundContain().length() > 0) {
            modelDto.setRBackgrounds(new ArrayList<>(modelDto.getBackgroundContain().split(",").length));
            Arrays.asList(modelDto.getBackgroundContain().split(",")).forEach(bgItem-> {
                modelDto.getRBackgrounds().add(dmResourcesMapper.selectById(Long.parseLong(bgItem)));
            });
        }
        **/
        // 获取模型页
        modelDto.setModelUrl(dmResourcesMapper.selectById(modelDto.getCurrentModel()).getUrl());
        // 获取展示页
        List<DmScreenOffPo> screenOffPos = screenOffMapper.selectList(null);
        List<DmResourcesPo> resourcesPos = new ArrayList<>();
        screenOffPos.forEach(rpo->resourcesPos.add(dmResourcesMapper.selectById(rpo.getResourceId())));
        modelDto.setRScreenOffs(resourcesPos);
        if (modelDto.getIconId() != null) {
            modelDto.setRIcon(dmResourcesMapper.selectById(modelDto.getIconId()));
        }

        // 获取主界面icon
        List<DmModelIconPo> modelIconList = dmModelIconMapper.selectModelIconListByModelId(modelDto.getId());
        log.info("主界面icon列表:{}", modelIconList);
        if (modelIconList != null && modelIconList.size() > 0) {
            List<DmScreenIconDto> screenIconDtos = new ArrayList<>();
            modelIconList.forEach(iconItem-> {
                // 获取icon
                DmScreenIconPo iconPo = dmScreenIconMapper.selectById(iconItem.getIconId());
                DmScreenIconDto temp = screenIconConverter.mapperDto(iconPo);
                DmResourcesPo resourcesPo = dmResourcesMapper.selectById(iconPo.getResourceId());
                temp.setPos(iconItem.getPos());
                temp.setIconUrl(resourcesPo.getUrl());
                screenIconDtos.add(temp);
            });
            modelDto.setDmScreenIconDtos(screenIconDtos);
        }

        return modelDto;
    }

    @Override
    public int uploadResourceByResourceId(DmModelUploadDto dto) {
        //获取数字人模型
        DmModelPo mpo = super.selectById(dto.getId());
        //获取资源数据
        Long id = dto.getBgUploadId() == null ? dto.getBgUploadId() : dto.getIconUploadId();
        DmResourcesPo rpo = new DmResourcesPo();
        rpo.setType(dto.getUploadType());
        rpo.setName(dto.getUploadName());
        dmResourcesMapper.update(rpo, Wrappers.<DmResourcesPo>query()
                .lambda().eq(DmResourcesPo::getId,rpo.getId()));
        //绑定数字人模型-资源
        if (dto.getBgUploadId() != null) {
            //更新背景接口
            String tmp = mpo.getBackgroundContain();
            if (mpo.getBackgroundContain().split(",").length < 10) {
                mpo.setBackgroundContain(dto.getBgUploadId() + "," + tmp);
            } else {
                mpo.setBackgroundContain(dto.getBgUploadId() + "," + tmp.substring(0,tmp.lastIndexOf(",")));
            }
        } else {
            //更新icon接口
            mpo.setIconId(dto.getIconUploadId());
        }

        return modelMapper.updateById(mpo);
    }

    @Override
    public int update(DmModelDto dto) {
        //更新数字人昵称
//        DmDigitalmanPo po = digitalmanMapper.selectOne(Wrappers.<DmDigitalmanPo>query()
//                .lambda().eq(DmDigitalmanPo::getManCode, dto.getManId()));
        DmDigitalmanPo po = digitalmanMapper.selectById(dto.getManId());
        po.setName(dto.getName());
        digitalmanMapper.updateById(po);
        //更新主界面icon
        List<DmModelIconPo> iconPos = dmModelIconMapper.selectModelIconListByModelId(dto.getId());
        if (iconPos != null && iconPos.size() > 0) {
            // 删除原有icon
            dmModelIconMapper.deleteMerge(iconPos.get(0));
        }
        log.info("主界面icon列表：{}",dto.getDmScreenIconDtos());
        if (dto.getDmScreenIconDtos() != null && dto.getDmScreenIconDtos().size() > 0) {
            // 新增icon
            for (DmScreenIconDto screenIconDto : dto.getDmScreenIconDtos()) {
                DmScreenIconPo screenIconPo = new DmScreenIconPo();
                if (screenIconDto.getId() != null && screenIconDto.getId().doubleValue() > 0) {
                    // 更新模型-主界面icon关系
                    screenIconPo = dmScreenIconMapper.selectById(screenIconDto.getId());
                    screenIconPo.setName(screenIconDto.getName());
                    screenIconPo.setResourceId(screenIconDto.getResourceId());
                    screenIconPo.setBroadcastId(screenIconDto.getBroadcastId());
                    dmScreenIconMapper.updateById(screenIconPo);
                } else {
                    screenIconPo = new DmScreenIconPo();
                    screenIconPo.setName(screenIconDto.getName());
                    screenIconPo.setResourceId(screenIconDto.getResourceId());
                    screenIconPo.setBroadcastId(screenIconDto.getBroadcastId());
                    dmScreenIconMapper.insert(screenIconPo);
                }
                // 新增模型-主界面icon关系
                DmModelIconPo iconPo = new DmModelIconPo();
                iconPo.setModelId(dto.getId());
                iconPo.setIconId(screenIconPo.getId());
                iconPo.setPos(screenIconDto.getPos());
                dmModelIconMapper.insertMerge(iconPo);
            }
        }

        return super.update(dto);
    }
}