<template>
    <div>
        <SearchBox ref="searchBarRef" :formName="search" :formData="query" @showPopupUser="showPop" showResetButton
            @reset="reset" />
        <ButtonBar @search="handleSearch" @add="count" @remove="handleRemoveBatch" @edit="handleEditBatch"
            @upload="handleUpload" @download="handleDownload" @import="handleImport" @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-if="true" prop="operDt" label="生产日期" width="160" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="operShift" label="班次" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="indiNm" label="指标名称" width="160" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="indiGrd" label="指标品位" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="rewaPuni" label="奖惩" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="操作" header-align="center" align="center" width="200px">
                    <template #default="scope">
                        <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-card :body-style="cardBodyStyle">
            <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>

        <el-card :body-style="cardBodyStyle">
            <el-row>
            <el-form :inline="true">
                <el-form-item label="统计时间" style="margin-bottom: 5px;">
                    <el-date-picker v-model="monthQuery.monthValue" type="month" placeholder="请选择年月" />
                </el-form-item>
            </el-form>
            <el-button type="success" plain @click="countMonthQuery">统计查询</el-button>
            <el-button type="primary" plain @click="searchReport">查看报表</el-button>
        </el-row>
            <el-tabs type="border-card">
                <el-tab-pane label="总计">
                    <el-table :data="monthTableData" border highlight-current-row >
                <el-table-column v-if="true" prop="table1" label="" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table2" label="" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table3" label="铁精品位" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table4" label="铜精品位" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table5" label="尾铁品位" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table6" label="尾铜品位" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table7" label="铁精含硫" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table8" label="铁精水分" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="table9" label="总计" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
            </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-dialog :close-on-click-modal="false" draggable title="编辑" v-model="dialogVisible" width="1000px" top="5vh"
            @open="openDialog">
            <el-form :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <el-form-item label="指标品位">
                    <el-input v-model="form.indiGrd" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="奖惩">
                    <el-input v-model="form.rewaPuni" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="指标名称">
                    <el-input v-model="form.indiNm" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="生产日期" prop="operDt">
                    <el-date-picker v-model="form.operDt" type="date" style="width: 200px;"
                        value-format="YYYY-MM-DD" format="YYYY-MM-DD"></el-date-picker>
                </el-form-item>
                <el-form-item label="班次" prop="operShift">
                    <el-input v-model="form.operShift" clearable style="width: 200px"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog :close-on-click-modal="false" draggable v-model="reportDialogVisible" width="900px" top="5vh">
            <fine-report ref="finereport" :reportPath="reportPath"></fine-report>
        </el-dialog>
        
    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    handleSearch()
})
const monthQuery = ref({
    monthValue : ''
})
const monthTableData = ref([])
const countMonthQuery = () => {
    var url = 'prd/IndiAsseStdCount/countMonthQuery'
    var param = {
        params: JSON.stringify(monthQuery.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            monthTableData.value = response.data.data
            monthTableData.value.forEach(item => {item.table9 = item.table3 + item.table4 + item.table5 + item.table6+item.table7 + item.table8
            })
        } else {
            monthTableData.value = null
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
const pDate = ref('')
const pReportDate = ref('')
import FineReport from '@/components/report/FineReport.vue'
const reportPath = ref('')
const finereport = ref(null)
const reportDialogVisible = ref(false);

const searchReport = () => {
    if(monthQuery.value.monthValue != '' && monthQuery.value.monthValue != null && monthQuery.value.monthValue.length == undefined){
        pDate.value = monthQuery.value.monthValue.getFullYear() + String(monthQuery.value.monthValue.getMonth() + 1).padStart(2, '0')
        pReportDate.value = formatDateToYYYYMMDD(new Date())
        reportPath.value = 'jlyypt/prdIndiAsseStdCount.cpt&p_date='+String(pDate.value)+'&p_report_user='+String(localStorage.getItem('userDesc'))+'&p_report_date='+String(pReportDate.value)
        reportDialogVisible.value = true
        finereport.value.refresh()
    }else{
        ElMessage.error('请输入统计时间')
    }
}
function formatDateToYYYYMMDD(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); 
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**
 *   查询
 */




const query = ref({
    operDt: [proxy.$dayjs().format('YYYY-MM-DD') + ' 00:00:00', proxy.$dayjs().format('YYYY-MM-DD') + ' 23:59:59']
})
const tableData = ref([])
const handleSearch = () => {
    currentPage.value = 1
    getTableData()
}

const getTableData = () => {
    var url = 'prd/IndiAsseStdCount/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
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
/**
 *   查询
 */

 const count = ()=>{
    var url = 'prd/IndiAsseStdCount/count'
    var param = {
        params: JSON.stringify(query.value)
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == '0') {
            ElMessage.success('操作成功！')
            getTableData()
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
 }

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


/**
 * 新增
 */
const dialogVisible = ref(false)
const form = ref({
    indiGrd: '',
    rewaPuni: '',
    indiNm: '',
    operDt: '',
    operShift: ''
})
const ruleFormRef = ref()
const rules = reactive({
    operDt: [{
        required: true,
        message: '请输入生产日期',
        trigger: 'change' | 'blur'
    }],
    operShift: [{
        required: true,
        message: '请输入班次',
        trigger: 'change' | 'blur'
    }]
})

const handleAdd = () => {
    form.value = {
        indiGrd: '',
        rewaPuni: '',
        indiNm: '',
        operDt: '',
        operShift: ''
    }
    dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'prd/IndiAsseStdCount/save'
            var param = {
                json: JSON.stringify(form.value),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    form.value = response.data.data
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    getTableData()
                    dialogVisible.value = false
                } else {
                    // ElMessage.error('操作失败！' + response.data.msg)
                    ElMessage({
                        message: '操作失败' + response.data.msg,
                        type: 'error'
                    })
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {
    dialogVisible.value = true
    form.value = row
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    )
        .then(() => {
            var url = 'prd/IndiAsseStdCount/remove'
            var param = {
                id: row.id
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getTableData()
                } else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败' + response.data.msg
                    });
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = 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 = 'prd/IndiAsseStdCount/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 handleEditBatch = () => {
    console.log('handleEditBatch')
    if (multipleSelection.value.length != 1) {
        ElMessage({
            type: 'warning',
            message: '请选择一条数据编辑!'
        })
        return
    }
    handleEdit(multipleSelection.value[0])
}

const handleUpload = () => {
    console.log('handleUpload')
}

const handleDownload = () => {
    console.log('handleDownload')
}

const handleImport = () => {
    console.log('handleImport')
}

const handleExport = () => {
    console.log('handleExport')
}

</script>

<style></style>