package com.ruoyi.web.controller.dxp.system.metadata;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dxp.constant.DxpConstants;
import com.ruoyi.dxp.domain.DataIntegration;
import com.ruoyi.dxp.domain.DataItem;
import com.ruoyi.dxp.domain.DataShare;
import com.ruoyi.dxp.dto.MetaDataSave;
import com.ruoyi.dxp.dto.ResApiPageDto;
import com.ruoyi.dxp.dto.database.DatabaseUtilsDbQueryParam;
import com.ruoyi.dxp.service.IDataIntegrationService;
import com.ruoyi.dxp.service.IDataItemService;
import com.ruoyi.dxp.utils.DatabaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 元数据Controller
 *
 * @author jy
 * @date 2022-11-22
 */
@RestController
@RequestMapping("/system/metadata/data")
public class MetadataDataController extends BaseController {
    @Autowired
    private IDataIntegrationService dataIntegrationService;

    @Autowired
    private IDataItemService dataItemService;

    /**
     * 查询元数据数据列表
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(DataIntegration dataIntegration) {
        startPage();
        dataIntegration.setIsMetadata(DxpConstants.YES);
        List<DataIntegration> list = dataIntegrationService.selectDataIntegrationList(dataIntegration);
        return getDataTable(list);
    }

    /**
     * 导出元数据列表
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:export')")
    @Log(title = "元数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DataIntegration dataIntegration)
    {
        // 获取远程数据
        DatabaseUtilsDbQueryParam queryParam = new DatabaseUtilsDbQueryParam();
        queryParam.setId(dataIntegration.getDatabaseId());
        queryParam.setTbName(dataIntegration.getTableName());
        queryParam.setPageNo(1);
        queryParam.setPageSize(1000000);
        R<ResApiPageDto<List<Object>>> resApiPageDtoR = DatabaseUtils.queryTable(queryParam);
        if (resApiPageDtoR.getCode() == HttpStatus.SUCCESS) {
            List<Object> list = resApiPageDtoR.getData().getList();
            ExcelUtil<Object> util = new ExcelUtil<Object>(Object.class);
            util.exportExcel(response, list, "元数据数据");
        }
    }

    /**
     * 获取元数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(dataIntegrationService.selectDataIntegrationById(id));
    }

    /**
     * 查询元数据明细
     *
     * @param id 元数据id
     * @return 明细集合
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:query')")
    @GetMapping(value = "/dataitem")
    public AjaxResult getDataItem(Long id) {
        DataItem req = new DataItem();
        req.setDataType(DxpConstants.DATA_TYPE_INTEGRATION);
        req.setDataId(id);
        return success(dataItemService.selectDataItemList(req));
    }

    /**
     * 查询数据
     *
     * @param id id
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:query')")
    @GetMapping(value = "/data")
    public AjaxResult getData(Long id, Integer page, Integer pageSize) {
        return dataIntegrationService.getData(id, page, pageSize);
    }

    /**
     * 新增元数据
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:add')")
    @Log(title = "元数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MetaDataSave metaDataSave) {
        metaDataSave.setIsMetadata(DxpConstants.YES);
        try {
            return dataIntegrationService.saveMetadata(metaDataSave);
        } catch (Exception e) {
            // 删除远程创建的表
//            DatabaseUtils.deleteTable(metaDataSave.getDatabaseId(), metaDataSave.getTableName());
            return error(e.getMessage());
        }
    }

    /**
     * 修改元数据
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:edit')")
    @Log(title = "元数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MetaDataSave metaDataSave) {
        try {
            return dataIntegrationService.saveMetadata(metaDataSave);
        } catch (Exception e) {
            // 删除远程创建的表
//            DatabaseUtils.deleteTable(metaDataSave.getDatabaseId(), metaDataSave.getTableName());
            return error(e.getMessage());
        }
    }

    /**
     * 删除元数据
     */
    @PreAuthorize("@ss.hasPermi('system/metadata:data:remove')")
    @Log(title = "元数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return dataIntegrationService.deleteDataIntegrationById(id);
    }
}
