<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row :gutter="30">
                    <a-col :md="20">
                        <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                        </span>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="4" :sm="4">
                        <a-form-item label="型号">
                            <a-select placeholder="选择型号" option-filter-prop="children" show-search
                                :filter-option="filterOption" v-model="queryParam.mdl" @change="changeshipModel">
                                <a-select-option v-for="item in shipModel" :value="item">
                                    {{ item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="4">
                        <a-form-item label="舷号">
                            <a-select placeholder="选择舷号" option-filter-prop="children" show-search
                                :filter-option="filterOption" v-model="queryParam.hn" @change="changeshipNumber">
                                <a-select-option v-for="item in shipNumber" :value="item">
                                    {{ item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="4">
                        <a-form-item label="数据类型">
                            <a-select placeholder="选择数据类型" option-filter-prop="children" v-model="queryParam.schemaMass"
                                @change="handleTypeChange">
                                <a-select-option v-for="item in dataTypeList" :value="item.cnName">
                                    {{ item.cnName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="4">
                        <a-form-item label="任务">
                            <a-select placeholder="选择任务" option-filter-prop="children" v-model="activeTaskId"
                                @change="handleTaskChange">
                                <a-select-option v-for="d in allTask" :key="d.id">
                                    {{ d.name }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-item label="时间范围">
                            <!-- <a-range-picker :default-value="defaultTime" show-time :show-time="{ format: 'HH:mm:ss' }"
                :format="dateFormat" @change="onChangeTime" /> -->
                            <a-range-picker :show-time="{ format: 'HH:mm:ss' }" v-model="defaultTime"
                                format="YYYY-MM-DD HH:mm:ss" @change="onChangeTime" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="4" :sm="4">
                      <a-form-item label="编目" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-select placeholder="选择编目" option-filter-prop="children" @change="getMetaDataTypeTree" v-model="queryParam.tagId">
                          <a-select-option v-for="d in datatagSources" :key="d.id">
                            {{ d.tagName }}
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="5">
                        <a-form-item label="关键词">
                            <a-input placeholder="请输入搜索关键词" v-model="queryParam.massKey"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                        <a-button @click="getTableDataList" type="primary">查询</a-button>&nbsp;
                        <a-button @click="exportTool" type="primary">导出dmp</a-button>&nbsp;
                        <a-button @click="handleAdd" type="primary">导出csv、txt</a-button>&nbsp;
                        <a-button @click="openexptable" type="primary">导出日志</a-button>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <a-row :gutter="30" style="padding: 0 10px;">
            <a-col :md="6">
                <div class="linese"></div>
                <!-- 分类区域 -->
                <div style="height:calc(100vh - 420px);overflow: auto;background: #e6e9f1;padding:10px;"
                    ref="treeContainer">
                    <a-tree :tree-data="treeDate" @select="onSelect" />
                </div>
                <div class="linese"></div>
            </a-col>
            <a-col :md="18">
                <div class="linese"></div>
                <!-- 表格区域 -->
                <div style="height:calc(100vh - 420px);background: #e6e9f1;overflow:hidden;padding: 15px;">
                    <a-table size="middle" bordered :columns="columns" :data-source="dataSource" :loading="loading"
                        :pagination="pagination" :scroll="{ x: 1200, y: 'calc(100vh - 450px)' }" rowKey="序号"
                        @change="handleTableChange">
                    </a-table>
                </div>
                <div class="linese"></div>
            </a-col>
        </a-row>
        <tablelist ref="modalForm"></tablelist>
        <exptable ref="exptable"></exptable>
        <editdataseach ref="editdataseachForm" @ok="getTableDataList" />
    </a-card>
</template>
<script>
import { metaDataTypeTree, tableDataList, DmExportTool } from '@/api/metaData'
import { getAction, deleteAction, putAction, postAction, downFile } from '@/api/manage'
import { getAllTask } from '@/api/task'
import moment from 'moment';
import tablelist from '../../data/modules/tablelist.vue'
import exptable from '../../data/modules/exptable.vue'
import editdataseach from '../../data/modules/editdataseach.vue'
import {idcTableTaglist} from "@api/tag";

export default {
    name: "metadata",
    components: {
        tablelist,
        exptable,
        editdataseach
    },
    data() {
        return {
            moment,
            dateFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: [],
            loading: false,
            allTask: [],
            activeTaskId: null,
            pagination: {
                defaultCurrent: 1, // 默认当前页数
                defaultPageSize: 10, // 默认当前页显示数据的大小total: 0, // 总数，必须先有
                showSizeChanger: true,
                showQuickJumper: false,
                pageSizeOptions: ['10', '20', '30'],
                showTotal: total => `总共 ${total} 个项目`, // 显示总数
                onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize)
            },
            // 查询条件 
            queryParam: {
                sourceType: 1,
                tagId: null,
                massKey: null,
                mdl: null, // 型号
                hn: null, // 舷号
                schemaMass: null,
                tableName: null,
                startTime: null,
                endTime: null,
                pageSize: 10,
                pageNum: 1
            },
            tagqueryParam: {
              pageNum: 1,
              pageSize: 20,
              tagName: ""
            },
            treeDate: [],
            dataSource: [],
            columns: [],
            dataTypeList: [],
            shipModel: [],
            shipNumber: [],
            datatagSources: [],
            existingDataTypes: {},
            treeHeight: 0
        }
    },
    watch: {
        'queryParam.massKey'(value) {
            this.queryParam.massKey = value
            this.getMetaDataTypeTree()
        }
    },
    mounted() {
        this.calculateScrollY();
    },
    computed: {

    },
    created() {
        this.getselect()
        this.queryAllTask()
        this.getdatatagSources()
        // this.initDate() 
    },
    methods: {
        queryAllTask() {
            getAllTask().then(res => {
                if (res.success) {
                    this.allTask = res.result
                    if (res.result.length > 0) {
                        this.activeTaskId = res.result[0].id
                        const start = moment(res.result[0].startTime)
                        const end = moment(res.result[0].endTime)
                        this.defaultTime.push(start, end)
                        this.queryParam.startTime = start.format(this.dateFormat);
                        this.queryParam.endTime = end.format(this.dateFormat)
                    }
                } else {
                    this.$message.warning(res.message);
                }
            })
        },
        handleTaskChange(value) {
            var curTask = this.allTask.filter(item => item.id == value)[0]
            if (curTask) {
                const start = moment(curTask.startTime)
                const end = moment(curTask.endTime)
                this.defaultTime = [start, end]
                this.queryParam.startTime = start.format(this.dateFormat);
                this.queryParam.endTime = end.format(this.dateFormat)
            }
        },
        calculateScrollY() {
            // 获取父容器高度（需减去表格内其他元素的高度，如分页栏）
            const container = this.$refs.treeContainer;
            this.treeHeight = container.clientHeight;
        },

        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        getdatatagSources() {
          idcTableTaglist(this.tagqueryParam).then((res) => {
            if (res.success) {
              this.datatagSources = res.result.records;
              this.datatagSources.unshift({tagName:'全部',id:null})
              this.queryParam.tagId = res.result.records[0].id;
            } else {
              this.$message.warning(res.message);
            }
          });
        },
        changeshipModel(value) {
            this.queryParam.shipModel = value
            var number = Object.keys(this.existingDataTypes[value])
            this.shipNumber = []
            number.forEach((element, index) => {
                this.shipNumber.push(element);
            });
            this.dataTypeList = this.existingDataTypes[value][this.shipNumber[0]]
            this.queryParam.mdl = value
            this.queryParam.hn = this.shipNumber[0]
            this.queryParam.schemaMass = this.dataTypeList[0].cnName
            this.getMetaDataTypeTree()
        },
        changeshipNumber(value) {
            this.dataTypeList = this.existingDataTypes[this.queryParam.shipModel][value]
            this.queryParam.hn = value
            this.queryParam.schemaMass = this.dataTypeList[0].cnName
            this.getMetaDataTypeTree()
        },
        getselect() {
            getAction("/dataType/getExistingDataTypes", {}).then((res) => {
                if (res.success) {
                    this.existingDataTypes = res.result.result.original
                    var ship = Object.keys(this.existingDataTypes)
                    ship.forEach((element, index) => {
                        this.shipModel.push(element);
                    });
                    var number = Object.keys(this.existingDataTypes[this.shipModel[0]])
                    number.forEach((element, index) => {
                        this.shipNumber.push(element);
                    });
                    this.dataTypeList = this.existingDataTypes[this.shipModel[0]][this.shipNumber[0]]
                    this.queryParam.mdl = this.shipModel[0]
                    this.queryParam.hn = this.shipNumber[0]
                    this.queryParam.schemaMass = this.dataTypeList[0].cnName
                    this.getMetaDataTypeTree()
                } else {
                    this.$message.warning(res.message);
                }
            });
        },
        handleAdd() {
            if (this.queryParam.mdl == "") {
                this.$message.warning("请选择型号");
                return;
            }
            if (this.queryParam.hn == "") {
                this.$message.warning("请选择舷号");
                return;
            }
            if (this.queryParam.schemaMass == "") {
                this.$message.warning("请选择导出的数据类型");
                return;
            }
            this.$refs.modalForm.add(this.queryParam.sourceType, this.queryParam.schemaMass, this.queryParam.mdl, this.queryParam.hn);
        },
        openexptable() {
            
            if (this.queryParam.mdl == "") {
                this.$message.warning("请选择型号");
                return;
            }
            if (this.queryParam.hn == "") {
                this.$message.warning("请选择舷号");
                return;
            } 
            if (this.queryParam.schemaMass == "") {
                this.$message.warning("请选择查询的导出的数据类型");
                return;
            }
            this.$refs.exptable.add(this.queryParam.sourceType, this.queryParam.schemaMass, this.queryParam.mdl, this.queryParam.hn);
        },
        getMetaDataTypeTree() {
            metaDataTypeTree(this.queryParam).then(res => {
                if (res.code == 200) {
                    this.treeDate = []
                    var keys = Object.keys(res.result)
                    keys.forEach((element, index) => {
                        const _children = res.result[element]
                        var childrenList = []
                        _children.forEach((childrenNode, chil) => {
                            childrenList.push({
                                key: childrenNode.tableName,
                                type: 'childern',
                                title: childrenNode.massName
                            })
                        });
                        this.treeDate.push({
                            key: 'type_' + index,
                            type: 'parentType',
                            title: element,
                            children: childrenList
                        })
                    });
                }
            })
        },
        handleTypeChange(value) {
            this.queryParam.schemaMass = value
            this.getMetaDataTypeTree()
        },
        onSelect(selectedKeys, info) {
            if (info.node.dataRef.type && info.node.dataRef.type == 'childern') {
                this.queryParam.schemaMass = info.node.$parent.dataRef.title
                this.queryParam.tableName = info.node.dataRef.key
                this.getTableDataList()
            }
        },
        handleTableChange(pagination, filters, sorter) {
            this.pagination = pagination
            this.queryParam.pageNum = pagination.current
            this.queryParam.pageSize = pagination.pageSize
            this.getTableDataList()
        },
        onChangeTime(date, dateString) {
            if (date.length == 0) {
                this.queryParam.startTime = null
                this.queryParam.endTime = null
                this.queryParam.pageNum = 1
            } else {
                this.queryParam.startTime = moment(date[0]).format(this.dateFormat);
                this.queryParam.endTime = moment(date[1]).format(this.dateFormat);
                this.queryParam.pageNum = 1
            }
        },
        handelEdit(record) {
            console.log('sdfsdf', record)
            const filteredColumn = this.columns.filter(item => item.dataIndex != 'operation' && item.dataIndex != 'ROW_ID' && item.dataIndex != '数据');
            delete record['ROW_ID'];
            delete record['数据'];
            this.$refs.editdataseachForm.initForm(this.queryParam.schemaMass, this.queryParam.tableName, filteredColumn, record, this.queryParam.sourceType, this.queryParam.mdl, this.queryParam.hn);
        },
        getTableDataList() {
            console.log(this.queryParam)
            if (this.queryParam.schemaMass == null || this.queryParam.tableName == null) {
                this.$message.warning('必须选择查询的表')
                return
            }
            tableDataList(this.queryParam).then(res => {
                if (res.code == 200) {
                    this.columns = []
                    if (res.result.columnNames.length > 0) {
                        res.result.columnNames.forEach(columns => {
                            this.columns.push({
                                title: columns,
                                dataIndex: columns,
                                ellipsis: true,
                                width: 180
                            })
                        })
                    }

                    const pagination = { ...this.pagination }
                    pagination.total = res.result.total
                    this.dataSource = res.result.rows
                    this.pagination = pagination
                }

            })
        },
        exportTool() { 
            if (this.queryParam.schemaMass == "") {
                this.$message.warning("请选择导出的数据类型");
                return;
            }
            postAction("/dataManager/DmExportTool?sourceType="+this.queryParam.sourceType+"&mdl="+this.queryParam.mdl+"&hn="+this.queryParam.hn+"&schemaMass=" + this.queryParam.schemaMass + "&tableNames=" + "" + "&exportType=0", {}).then(res => {
                if (res.code == 200) {
                    this.$message.success(res.result);
                } else {
                    this.$message.warning(res.message)
                }
            })
        }
    }
}
</script>