<template>
    <div>
        <SearchBox ref="SearchBoxRef" formName="search" :formData="query" @showPop="showPop" @reset="reset"></SearchBox>
        <ButtonBar @search="handleSearch" @add="handleAdd" @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"
                style="height: 500px;">
                <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="false" prop="" label="ID" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="planDate" label="计划日期" width="150" header-align="center"
                    align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <el-date-picker v-if="scope.row.planDate1" v-model="scope.row.planDate" type="date"
                            style="width: 100%;" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
                            placeholder="请选择"></el-date-picker>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.planDate }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="resoQty" label="资源获取计划量" width="130" header-align="center"
                    align="right" show-overflow-tooltip>
                    <template #default="scope">
                        <!-- <el-input v-if="scope.row.resoQty1" v-model="scope.row.resoQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.resoQty }}</div> -->
                        <div>{{ scope.row.resoQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="jfQty" label="精粉类计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.jfQty1" v-model="scope.row.jfQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.jfQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="fjfQty" label="非精粉类计划量" width="130" header-align="center"
                    align="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.fjfQty1" v-model="scope.row.fjfQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.fjfQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="jzQty" label="金召矿计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.jzQty1" v-model="scope.row.jzQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.jzQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="jdQty" label="金鼎矿计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.jdQty1" v-model="scope.row.jdQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.jdQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="zyQty" label="正元矿计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.zyQty1" v-model="scope.row.zyQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.zyQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="feQty" label="铁精粉计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.feQty1" v-model="scope.row.feQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.feQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="cuQty" label="铜精粉计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.cuQty1" v-model="scope.row.cuQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.cuQty }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="feSaleQty" label="铁精粉销售计划量" width="140" header-align="center"
                    align="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-if="scope.row.feSaleQty1" v-model="scope.row.feSaleQty" size="mini"></el-input>
                        <div v-else @click="editHandleClick(scope.row, scope.column)">{{ scope.row.feSaleQty }}</div>
                    </template>
                </el-table-column>


                <el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
                    <template #default="scope">
                        <el-button plain type="success" @click="handleSave(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-dialog :close-on-click-modal="false"  :title="dialogName" v-model="dialogVisible" width="1420px"
            top="5vh" @open="openDialog">
            <el-table :data="addTableData">
                <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
                <el-table-column v-if="true" prop="planDate" label="计划日期" width="150" header-align="center"
                    align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.planDate" type="date" style="width: 100%;"
                            value-format="YYYY-MM-DD" format="YYYY-MM-DD" placeholder="请选择"></el-date-picker>
                    </template>
                </el-table-column>
                <!-- <el-table-column v-if="true" prop="resoQty" label="资源获取计划量" width="130" header-align="center"
                    align="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.resoQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column> -->
                <el-table-column v-if="true" prop="jfQty" label="精粉类计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.jfQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="fjfQty" label="非精粉类计划量" width="130" header-align="center"
                    align="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.fjfQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="jzQty" label="金召矿计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.jzQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="jdQty" label="金鼎矿计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.jdQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="zyQty" label="正元矿计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.zyQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="feQty" label="铁精粉计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.feQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="cuQty" label="铜精粉计划量" width="120" header-align="center" align="right"
                    show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.cuQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="feSaleQty" label="铁精粉销售计划量" width="140" header-align="center"
                    align="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input v-model="scope.row.feSaleQty" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>


                <el-table-column label="操作" header-align="center" align="center" width="170px">
                    <template #default="scope">
                        <el-button plain type="warning" @click="addHandleCopy(scope.row)">复制</el-button>
                        <el-button plain type="danger" @click="addHandleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button color="#626aef" @click="addPlan">添加计划</el-button>
                    <el-button type="success" @click="addHandleSave">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <ImportExcel ref="ImportExcelRef" :url="importUrl" :formData="importExcelformData"
            @importSuccess="importSuccess">
        </ImportExcel>
    </div>
</template>

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

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

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import { el } from 'element-plus/es/locales.mjs';
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    handleSearch()
})
//导入
import ImportExcel from '@/components/ImportExcel.vue'
const ImportExcelRef = ref(null)
const importUrl = ref('pla/ProdBeneDay/importExcel')
const importExcelformData = ref({
    fId: ''
})

/**
 *   查询
 */




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

const getTableData = () => {
    var url = 'pla/ProdBeneDay/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
            tableData.value.forEach(element => {
                element.planDate1 = false
                element.resoQty1 = false
                element.jzQty1 = false
                element.jdQty1 = false
                element.zyQty1 = false
                element.feQty1 = false
                element.cuQty1 = false
                element.feSaleQty1 = false
                element.jfQty1 = false
                element.fjfQty1 = false
            })
            console.log(tableData.value)
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
/**
 *   查询
 */

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


/**
 * 新增
 */
const addTableData = ref([
    {
        planDate: '',
        resoQty: '',
        jzQty: '',
        jdQty: '',
        zyQty: '',
        feQty: '',
        cuQty: '',
        feSaleQty: '',
        jfQty: '',
        fjfQty: ''
    }
])
const addPlan = () => {
    addTableData.value.push({
        planDate: '',
        resoQty: '',
        jzQty: '',
        jdQty: '',
        zyQty: '',
        feQty: '',
        cuQty: '',
        feSaleQty: '',
        jfQty: '',
        fjfQty: ''
    })
}
const addHandleDelete = (row) => {
    addTableData.value.splice(addTableData.value.indexOf(row), 1)
}
const addHandleCopy = (row) => {
    addTableData.value.push({
        planDate: row.planDate,
        resoQty: row.resoQty,
        jzQty: row.jzQty,
        jdQty: row.jdQty,
        feQty: row.feQty,
        zyQty: row.zyQty,
        cuQty: row.cuQty,
        feSaleQty: row.feSaleQty,
        jfQty: row.jfQty,
        fjfQty: row.fjfQty
    })
}
const dialogVisible = ref(false)


const dialogName = ref('新增')
const handleAdd = () => {
    dialogName.value = '新增'
    dialogVisible.value = true
}
/**
 * 新增
 */


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

const openDialog = () => {
}
const addHandleSave = () => {
    // 校验表单
    let isValid = true;
    addTableData.value.forEach((row, index) => {
        const requiredFields = ['planDate', 'jzQty', 'jdQty', 'zyQty', 'feQty', 'cuQty', 'feSaleQty', 'jfQty', 'fjfQty'];
        for (const field of requiredFields) {
            const value = row[field];
            if (!value) {
                isValid = false;
                ElMessage.error(`第 ${index + 1} 行输入错误，不能为空`);
                break;
            }
            if (field !== 'planDate' && (!/^\d+(\.\d+)?$/.test(value) || value.length > 30)) {
                isValid = false;
                ElMessage.error(`第 ${index + 1} 行输入错误，请输入有效数字`);
                break;
            }
        }
    });
    if (!isValid) {
        return;
    }
    // 保存数据
    var url = 'pla/ProdBeneDay/addPlan'
    var param = {
        json: JSON.stringify(addTableData.value),
        dept: localStorage.getItem('dept'),
        userCode: localStorage.getItem('userCode'),
        userName: localStorage.getItem('userName')
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            getTableData()
            dialogVisible.value = false
        } else {
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
};
const handleSave = (row) => {

    // 校验表单
    let isValid = true;

    const requiredFields = ['planDate', 'jzQty', 'jdQty', 'zyQty', 'feQty', 'cuQty', 'feSaleQty', 'jfQty', 'fjfQty'];
    for (const field of requiredFields) {
        const value = row[field];
        if (!value && value !== 0) {
            isValid = false;
            console.log(field);
            ElMessage.error(`输入错误，不能为空`);
            break;
        }
        if (field !== 'planDate' && (!/^\d+(\.\d+)?$/.test(value) || value.length > 30)) {
            isValid = false;
            ElMessage.error(`输入错误，请输入有效数字`);
            break;
        }
    }


    if (!isValid) {
        return;
    }
    var url = 'pla/ProdBeneDay/save'
    var param = {
        json: JSON.stringify(row),
        dept: localStorage.getItem('dept'),
        userCode: localStorage.getItem('userCode'),
        userName: localStorage.getItem('userName')
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            getTableData()
        } else {
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {
    dialogName.value = '编辑'
    dialogVisible.value = true
    form.value = row
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    )
        .then(() => {
            var url = 'pla/ProdBeneDay/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 = () => {
    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 = 'pla/ProdBeneDay/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 = () => {
    if (multipleSelection.value.length != 1) {
        ElMessage({
            type: 'warning',
            message: '请选择一条数据编辑!'
        })
        return
    }
    handleEdit(multipleSelection.value[0])
}

//编辑
const editHandleClick = (row, column) => {
    console.log(column)
    if (column.property == 'resoQty') {
        row.resoQty1 = true
    } else if (column.property == 'planDate') {
        row.planDate1 = true
    } else if (column.property == 'jzQty') {
        row.jzQty1 = true
    } else if (column.property == 'jdQty') {
        row.jdQty1 = true
    } else if (column.property == 'zyQty') {
        row.zyQty1 = true
    } else if (column.property == 'feQty') {
        row.feQty1 = true
    } else if (column.property == 'cuQty') {
        row.cuQty1 = true
    } else if (column.property == 'feSaleQty') {
        row.feSaleQty1 = true
    } else if (column.property == 'jfQty') {
        row.jfQty1 = true
    } else if (column.property == 'fjfQty') {
        row.fjfQty1 = true
    }
}
const editHandleBlur = (row) => {
    row.resoQty1 = false
}

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

const handleDownload = () => {
    console.log('handleDownload')
    location.href = import.meta.env.VITE_BASE_API +
        '/framework/Common/downloadFileFtpByName?fId=TEMPLATES&fileName=' + '选矿生产日计划.xlsx'
}


const importSuccess = () => {
    ImportExcelRef.value.close()
}

const handleImport = () => {
    ImportExcelRef.value.open()
}
const handleExport = () => {
    console.log('handleExport')
}

</script>

<style></style>