<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form status-icon inline v-model="query">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="物料名称">
                            <el-select v-model="query.leibiemc" filterable placeholder="请选择物料" clearable style="width: 200px">
                                <el-option v-for="item in typeList" :key="item.itemCd" :label="item.itemNm"
                                    :value="item.itemNm"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="5">
                        <el-form-item label="供货单位">
                            <el-select v-model="query.gonghuodw" filterable placeholder="请选择" clearable style="width: 200px">
                                <el-option v-for="item in gongsiList" :key="item.fnumber" :label="item.fname"
                                    :value="item.fname" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="委托类型" prop="">
                            <el-select v-model="query.smpType" placeholder="" clearable style="width: 200px">
                                <!-- <el-option v-for="item in smpTypeList" :key="item.bm" :label="item.wtmc"
                                    :value="item.bm"></el-option> -->
                                    <el-option label="原料委托" value="Y"></el-option>
                                    <el-option label="成品委托" value="C"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="计量号" prop="">
                            <el-input placeholder="请输入" v-model="query.jiliangh" style="width: 200px"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" link @click="show">
                            高级查询
                            <el-icon v-if="showA">
                                <ArrowUp />
                            </el-icon>
                            <el-icon v-else>
                                <ArrowDown />
                            </el-icon>
                        </el-button>
                        <el-button type="primary" link @click="reset">
                            重置
                        </el-button>
                    </el-col>
                </el-row>
                <el-row v-if="showA">

                    <el-col :span="5">
                        <el-form-item label="委托编号" prop="">
                            <el-input placeholder="请输入" v-model="query.id" style="width: 200px" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="留样编号" prop="">
                            <el-input placeholder="请输入" v-model="query.liuyangbh" style="width: 200px"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="组批编号" prop="">
                            <el-input placeholder="请输入" v-model="query.zupibh" style="width: 200px"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="合同号" prop="">
                            <el-input placeholder="请输入" v-model="query.contractNo" style="width: 200px"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="showA">
                    <el-col :span="5">
                        <el-form-item label="物理编号" prop="">
                            <el-input placeholder="请输入" v-model="query.wulizybh" style="width: 200px"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="化学编号" prop="">
                            <el-input placeholder="请输入" v-model="query.huaxuezybh" style="width: 200px"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="5">
                        <el-form-item label="制样提交时间">
                            <el-date-picker v-model="query.tijiaosj" type="datetimerange" align="right" unlink-panels
                                range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                                style="width: 435px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                                clearable>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="showA">

                </el-row>
            </el-form>
        </el-card>
        <ButtonBar area="top" @search="handleSearch" @export="handleExport"></ButtonBar>
        <el-card :body-style="cardBodyStyle">
            <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
                <el-table-column type="selection" fixed></el-table-column>
                <el-table-column type="index" label="序号" align="center" width="60">
                    <template #default="scope">
                        <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column v-for="item in listKey" :prop="item" :label="item" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </el-card>
    </div>
</template>

<script setup>
import ButtonBar from "@/components/ButtonBar.vue";
import SearchBox from "@/components/SearchBox.vue";
import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'
import style from '@/tools/style'
import { ElMessage, ElMessageBox } from "element-plus";


onMounted(() => {
    queryType()
    queryGS()
    queryWTLXType()
    handleSearch()
})


const { proxy } = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const form = ref({

})
const tableData = ref([])
const query = ref({
    leibiemc: '',
    gonghuodw: '',
    smpType: '',
    jiliangh: '',
    id: '',
    liuyangbh: '',
    zupibh: '',
    contractNo: '',
    wulizybh: '',
    huaxuezybh: '',
    tijiaosj: ''
})
const showA = ref(false)
const show = () => {
    showA.value = !showA.value
}

/**
 * 重置查询条件
 */
const reset = () => {
    Object.keys(query.value).map(key => {
        query.value[key] = ''
    })
}

const gongsiList = ref([])
const queryGS = () => {
    gongsiList.value = []
    var url = 'sci/Weituogl/queryGS'
    var param = {}
    proxy.$axios.get(url, param).then(resp => {
        if (resp.data.code == '0') {
            gongsiList.value = resp.data.data
            console.log(gongsiList.value)
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }

    })
}

// 查询物料名称
const typeList = ref([])
const queryType = () => {
    var url = 'sci/platform/queryType'
    var param = {}
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            typeList.value = response.data.data
            // console.log(response.data.data)
            // console.log(typeList.value)
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}

// ==========查询数据===========
const orderedKeys = ref([
    "委托编号",
    "物料名称",
    "创建时间",
    "组批编号",
    "样品类型",
    "供货单位",
    "收货单位",
    "留样编号",
    "计量号",
    "运输方式",
    "委托状态",
    "委托类型",
    "物理制样编号",
    "化学制样编号",
    "物理站审核人",
    "化学站审核人",
    "物理站提交时间",
    "物理站审核时间",
    "化学站提交时间",
    "化学站审核时间"
]);
const listKey = ref([])
const getTableData = () => {
    var url = 'sci/dataQuery/query'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value),
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            console.log(tableData.value)
            const dynamicKeysSet = new Set();
            tableData.value.forEach(currentObj => {
                Object.keys(currentObj).forEach(key => {
                    if (!orderedKeys.value.includes(key)) { // 如果 key 不在 orderedKeys 中，添加到 dynamicKeysSet
                        dynamicKeysSet.add(key);
                    }
                });
            });
            // 将静态字段和动态字段合并，生成最终顺序的 listKey
            listKey.value = [...orderedKeys.value, ...Array.from(dynamicKeysSet)];
            listKey.value = listKey.value.filter(x => x !== 'ROW_ID');
            console.log(listKey.value)
            tableData.value.forEach(x => {
                smpTypeList.value.forEach(y => {
                    if (x.样品类型 == y.bm) {
                        x.样品类型 = y.wtmc
                    }
                })
            })
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
};
const smpTypeList = ref([])
const queryWTLXType = () => {
    var url = 'sci/Weituogl/query_YLType'
    var param = {}
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            smpTypeList.value = response.data.data
            // console.log(smpTypeList.value)
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}


// ==========按钮功能===========

// 导出Excel
const handleExport = () => {
    console.log('导出')
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请至少选择一条数据导出!'
        })
        return
    }
    var params = {
        ids: multipleSelection.value.map(item => item.委托编号)
    }
    location.href = import.meta.env.VITE_BASE_API +
        '/sci/export/exportExcel_DQ?params=' + encodeURIComponent(JSON.stringify(params))
}


// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getTableData()
}
// 添加
const handleSave = () => {
    console.log('保存')
}
// 提交
const handleCommit = () => {
    console.log('提交')
}
// 批量删除
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
    console.log(val)
}
const handleRemoveBatch = () => {
    console.log('handleRemoveBatch')
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要删除的数据!'
        })
        return
    }

    ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        var ids = []
        multipleSelection.value.forEach((item, index) => {
            ids.push(item.id)
        })
        /* var url = 'cot/SignRequest/removeBatch'*/
        var param = {
            ids: JSON.stringify(ids)
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == '0') {
                ElMessage({
                    type: 'success',
                    message: '操作成功!',
                });
                getTableData()
                dialogVisible.value = false
            } else {
                ElMessage({
                    type: 'error',
                    message: '操作失败!' + response.data.msg
                });
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}
// 查询
const handleQuery = () => {
    console.log('handleQuery')
}
// 删除
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    )
        .then(() => {
            // 假数据
            const fakeData = {
                code: 0,
                msg: '删除成功'
            };

            // 模拟接口响应
            if (fakeData.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });
                getTableData();
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败' + fakeData.msg,
                });
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            });
        });
};




/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
</script>

<style scoped></style>