<template>
    <el-dialog title="新增" append-to-body :modelValue="openShow" width="70%" @close="closeDialog" fullscreen>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-row :gutter="24">
                <!-- 按照日期自动生成  202511101037  看之前的逻辑-->
                <!-- <el-col :span="8">
                    <el-form-item label="入库单号:" prop="userId3">
                        {{ruleForm.sirCode}}
                    </el-form-item>
                </el-col> -->
                <el-col :span="8">
                    <el-form-item label="入库时间:" prop="inOutDate">
                        <el-date-picker v-model="ruleForm.inOutDate" :clearable="false" type="date" placeholder="选择日期"
                            style="width: 100%;">
                        </el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="入库仓库:" prop="shId">
                        <el-select v-model="ruleForm.shId" placeholder="请选择" @change="changeWarehouse">
                            <el-option v-for="item in warehouseList" :key="item.id" :label="item.shName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="入库人员:" prop="keeper">
                        <el-select v-model="ruleForm.keeper" placeholder="请选择">
                            <el-option v-for="item in keeperList" :key="item.id" :label="item.realName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="入库原因:" prop="warehousingReason">
                        <el-select v-model="ruleForm.warehousingReason" placeholder="请选择">
                            <el-option v-for="item in warehousingReasonOption" :key="item.value" :label="item.value" :value="item.warehousingReason"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div style="margin-bottom: 12px;" v-if="moldAddMore">
            <el-button type="primary" @click="addTable">插入一行</el-button>
            <el-button type="danger" @click="delTable">删除行</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="sirCode" label="入库单号" align="center" width="150">
                <template #default="scope">
                    {{scope.row.sirCode}}
                </template>
            </el-table-column>
            <el-table-column prop="boCode" label="物料编号" align="center" width="200">
                <template #header>
                    <span><i style="color:red">*</i>物料编号</span>
                </template>
                <template #default="scope">
                    <el-select v-model="scope.row.goodsCode" placeholder="请选择" @change="(val) => changeGoods(val,scope.$index)">
                        <el-option v-for="item in goodsList" :key="item.id" :label="item.goodsCode" :value="item.goodsCode"></el-option>
                        <!-- <el-option label="玻璃饼" value="2">
                        </el-option> -->
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="物料名称" align="center" width="120"></el-table-column>
            <el-table-column prop="materialModel" label="型号/牌号" align="center" width="120"></el-table-column>
            <el-table-column prop="checkNo" label="质量编号" align="center" width="200">
                <template #default="scope">
                    <el-input v-model="scope.row.checkNo" @blur="(e) => changeCheckNo(e,scope.$index)"></el-input>
                    <!-- <el-select v-model="scope.row.goodsId" placeholder="请选择">
                        <el-option label="质量编号一" value="1">
                        </el-option>
                        <el-option label="质量编号二" value="2">
                        </el-option>
                    </el-select> -->
                </template>
            </el-table-column>
            <el-table-column prop="piNo" label="批次号" align="center" width="200">
                <template #default="scope">
                    <el-input v-model="scope.row.piNo" placeholder="请输入" />
                </template>
            </el-table-column>
            <el-table-column prop="stovePiNo" label="炉批号" align="center" width="200">
                <template #default="scope">
                    <el-input v-model="scope.row.stovePiNo" placeholder="请输入" />
                </template>
            </el-table-column>
            <!-- <el-table-column prop="goodsName" label="物料名称" align="center">
                <template #default="scope">
                    <el-input v-model="scope.row.goodsName" placeholder="请输入" />
                </template>
            </el-table-column> -->
            <el-table-column prop="quantityLevel" label="生产标识" align="center" width="200">
                <template #default="scope">
                    <el-input v-model="scope.row.quantityLevel"></el-input>
                    <!-- <el-select v-model="scope.row.goodsId" placeholder="请选择">
                        <el-option label="生产标识一" value="1">
                        </el-option>
                        <el-option label="生产标识二" value="2">
                        </el-option>
                    </el-select> -->
                </template>
            </el-table-column>
            <el-table-column prop="scrapCycle" label="到期日期" align="center" width="150">
                <template #default="scope">
                    <el-date-picker v-model="scope.row.scrapCycle" type="date" placeholder="请选择"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:100%" />
                </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" align="center" width="200px">
                <template #header>
                    <span><i style="color:red">*</i>数量</span>
                </template>
                <template #default="scope">
                    <el-input-number v-model="scope.row.quantity" controls-position="right" @change="(e) => changeQuantity(e,scope.$index)"
                        :min="1"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="slId" label="库位号" align="center" width="200">
                <template #header>
                    <span > <i style="color:red">*</i>库位号</span>
                </template>
                <template #default="scope">
                    <el-select v-model="scope.row.slId" placeholder="请选择">
                        <el-option v-for="item in scope.row.locationList" :key="item.id" :label="item.location" :value="item.id"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" align="center" width="200">
                <template #default="scope">
                    <el-input-number style="width:90%;" v-model="scope.row.unitPrice" controls-position="right" @change="(val) => changePrice(val,scope.$index)"
                        ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="sirMoney" label="金额" align="center" width="200">
                <template #default="scope">
                    <el-input-number style="width:90%;" disabled v-model="scope.row.sirMoney" controls-position="right" 
                        ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="woCode" label="车间订单号" align="center" width="200">
                 <!-- <template #header>
                    <span > <i style="color:red">*</i>车间订单号</span>
                </template> -->
                <!-- 物料是玻璃饼的时候 车间订单号必填 -->
                <template #default="scope">
                    <el-input v-model="scope.row.woCode" @blur="(val) => changeWoCode(val,scope.$index)"></el-input>
                </template>
            </el-table-column>

        </el-table>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script>
import {dateFormat} from '@/utils/date'
import {getGoodsOutList,getCode,getWarehouseList,getKeeperList,getBatch,getLocationList,getGlassPieList,addOtherIn,getPrice} from "@/api/storeManagement/otherReceiving"
export default {
    props: {
        showDialog: {
            type: Boolean,
            default: false
        },
        moldAddMore: {
            type: Boolean,
            default: false
        },
        buyCycle: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            openShow: false,
            ruleForm: {
                userId: '1',
                inOutDate: dateFormat(new Date(),'yyyy-MM-dd'),
                declareDate: '',
                needDate: '',
                buyDept: '',
                warehousingReason: null,
            },
            warehousingReasonOption: [
                { warehousingReason: 1, value: '余料退库' },
                { warehousingReason: 2, value: '库转移' },
                { warehousingReason: 3, value: '计划取消退库' },
                { warehousingReason: 4, value: '领用入库' },
                // { warehousingReason: 5, value: '料头入库' },
                { warehousingReason: 6, value: '物料入库' },
                { warehousingReason: 7, value: '生产入库' },

            ],
            keeperList:[],
            wareList:[],
            goodsList:[],
            rules: {
                shId:[{required:true,message:'请选择入库仓库',trigger:'blur'}],
                keeper:[{required:true,message:'请选择入库人员',trigger:'blur'}],
                warehousingReason:[{required:true,message:'请选择入库原因',trigger:'blur'}]
            },
            warehouseList:[],
            tableData: [],
            boCode: null,
        }
    },
    mounted() {
        this.openShow = this.showDialog
        this.getBasic()
        this.getGoodsList()
        this.getKeeper()
    },
    methods: {
        getKeeper(){
            getKeeperList().then(res =>{
                this.keeperList = res.data.data
            })
        },
        async getBasic(){
            const code = await getCode()
            console.log('code--------',code)
            this.boCode = code.data.data.sirCode
            const res = await getWarehouseList()
            this.warehouseList = res.data.data.records
            console.log('res--------',res)
        },
        // 获取物料信息
        getGoodsList(){
            getGoodsOutList().then(res =>{
                this.goodsList = res.data.data.records
            })
        },
        // 切换仓库
        changeWarehouse(val){
            if(this.tableData.length > 0){
                if(this.tableData.length == 1){
                    this.tableData[0].slId = ''
                    getLocationList({
                        shId:this.ruleForm.shId,
                        goodsCode:this.tableData[0].goodsCode
                    }).then(res =>{
                        this.tableData[0].locationList = res.data.data
                    })
                }else{
                    this.tableData.map(item =>{
                        item.goodsCode = ''
                        item.goodsName = ''
                        item.goodsId = ''
                        item.materialModel = ''
                        item.slId = ''
                    })
                }
            }
            
        },
        // 切换物料
        changeGoods(val,index){
            let tmp = this.goodsList.find(item => item.goodsCode == val)
            this.tableData[index].goodsName = tmp.goodsName
            this.tableData[index].goodsId = tmp.id
            this.tableData[index].materialModel = tmp.materialModel
            getLocationList({
                shId:this.ruleForm.shId,
                goodsCode:val
            }).then(res =>{
                this.tableData[index].locationList = res.data.data
            })
        },
        // 修改质量编码
        changeCheckNo(e,index){
            console.log('e--------',e)
            console.log('index--------',index)
            getPrice({
                goodsId:this.tableData[index].goodsId,
                checkNo:e.target.value
            }).then(res =>{
                console.log('res-------------',res)
                this.tableData[index].unitPrice = res.data.data
                console.log('this.tableData-----------',this.tableData)
                if(this.tableData[index].quantity >= 0){
                    this.tableData[index].sirMoney = Number(this.tableData[index].quantity) * Number(this.tableData[index].unitPrice)
                }
            })
        },
        // 修改单价
        changePrice(val,index){
            if(this.tableData[index].quantity >=0 && this.tableData[index].unitPrice >=0){
                this.tableData[index].sirMoney = Number(this.tableData[index].quantity) * Number(this.tableData[index].unitPrice)
            }
        },
        // 修改数量
        changeQuantity(e,index){
            if(this.tableData[index].unitPrice >=0 && this.tableData[index].quantity >=0){
                this.tableData[index].sirMoney = Number(this.tableData[index].quantity) * Number(this.tableData[index].unitPrice)
            }
        },
        // 输入车间订单
        changeWoCode(e,index){ 
            console.log('e--------',e)
            console.log('index--------',index)
            getGlassPieList({
                woCode:e.target.value
            }).then(res =>{
                console.log('res--------',res)
            })
        },
        submit() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let hasInvalidRow = false
                    for (let i = 0; i < this.tableData.length; i++) {
                        const row = this.tableData[i]
                        if (!row.goodsCode) {
                            this.$message.error(`第${i + 1}行：请选择物料编号`)
                            hasInvalidRow = true
                            break;
                        }
                        if (!row.quantity || row.quantity <= 0) {
                            this.$message.error(`第${i + 1}行：请输入有效的数量`)
                            hasInvalidRow = true
                            break;
                        }
                        if(!row.slId){
                            this.$message.error(`第${i + 1}行：请选择库位号`)
                            hasInvalidRow = true
                            break
                        }
                        // if (row.goodsId === '2' && !row.buyQty) {
                        //     this.$message.warning(`第${i + 1}行：玻璃饼物料必须填写车间订单号`)
                        //     hasInvalidRow = true
                        //     break
                        // }

                        if(this.ruleForm.warehousingReason == 7 && (!row.woCode || row.woCode == '')){
                            this.$message.error(`第${i + 1}行：请填写车间订单号`)
                            hasInvalidRow = true
                            break
                        }
                    }
                    
                    console.log('form-------',this.ruleForm)
                    console.log('tableData-------',this.tableData)
                    // 校验通过：准备提交数据（过滤无用字段）
                    const submitData = this.tableData.map(row => {
                        const { _select,locationList, ...validData } = row; // 剔除选择状态字段
                        return validData;
                    });
                    let params = {
                        ...this.ruleForm,
                        inoutList:submitData
                    }
                    if (!hasInvalidRow) {
                        this.$refs.ruleForm.resetFields()
                        addOtherIn(params).then(res =>{
                            if(res.data.code === 200){
                                this.$message.success('新增成功')
                                this.tableData = []
                            }
                        })
                    //     this.tableData = []
                    //     this.openShow = true
                    //     this.$message.success('添加成功')
                    }
                } else {
                    this.$message.error('请填写所有必填项')
                    return false
                }
            });
        },
        // 删除一行
        deleteTable(index) {
            this.tableData.splice(index, 1)
        },
        closeDialog() {
            this.openShow = false
            this.$emit('closeDialog')
        },
        // 插入一行
        addTable() {
            if(!this.ruleForm.shId || this.ruleForm.sjId === ''){
                this.$message.error('请选择仓库')
                return
            }
            
            let sirCode = '';
            console.log('this.boCode--------',this.boCode)
            const len = this.tableData;
            if (len.length === 0) {
                sirCode = this.boCode;
            } else {
                const newBoCode = len[len.length - 1].sirCode;
                // const codeArr = newBoCode.split('-');
                // const num = Number(codeArr[1]) + 1;
                // boCode = codeArr[0] + '-' + num;
                sirCode = Number(newBoCode) + 1;
            }
            let piNo = ""
            getBatch().then(res =>{
                console.log('res-----------',res)
                piNo = res.data.msg
                // 新增一行
                const record = { sirCode,piNo,_select:false };
                this.tableData.push(record)
            })
            
        },
        // 删除一行
        delTable(row, index) {
            this.tableData.splice(index, 1)
        },
    }
}
</script>
<style lang="scss" scoped></style>