<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form status-icon inline v-model="query">
                <el-row :span="24">
                    <el-col :span="5">
                        <el-form-item label="货物名称">
                            <el-input placeholder="请输入" v-model="query.hwmc" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="发货单位">
                            <el-input placeholder="请输入" v-model="query.fhdwmc" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="收货单位">
                            <el-input placeholder="请输入" v-model="query.shdwmc" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="创建日期" prop="">
                            <el-date-picker v-model="query.rossTime" type="daterange" align="right" unlink-panels
                                range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                                style="width: 403px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <el-card :body-style="cardBodyStyle">
            <el-row :span="24">

                <el-button type="primary" plain @click="handleSearch">查询</el-button>
                <el-button type="success" plain @click="handleImport">导入Excel</el-button>
                <el-button type="primary" plain @click="handleAdd">新增</el-button>
                <el-button type="danger" plain @click="handleRemove">删除</el-button>
                <el-button type="primary" plain @click="handleUpdate">更正</el-button>
            </el-row>
        </el-card>
        <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 align="center" label="序号" prop="no" sortable></el-table-column>
                <el-table-column align="center" label="车号" prop="carno" sortable></el-table-column>
                <el-table-column align="center" label="收货单位" prop="shdw" sortable></el-table-column>
                <el-table-column align="center" label="发货单位" prop="fhdw" sortable></el-table-column>
                <el-table-column align="center" label="货物名称" prop="hwmc" sortable></el-table-column>
                <el-table-column align="center" label="毛重" prop="mz" sortable></el-table-column>
                <el-table-column align="center" label="皮重" prop="pz" sortable></el-table-column>
                <el-table-column align="center" label="净重" prop="jz" sortable></el-table-column>
                <el-table-column align="center" label="日期" prop="datetime" sortable></el-table-column>
                <el-table-column align="center" label="时间" prop="time" sortable></el-table-column>
            </el-table>
            <el-card :body-style="cardBodyStyle">
                <div style="display: flex;justify-content: space-between; align-items: center;">
                    <div>
                        <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>
                    </div>
                    <div>
                        累计净重: {{ totalJz }} 吨
                    </div>
                </div>
            </el-card>
        </el-card>
        <ImportExcel ref="ImportExcelRef" :url="importUrl" :formData="formData" @importSuccess="importSuccess">
        </ImportExcel>
        <el-dialog width="600px" v-model="dialogVisible" @close="onClose">
            <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                <el-form ref="ruleForm" :model="addparam" :rules="rules" label-width="80px">
                    <el-form-item label="采购状态" prop="ywlxid">
                        <el-select v-model="addparam.ywlxid" placeholder="请选择" style="width: 200px;" clearable
                            @change="handleChange">
                            <el-option label="采购" value="01"></el-option>
                            <el-option label="销售" value="02"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="库房" prop="kufangcd" v-if="showKufang">
                        <el-select v-model="addparam.kufangcd" placeholder="请选择库房" clearable>
                            <el-option v-for="item in kufangs" :key="item.value" :label="item.STORE_NM"
                                :value="item.STORE_CD"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="物料名称" prop="wuliao">
                        <el-input placeholder="请输入物料名称" v-model="addparam.wuliao" style="width: 200px;" clearable
                            @change="handleChangeInput1"></el-input>
                    </el-form-item>
                    <el-form-item label="单位名称" prop="danwei">
                        <el-input placeholder="请输入单位名称" v-model="addparam.danwei" style="width: 200px;" clearable
                            @change="handleChangeInput2"></el-input>
                    </el-form-item>
                    <el-form-item label="计划号" prop="planNumber">
                        <el-select v-model="addparam.planNumber" placeholder="请选择计划号" clearable style="width: 280px;">
                            <el-option v-for="item in PlanNumbers" :key="item.value" :label="item.planNumber"
                                style="width: 650px;" :value="item.planNumber">
                                <template #default>
                                    <div>
                                        <strong>{{ item.planNumber }}</strong> -- {{ item.itemNm }} -- {{
                                            item.TRADE_PARTNER_NAME }} -- {{ item.CONTR_NO }}
                                    </div>
                                </template>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div>
                    <el-button type="primary" @click="handleClose">取消</el-button>
                    <el-button type="success" @click="handleAddBatch(ruleForm)">确定</el-button>
                </div>
            </div>

        </el-dialog>
        <el-dialog width="1300px" v-model="dialogVisible_update" @close="onClose">
            <el-card :body-style="cardBodyStyle">
                <el-form status-icon inline v-model="query_update">
                    <el-row :span="24">
                        <el-col :span="5">
                            <el-form-item label="货物名称">
                                <el-input placeholder="请输入" v-model="query_update.hwmc" clearable style="width:200px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="发货单位">
                                <el-input placeholder="请输入" v-model="query_update.fhdwmc" clearable style="width:200px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="收货单位">
                                <el-input placeholder="请输入" v-model="query_update.shdwmc" clearable style="width:200px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="日期" prop="">
                                <el-date-picker v-model="query_update.addTime" type="datetimerange" align="right"
                                    unlink-panels range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                                    style="width: 403px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
            <el-card :body-style="cardBodyStyle">
                <el-button type="primary" plain @click="handleSearch_jlxx">查询</el-button>
                <el-button type="primary" plain @click="handleRein">重新录入</el-button>
            </el-card>
            <el-table :data="tableData_jlxx" border @selection-change="handleSelectionChange_jlxx">
                <el-table-column type="selection" fixed></el-table-column>
                <el-table-column align="center" label="车号" prop="carno" ></el-table-column>
                <el-table-column align="center" label="计划号" prop="planNumber" ></el-table-column>
                <el-table-column align="center" label="收货单位" prop="shdwmc" ></el-table-column>
                <el-table-column align="center" label="发货单位" prop="fhdwmc" ></el-table-column>
                <el-table-column align="center" label="货物名称" prop="wuzimc" ></el-table-column>
                <el-table-column align="center" label="毛重" prop="mzh" ></el-table-column>
                <el-table-column align="center" label="皮重" prop="pzh" ></el-table-column>
                <el-table-column align="center" label="净重" prop="jzh" ></el-table-column>
                <el-table-column align="center" label="添加时间" prop="addTime"></el-table-column>
            </el-table>
            <el-pagination :current-page="currentPage_update" :page-size="pageSize_update" :page-sizes="pageSizes_update"
                            :total="totalRows_update" background="background" layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange_update" @current-change="handleCurrentChange_update">
                        </el-pagination>
        </el-dialog>


        <el-dialog width="600px" v-model="dialogVisible_updatejlxx" @close="onClose">
            <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                <el-form ref="ruleForm_jlxx" :model="addparam_jlxx" :rules="rules_jlxx" label-width="80px">
                    <el-form-item label="采购状态" prop="ywlxid">
                        <el-select v-model="addparam_jlxx.ywlxid" placeholder="请选择" style="width: 200px;" clearable
                            @change="handleChange_jlxx">
                            <el-option label="采购" value="01"></el-option>
                            <el-option label="销售" value="02"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="库房" prop="kufangcd" v-if="showKufang_jlxx">
                        <el-select v-model="addparam_jlxx.kufangcd" placeholder="请选择库房" clearable>
                            <el-option v-for="item in kufangs" :key="item.value" :label="item.STORE_NM"
                                :value="item.STORE_CD"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="物料名称">
                        <el-input placeholder="请输入物料名称" v-model="addparam_jlxx.wuliao" style="width: 200px;" clearable
                            @change="handleChangeInput1_jlxx"></el-input>
                    </el-form-item>
                    <el-form-item label="单位名称">
                        <el-input placeholder="请输入单位名称" v-model="addparam_jlxx.danwei" style="width: 200px;" clearable
                            @change="handleChangeInput2_jlxx"></el-input>
                    </el-form-item>
                    <el-form-item label="计划号" prop="planNumber">
                        <el-select v-model="addparam_jlxx.planNumber" placeholder="请选择计划号" clearable style="width: 280px;">
                            <el-option v-for="item in PlanNumbers" :key="item.value" :label="item.planNumber"
                                style="width: 650px;" :value="item.planNumber">
                                <template #default>
                                    <div>
                                        <strong>{{ item.planNumber }}</strong> -- {{ item.itemNm }} -- {{
                                            item.TRADE_PARTNER_NAME }} -- {{ item.CONTR_NO }}
                                    </div>
                                </template>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div>
                    <el-button type="primary" @click="handleClose_jlxx">取消</el-button>
                    <el-button type="success" @click="handleAddBatch_jlxx(ruleForm_jlxx)">确定</el-button>
                </div>
            </div>

        </el-dialog>
    </div>

</template>

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

import Popup_sto_config_kf_bx from "@/views/sto/components/Popup_sto_config_kf_bx.vue";
import Popup_sto_config_Qh from "@/views/sto/components/Popup_sto_config_Qh.vue";
import Popup_sto_config_Dw from "@/views/sto/components/Popup_sto_config_Dw.vue";
const visible = ref(false)
const form = ref({})
const returnKf = (val) => {
    form.value.storeIdMB = val.id
    form.value.storeCdMB = val.storeCd
    form.value.storeNmMB = val.storeNm
    form.value.areaCdMB = ''
    console.log(val)
    console.log(form.value)
    debugger
}
const returnQh = (val) => {
    form.value.areaIdMB = val.id
    form.value.areaCdMB = val.areaCd
    console.log(val)
}
const returnDw = (val) => {
    form.value.stackIdMB = val.id
    form.value.stackCdMB = val.stackCd
    console.log(val)
}

const { proxy } = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const importUrl = ref('sci/Test/importConTmpClause')
const ImportExcelRef = ref(null)
const tableData = ref([])
const handleImport = () => {
    ImportExcelRef.value.open()
}
const importSuccess = () => {
    handleSearch()
}
var userName = localStorage.getItem('userDesc')
var userId = localStorage.getItem('userId')
let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode
const formData = ref({
    userId: userId,
    userName: userName,
    deptCode: deptCode
})
const PlanNumbers = ref([])
onMounted(() => {
    handleSearch()
    getKuFang()
})
const handleSearch = () => {
    getTableData()
}
const showKufang = ref(false)
const query = reactive({
    hwmc: '',
    fhdwmc: '',
    shdwmc: '',
    rossTime: ''
})
const getTableData = () => {
    var url = 'sci/Test/query'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            totalRows.value = response.data.data.total
            console.log(response.data.data)
        } else {
            ElMessage.error('操作失败!' + response.data.msg)
        }
    })
}
const addparam = ref({
    planNumber: '',
    ywlxid: '',
    kufangcd: '',
    kufang: '',
    wuliao: '',
    danwei: ''
})
const dialogVisible = ref(false)
// 导入计量按钮
const handleAdd = () => {
    showKufang.value = false
    addparam.value.kufangcd = ''
    addparam.value.planNumber = ''
    addparam.value.ywlxid = ''
    addparam.value.wuliao = ''
    addparam.value.danwei = ''
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要处理的数据!'
        })
        return
    }
    dialogVisible.value = true
    PlanNumbers.value = []
}
// 取消
const handleClose = () => {
    dialogVisible.value = false
}
// 对话框关闭
const onClose = () => {
    handleSearch()
}
const multipleSelection = ref([]);
const totalJz = ref(0);
const handleSelectionChange = (val) => {
    totalJz.value = 0; // 每次重新计算前先清零
    multipleSelection.value = val;
    multipleSelection.value.forEach((item, index) => {
        console.log(item.jz);
        totalJz.value += item.jz; // 累加净重
    });
    // 使用toFixed(2)保留 2 位小数，但结果为字符串类型
    // 使用 parseFloat 将结果转化为数字类型
    totalJz.value = parseFloat(totalJz.value.toFixed(2));
}
// 批量添加
const ruleForm = ref()
const handleAddBatch = () => {
    ruleForm.value.validate((valid) => {
        if (!valid) {
            ElMessage.error('请填写完整信息');
            return;
        } else {
            kufangs.value.forEach((item, index) => {
                if (item.STORE_CD == addparam.value.kufangcd) {
                    addparam.value.kufang = item.STORE_NM
                }
            })
            var ids = []
            multipleSelection.value.forEach((item, index) => {
                ids.push(item.id)
            })
            var url = 'sci/Test/addBatch'
            var param = {
                ids,
                params: JSON.stringify(addparam.value)
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == '0') {
                    ElMessage({
                        type: 'success',
                        message: '操作成功!'
                    })
                    dialogVisible.value = false
                    handleSearch()
                } else {
                    ElMessage.error('操作失败!' + response.data.msg)
                }
            })
        }
    });
}
// 选择计划号
const handleChange = (value) => {
    if (value == '01') {
        showKufang.value = true
    } else {
        showKufang.value = false
    }
    addparam.value.planNumber = ''
    getPlanNumber(value, addparam.value.wuliao, addparam.value.danwei)
}

const handleChangeInput1 = () => {
    getPlanNumber(addparam.value.ywlxid, addparam.value.wuliao, addparam.value.danwei)
}
const handleChangeInput2 = () => {
    getPlanNumber(addparam.value.ywlxid, addparam.value.wuliao, addparam.value.danwei)
}

// 获取计划号
const getPlanNumber = (value, wuliao, danwei) => {
    var url = 'sci/Test/getPlanNumber'
    var param = {
        value,
        wuliao,
        danwei
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            PlanNumbers.value = response.data.data
            console.log(response.data.data)
            console.log(PlanNumbers.value)
        } else {
            ElMessage.error('操作失败!' + response.data.msg)
        }
    })
}

const kufangs = ref([])
// 获取计划号
const getKuFang = () => {
    var url = 'sci/Test/getKuFang'
    var param = {
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            kufangs.value = response.data.data
            console.log(response.data.data)
            console.log(kufangs.value)
        } else {
            ElMessage.error('操作失败!' + response.data.msg)
        }
    })
}
const rules = reactive({
    planNumber: [{
        required: true,
        message: '请选择计划号',
        trigger: 'change' | 'blur'
    }],
    ywlxid: [{
        required: true,
        message: '请选择采购状态',
        trigger: 'change' | 'blur'
    }],
    kufangcd: [{
        required: true,
        message: '请选择库房',
        trigger: 'change' | 'blur'
    }]
})
const rules_jlxx = reactive({
    planNumber: [{
        required: true,
        message: '请选择更正计划号',
        trigger: 'change' | 'blur'
    }],
    ywlxid: [{
        required: true,
        message: '请选择更正采购状态',
        trigger: 'change' | 'blur'
    }],
    kufangcd: [{
        required: true,
        message: '请选择更正库房',
        trigger: 'change' | 'blur'
    }]
})

const currentPage = ref(1)
const pageSizes = ref([20, 30, 50, 80, 100, 200,600,1000,9999])
const pageSize = ref(50)
const totalRows = ref(0)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
const handleRemove = () => {
    var url = 'sci/Test/delete'
    var param = {}
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == '0') {
            ElMessage({
                type: 'success',
                message: '操作成功!'
            })
            handleSearch()
        } else {
            ElMessage.error('操作失败!' + response.data.msg)
        }
    })
}
const dialogVisible_update = ref(false)
const handleUpdate = () => {
    query_update.value.hwmc = ''
    query_update.value.fhdwmc = ''
    query_update.value.shdwmc = ''
    query_update.value.rossTime = ''
    multipleSelection_jlxx.value = []
    dialogVisible_update.value = true
    getJlxx()
}
const query_update = ref({
    hwmc: '',
    fhdwmc: '',
    shdwmc: '',
    addTime: ''
})
const tableData_jlxx = ref([])
const currentPage_update = ref(1)
const pageSizes_update = ref([20, 30, 50, 80, 100, 200,600,1000,9999])
const pageSize_update = ref(50)
const totalRows_update = ref(0)
const handleSizeChange_update = (val) => {
    pageSize_update.value = val
    getJlxx()
}
const handleCurrentChange_update = (val) => {
    currentPage_update.value = val
    getJlxx()
}
const handleSearch_jlxx = () => {
    getJlxx()
}
const getJlxx = () => {
    var url = 'sci/Test/getJlxx'
    var param = {
        page: currentPage_update.value,
        rows: pageSize_update.value,
        params: JSON.stringify(query_update.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData_jlxx.value = response.data.data.records
            totalRows_update.value = response.data.data.total
        } else {
            ElMessage.error('操作失败!' + response.data.msg)
        }
    })
}
const dialogVisible_updatejlxx = ref(false)
const showKufang_jlxx = ref(false)
const handleRein = () => {
    showKufang_jlxx.value = false
    addparam_jlxx.value.kufangcd = ''
    addparam_jlxx.value.planNumber = ''
    addparam_jlxx.value.ywlxid = ''
    addparam_jlxx.value.wuliao = ''
    addparam_jlxx.value.danwei = ''
    if (multipleSelection_jlxx.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要处理的数据!'
        })
        return
    }
    PlanNumbers.value = []
    dialogVisible_updatejlxx.value = true
}
const handleClose_jlxx = () => {
    dialogVisible_updatejlxx.value = false
}
const addparam_jlxx = ref({
    planNumber: '',
    ywlxid: '',
    kufangcd: '',
    kufang: '',
    wuliao: '',
    danwei: ''
})
const multipleSelection_jlxx = ref([]);
const handleSelectionChange_jlxx = (val) => {
    multipleSelection_jlxx.value = val;
}
const ruleForm_jlxx = ref()
const handleAddBatch_jlxx = (ruleForm_jlxx) => {
    ruleForm_jlxx.validate((valid) => {
        if (!valid) {
            ElMessage.error('请填写完整信息');
            return;
        } else {
            kufangs.value.forEach((item, index) => {
                if (item.STORE_CD == addparam_jlxx.value.kufangcd) {
                    addparam_jlxx.value.kufang = item.STORE_NM
                }
            })
            var ids = []
            multipleSelection_jlxx.value.forEach((item, index) => {
                ids.push(item.id)
            })
            var url = 'sci/Test/updateBatch'
            var param = {
                ids,
                params: JSON.stringify(addparam_jlxx.value)
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == '0') {
                    ElMessage({
                        type: 'success',
                        message: '操作成功!'
                    })
                    dialogVisible_updatejlxx.value = false
                    handleSearch()
                } else {
                    ElMessage.error('操作失败!' + response.data.msg)
                }
            })
        }
    });
}

const handleChange_jlxx = (value) => {
    if (value == '01') {
        showKufang_jlxx.value = true
    } else {
        showKufang_jlxx.value = false
    }
    addparam_jlxx.value.planNumber = ''
    getPlanNumber(value, addparam_jlxx.value.wuliao, addparam_jlxx.value.danwei)
}
const handleChangeInput1_jlxx = () => {
    getPlanNumber(addparam_jlxx.value.ywlxid, addparam_jlxx.value.wuliao, addparam_jlxx.value.danwei)
}
const handleChangeInput2_jlxx = () => {
    getPlanNumber(addparam_jlxx.value.ywlxid, addparam_jlxx.value.wuliao, addparam_jlxx.value.danwei)
}
</script>

<style scoped></style>