<template>
    <div>
        <SearchBox ref="searchBarRef" :formName="search" :formData="query" @showPopupUser="showPop" showResetButton
            @reset="reset" />
        <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="true" prop="produceDt" label="日期" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="prodShift" label="班次" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="prodGrp" label="班组" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <!-- <el-table-column v-if="true" prop="typeCode" label="记录类型，RC,WF,DK,CS,XS,HS(入厂，外翻，倒矿，粗石，细石，回收矿）" -->
                <!-- <el-table-column v-if="true" prop="typeCode" label="记录类型" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column> -->
                <!-- <el-table-column v-if="true" prop="typeDes" label="记录类型说明，入厂，外翻，倒矿，粗石，细石，回收矿" width="1500" -->
                <!-- <el-table-column v-if="true" prop="typeDes" label="记录类型说明" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column> -->
                <!-- <el-table-column v-if="true" prop="materialCd" label="物料编码" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column> -->
                <!-- <el-table-column v-if="true" prop="materialNm" label="物料名称" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="valueWgt" label="重量" width="100" header-align="center" align="right"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="materialRes" label="物料来源" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="materialType" label="物料类别" width="100" header-align="center"
                    align="center" 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-dialog :close-on-click-modal="false" draggable title="编辑" v-model="dialogVisible" width="1200px" top="5vh"
            @open="openDialog">
            <el-form :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <el-card style=" margin-bottom: 5px; height: 70px;">
                    <el-row :gutter="60">
                        <el-col span="6">
                            <el-form-item label="生产日期" prop="produceDt">
                                <el-date-picker v-model="form.produceDt" type="date" style="width: 190px;"
                                    value-format="YYYY-MM-DD" format="YYYY-MM-DD"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col span="6">
                            <el-form-item label="班次" prop="prodShift">
                                <el-select v-model="form.prodShift" placeholder="请选择班次" style="width: 190px;">
                                    <el-option v-for="option in optionShiftList" :key="option.dicName"
                                        :label="option.dicName" :value="option.dicName" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col span="6">
                            <el-form-item label="班组" prop="prodGrp">
                                <el-input v-model="form.prodGrp" clearable style="width: 190px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>

                <el-card style=" margin-bottom: 5px; ">
                    <el-table :data="addTableData">
                        <el-table-column v-if="true" prop="materialCd" label="物料编码" width="150" header-align="center"
                            align="right" show-overflow-tooltip>
                            <template #default="scope">
                                <el-input v-model="scope.row.materialCd" readonly></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="materialNm" label="物料名称" width="150" header-align="center"
                            align="right" show-overflow-tooltip>
                            <template #default="scope">
                                <el-input v-model="scope.row.materialNm" readonly>
                                    <template #append>
                                        <el-button :icon="Search" @click="itemDialog(scope.$index)" />
                                    </template>
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="typeDes" label="记录类型" width="150" header-align="center"
                            align="right" show-overflow-tooltip>
                            <template #default="scope">
                                <!-- <el-input v-model="scope.row.typeDes" placeholder="请输入"></el-input> -->
                                <el-select v-model="scope.row.typeDes" placeholder="请选择">
                                    <el-option label="入厂" value="入厂" />
                                    <el-option label="外翻" value="外翻" />
                                    <el-option label="倒矿" value="倒矿" />
                                    <el-option label="粗石" value="粗石" />
                                    <el-option label="细石" value="细石" />
                                    <el-option label="回收矿" value="回收矿" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="valueWgt" label="重量" width="150" header-align="center"
                            align="right" show-overflow-tooltip>
                            <template #default="scope">
                                <el-input v-model="scope.row.valueWgt" placeholder="请输入"></el-input>
                            </template>
                        </el-table-column>

                        <el-table-column v-if="true" prop="materialType" label="物料类别" width="170" header-align="center"
                            align="right" show-overflow-tooltip>
                            <template #default="scope">
                                <!-- <el-input v-model="scope.row.materialType" placeholder="请输入"></el-input> -->
                                <el-select v-model="scope.row.materialType" placeholder="请选择">
                                    <el-option label="自产矿" value="自产矿" />
                                    <el-option label="外购矿" value="外购矿" />
                                    <el-option label="外购粉矿" value="外购粉矿" />
                                    <el-option label="成品矿" value="成品矿" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="materialRes" label="物料来源" width="200" header-align="center"
                            align="right" show-overflow-tooltip>
                            <template #default="scope">
                                <el-input v-model="scope.row.materialRes" placeholder="请输入"></el-input>
                            </template>
                        </el-table-column>


                        <el-table-column label="操作" header-align="center" align="center" width="140px">
                            <template #default="scope">
                                <el-button plain type="danger" @click="addHandleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
                <!-- <el-form-item label="记录类型说明，入厂，外翻，倒矿，粗石，细石，回收矿"> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button color="#626aef" @click="addMaterial">添加物料</el-button>
                    <el-button type="success" @click="addHandleSave(ruleFormRef)">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <Popup_base_wl ref="PopupRefTwo" @receive-from-child="retuWl"></Popup_base_wl>
        <Popup_base_wl ref="PopupRef" @receive-from-child="retu"></Popup_base_wl>
    </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()
    getDic()
})
/**
 *   查询物料
 */
import Popup_base_wl from "@/views/bas/Popup_base_wl.vue";
import { Search } from '@element-plus/icons-vue'
import { List } from 'echarts'

const PopupRef = ref(null)
const dataIndex = ref(0)
const itemDialog = (index) => {
    console.log("index", index)
    dataIndex.value = index
    PopupRef.value.open()
}
const retu = (val) => {
    console.log("val", val)
    addTableData.value[dataIndex.value].materialCd = val.itemCd
    addTableData.value[dataIndex.value].materialNm = val.itemNm
}
/**
 *   查询物料
 */


// 数据字典
const optionShiftList = ref([])
const getDic = () => {
    var url = 'framework/Common/querySelector'
    var param = {
        type: 'PRD_OPER_SHIFT'
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            optionShiftList.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}

/**
 *   查询
 */




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

const getTableData = () => {
    var url = 'prd/WeightInputVert/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 currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(20)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const addHandleDelete = (row) => {
    addTableData.value.splice(addTableData.value.indexOf(row), 1)
}
const addMaterial = () => {
    addTableData.value.push({
        typeDes: '',
        materialCd: '',
        materialNm: '',
        valueWgt: '',
        materialRes: '',
        materialType: ''
    })
}
const addTableData = ref([{
    typeDes: '',
    materialCd: '',
    materialNm: '',
    valueWgt: '',
    materialRes: '',
    materialType: ''
}])
const dialogVisible = ref(false)
const form = ref({
    produceDt: '',
    prodShift: '',
    prodGrp: '',
    // typeDes: '',
    // materialCd: '',
    // materialNm: '',
    // valueWgt: '',
    // materialRes: '',
    // materialType: ''
})
const ruleFormRef = ref()
const rules = reactive({
    produceDt: [{
        required: true,
        message: '请输入日期',
        trigger: 'change' | 'blur'
    }],
    prodShift: [{
        required: true,
        message: '请输入班次',
        trigger: 'change' | 'blur'
    }],
    prodGrp: [{
        required: true,
        message: '请输入班组',
        trigger: 'change' | 'blur'
    }],
})

const handleAdd = () => {
    form.value = {
        produceDt: '',
        prodShift: '',
        prodGrp: '',
        // typeDes: '',
        // materialCd: '',
        // materialNm: '',
        // valueWgt: '',
        // materialRes: '',
        // materialType: ''
    }
    addTableData.value = [{
        typeDes: '',
        materialCd: '',
        materialNm: '',
        valueWgt: '',
        materialRes: '',
        materialType: ''
    }]
    dialogVisible.value = true
}
/**
 * 新增
 */


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

const openDialog = () => {
}
const addHandleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'prd/WeightInputVert/addSave'
            var param = {
                json: JSON.stringify(form.value),
                list: JSON.stringify(addTableData.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 handleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'prd/WeightInputVert/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) => {
    var url = 'prd/WeightInputVert/queryAll'
    var param = {
        params: JSON.stringify(row)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            addTableData.value = response.data.data
            console.log(addTableData.value)
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
    dialogVisible.value = true
    form.value = row
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    )
        .then(() => {
            var url = 'prd/WeightInputVert/remove'
            var param = {
                id: row.id,
                produceDt: row.produceDt,
                prodShift: row.prodShift,
                prodGrp: row.prodGrp,
            }
            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/WeightInputVert/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>