<template>
    <!-- 往来单位 新增、编辑 表单组件 -->
    <div>
        <el-form ref="formBindCodeRef" :model="bindForm" :rules="bindCodeRules" :inline="true">
            <el-form-item label="编码前缀" prop="exCode">
                <el-input v-model="bindForm.exCode" />
            </el-form-item>

            <el-form-item label="后缀范围" prop="suffixOneCode">
                <el-input v-model="bindForm.suffixOneCode" maxlength="99999999" />
            </el-form-item>

            <el-form-item prop="suffixTwoCode">
                <el-input v-model="bindForm.suffixTwoCode" maxlength="99999999" />
            </el-form-item>

            <el-form-item label="本次检验时间">
                <el-date-picker
                    v-model="bindForm.thisCheckTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" plain @click="fillingCodeList">填充</el-button>
                <el-button type="danger" plain @click="onSubmit">编码提交</el-button>
            </el-form-item>
        </el-form>

        <!-- <el-row class="surplus-code">
                剩余待编码数量：<span style="color: red">{{
                    surplusNoBindNum
                }}</span>
        </el-row>-->
        <el-table :data="codeList" height="600" border>
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="物资名称" align="center" prop="materialName" show-overflow-tooltip />
            <el-table-column
                label="规格型号"
                align="center"
                prop="specificationCode"
                show-overflow-tooltip
            />
            <el-table-column label="物资编号" align="center" prop="maCode" show-overflow-tooltip>
                <template slot-scope="{row}">
                    <el-input
                        :ref="`inputRef-${row.id}`"
                        v-model="row.maCode"
                        οninput="value=value.replace(/[^0-9.]/g,'')"
                        maxlength="24"
                    ></el-input>
                </template>
            </el-table-column>
            <el-table-column label="出厂编号" align="center">
                <template slot-scope="{row}">
                    <el-input v-model="row.productionCode" maxlength="50"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="本次检验时间" align="center" prop="assetsCode">
                <template slot-scope="{row}">
                    <el-date-picker
                        v-model="row.thisCheckTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                    />
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="160"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="delCode(scope.$index)"
                        v-if="scope.$index !== 0"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button
                    type="primary"
                    @click="submitForm"
                    v-if="!isDetail"
                    :loading="codingLoading"
                    >确 定</el-button
                >
                <el-button @click="cancel">取 消</el-button>
        </div>-->
    </div>
</template>

<script>
import { submitCodeBindApi } from '@/api/purchase/binding'
export default {
    name: 'FormStorage',
    props: {
        rowData: {
            type: Object,
            default: () => null,
        },
    },
    created() {
        console.log(this.rowData, 'this.rowData')

        const {
            materialName,
            specificationCode,
            id,
            detailId,
            typeId,
        } = this.rowData
        this.initRowData = {
            materialName,
            specificationCode,
            id,
            detailId,
            typeId,
            maCode: '',
            productionCode: '',
            thisCheckTime: '',
        }
        this.codeList.push(this.initRowData)
    },
    mounted() {},
    data() {
        return {
            // 表单数据源
            bindForm: {
                exCode: '',
                suffixOneCode: '',
                suffixTwoCode: '',
                thisCheckTime: '',
            },
            initRowData: {},
            // 校验规则
            bindCodeRules: {
                exCode: [
                    { required: true, message: '请输入', trigger: 'blur' },
                ],
                suffixOneCode: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    {
                        pattern: /^[1-9][0-9]*$/,
                        message: '请输入大于0且不能以0开头的正整数',
                    },
                ],
                suffixTwoCode: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    {
                        pattern: /^[1-9][0-9]*$/,
                        message: '请输入大于0且不能以0开头的正整数',
                    },
                ],
            },
            // 列表数据源
            codeList: [],
        }
    },
    methods: {
        /** 填充按钮 */
        fillingCodeList() {
            // 1. 先校验后缀范围等是否输入
            this.$refs['formBindCodeRef'].validate(valid => {
                if (valid) {
                    console.log('校验通过--')
                    // 2. 判断后缀范围第二个值是否大于第一个值
                    if (
                        parseInt(this.bindForm.suffixTwoCode) <
                        parseInt(this.bindForm.suffixOneCode)
                    ) {
                        this.$message.error(
                            '后缀范围第二个值不能小于第一个值！',
                        )
                        return
                    }

                    // 3. 通过后走编码逻辑
                    this.codeList = []
                    this.codeList.push(this.initRowData)

                    let suffixOneCode = parseInt(this.bindForm.suffixOneCode)
                    let suffixTwoCode = parseInt(this.bindForm.suffixTwoCode)
                    let sumNum = suffixTwoCode - suffixOneCode + 1

                    for (let i = 0; i < sumNum; i++) {
                        if (i === 0) {
                            this.codeList[0].maCode = suffixOneCode
                            this.codeList[0].thisCheckTime = this.bindForm.thisCheckTime
                            
                            continue
                        }
                        let obj = {
                            materialName: this.initRowData.materialName,
                            specificationCode: this.initRowData.specificationCode,
                            id: this.initRowData.id,
                            detailId: this.initRowData.detailId,
                            typeId: this.initRowData.typeId,
                            maCode: suffixOneCode + i,
                            thisCheckTime: this.bindForm.thisCheckTime,
                        }
                        this.codeList.push(obj)
                    }

                    console.log(this.codeList, '处理后的数据')

                    this.codeList.forEach(e => {
                        e.maCode =
                            this.bindForm.exCode + this.intiCode(e.maCode)
                    })
                }
            })
        },
        /** 处理编码 */
        intiCode(code) {
            if (code < 10) {
                return `000${code}`
            } else if (code < 100) {
                return `00${code}`
            } else if (code < 1000) {
                return `0${code}`
            } else {
                return code
            }
        },
        /** 编码列表删除 */
        delCode(index) {
            console.log(index, '索引')
            this.codeList.splice(index, 1)
        },
        /** 确认按钮 */
        async onSubmit() {
            let isCode = false
            try {
                this.codeList.forEach((e, index) => {
                    if (!e.maCode) {
                        this.$message.error(
                            `序号${index + 1}的物资未编码，请输入编码`,
                        )
                        isCode = true
                        throw new Error()
                    }
                })
            } catch (error) {}

            if (isCode) return
            //  1. 掉后台接口
            console.log(this.codeList, 'this.codeList')

            const params = {
                dtoList: this.codeList,
            }
            const res = await submitCodeBindApi(params)
            console.log(res, 'res')
            if (res.code === 200) {
                this.$message.success(`编码绑定成功！`)

                //this.$emit('closeDialog', true)
            } else {
                this.$message.error(`${res.msg}`)
            }
        },
    },
}
</script>

<style scoped>
::v-deep .el-select {
    width: 100%;
}
::v-deep .el-form-item__label {
    font-weight: normal;
}
</style>
