package com.xueyi.system.digitalmans.controller;

import com.alibaba.fastjson2.JSONObject;
import com.xueyi.common.core.utils.core.IdUtil;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.core.web.validate.V_A;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.security.annotation.Logical;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.system.api.digitalmans.domain.vo.DmBroadcastVo;
import com.xueyi.system.api.meeting.feign.RemoteMeetingService;
import com.xueyi.system.api.organize.domain.po.SysUserPo;
import com.xueyi.system.digitalmans.domain.dto.DmBroadcastDto;
import com.xueyi.system.digitalmans.domain.dto.DmDigitalmanDto;
import com.xueyi.system.digitalmans.domain.merge.DmBroadcastResourceMerge;
import com.xueyi.system.digitalmans.domain.query.DmBroadcastQuery;
import com.xueyi.system.digitalmans.domain.query.DmDigitalmanQuery;
import com.xueyi.system.digitalmans.manager.impl.DmBroadcastManager;
import com.xueyi.system.digitalmans.service.IDmBroadcastService;
import com.xueyi.system.digitalmans.service.IDmDigitalmanService;
import com.xueyi.system.organize.service.ISysUserService;
import com.xueyi.system.resource.domain.dto.DmResourcesDto;
import com.xueyi.system.resource.domain.model.DmResourcesConverter;
import com.xueyi.system.resource.mapper.DmResourcesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 播报管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/broadcast")
public class DmBroadcastController extends BaseController<DmBroadcastQuery, DmBroadcastDto, IDmBroadcastService> {

    @Autowired
    private DmBroadcastManager broadcastManager;
    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "播报" ;
    }

    @Autowired
    private DmResourcesMapper resourceMapper;

    @Autowired
    private DmResourcesConverter resourcesConverter;

    @Autowired
    private IDmDigitalmanService digitalmanService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询播报列表
     */
    @GetMapping("/inner/list")
    public R<List<DmBroadcastVo>> innerlist(@RequestParam("manCode")String manCode) {
        DmDigitalmanQuery query = new DmDigitalmanQuery();
        query.setManCode(manCode);
        List<DmDigitalmanDto> manList = digitalmanService.selectList(query);
        List<DmBroadcastDto> list = baseService.selectListScope(new DmBroadcastQuery());
        List<DmBroadcastVo> voList = new ArrayList<>();
        list.forEach(item-> {
            // 定义DmBroadcastVo类型变量vo，将list.get(0)赋值给vo
            DmBroadcastVo vo = new DmBroadcastVo();
            vo.setId(item.getId());
            vo.setSpeed(item.getSpeed());
            vo.setRecycle(item.getRecycle());
            List<JSONObject> rList = new ArrayList<>();
            List<DmBroadcastResourceMerge> mergeDtos = broadcastManager.selectBroadcastResourceMerge(item.getId());
            int order = 0;
            for (DmBroadcastResourceMerge merge : mergeDtos) {
                if (merge.getResourceId() != null && merge.getResourceId() > 0) {

                    DmResourcesDto resourcesDto = resourcesConverter.mapperDto(resourceMapper.selectById(merge.getResourceId()));
                    JSONObject json = new JSONObject();
                    json.put("order",order++);
                    json.put("ttsText",merge.getTtsText());
                    json.put("url", resourcesDto.getUrl());
                    rList.add(json);
                }
            }
            vo.setResource(rList);
            voList.add(vo);
        });
        if (voList.size() > 0)
            return R.ok(voList);
        return R.fail("无法获取播报信息");
    }

    /**
     * 查询播报列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_BROADCAST_LIST)
    public AjaxResult list(DmBroadcastQuery broadcast) {
        startPage();
        List<DmBroadcastDto> list = baseService.selectListScope(broadcast);

        for (DmBroadcastDto dto : list) {
            List<DmBroadcastResourceMerge> mergeDtos = broadcastManager.selectBroadcastResourceMerge(dto.getId());
            SysUserPo user = sysUserService.selectById(dto.getCreateBy());
            dto.setUserName(user.getUserName());
            List<JSONObject> temp = new ArrayList<>();
            for (DmBroadcastResourceMerge merge : mergeDtos) {
                if (merge.getResourceId() != null && merge.getResourceId() > 0) {
                    DmResourcesDto resourcesDto = resourcesConverter.mapperDto(resourceMapper.selectById(merge.getResourceId()));
                    JSONObject json = JSONObject.from(merge);
                    json.put("url", resourcesDto.getUrl());
                    temp.add(json);
                }
            }


            dto.setObjList(temp);
        }
        return getDataTable(list);
    }

    /**
     * 查询播报详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_BROADCAST_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }

    /**
     * 播报新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_BROADCAST_ADD)
    @Log(title = "播报管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmBroadcastDto broadcast) {
        Long id = IdUtil.getSnowflakeNextId();
        broadcast.setId(id);
        broadcast.setCreateTime(LocalDateTime.now());
        broadcastManager.addBroadcastResourceMerge(id,  broadcast.getResourceList());
        return super.add(broadcast);
    }

    /**
     * 播报修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_BROADCAST_EDIT)
    @Log(title = "播报管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmBroadcastDto broadcast) {
        broadcastManager.editBroadcastResourceMerge(broadcast.getId(), broadcast.getResourceList());
        broadcast.setUpdateTime(LocalDateTime.now());
        return super.edit(broadcast);
    }

    /**
     * 播报修改状态
     */
    @Override
    @PutMapping("/status")
    @RequiresPermissions(value = {Auth.DM_BROADCAST_EDIT, Auth.DM_BROADCAST_ES}, logical = Logical.OR)
    @Log(title = "播报管理", businessType = BusinessType.UPDATE_STATUS)
    public AjaxResult editStatus(@RequestBody DmBroadcastDto broadcast) {
        return super.editStatus(broadcast);
    }

    /**
     * 播报批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_BROADCAST_DEL)
    @Log(title = "播报管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }

    /**
     * 获取播报选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }

    interface Auth {
        /** 系统 - 播报管理 - 列表 */
        String DM_BROADCAST_LIST = "digitalmans:broadcast:list";
        /** 系统 - 播报管理 - 详情 */
        String DM_BROADCAST_SINGLE = "digitalmans:broadcast:single";
        /** 系统 - 播报管理 - 新增 */
        String DM_BROADCAST_ADD = "digitalmans:broadcast:add";
        /** 系统 - 播报管理 - 修改 */
        String DM_BROADCAST_EDIT = "digitalmans:broadcast:edit";
        /** 系统 - 播报管理 - 修改状态 */
        String DM_BROADCAST_ES = "digitalmans:broadcast:es";
        /** 系统 - 播报管理 - 删除 */
        String DM_BROADCAST_DEL = "digitalmans:broadcast:delete";
    }
}
