<template>
    <div id="newDevicesCode">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="80px"
        >
            <el-form-item label="关键字" prop="keyWord">
                <el-input
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="typeList">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column
                label="机具名称"
                align="center"
                prop="typeName"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="规格型号"
                align="center"
                prop="specificationType"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="采购时间"
                align="center"
                prop="purchaseTime"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="采购数量"
                align="center"
                prop="purchaseNum"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="验收数量"
                align="center"
                prop="checkNum"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="绑定数量"
                align="center"
                prop="bindNum"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.bindNum > 0">{{
                        scope.row.bindNum
                    }}</span>
                    <span v-else>0</span>
                </template>
            </el-table-column>
            <el-table-column
                label="状态"
                align="center"
                prop="status"
                width="180"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.status == 0">待入库</span>
                    <span v-if="scope.row.status == 1">已入库</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        icon="el-icon-view"
                        v-if="scope.row.status == 0 || scope.row.status == 1"
                        @click="handleBindDetails(scope.row)"
                    >
                        查看
                    </el-button>
                    <el-button
                        size="mini"
                        type="primary"
                        v-if="scope.row.bindNum < scope.row.checkNum"
                        @click="handleCode(scope.row)"
                    >
                        绑定编码
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加或修改参数配置对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            v-if="open"
            width="90%"
            append-to-body
            :close-on-click-modal="false"
        >
            <el-table v-loading="loading" :data="codeList" max-height="600">
                <el-table-column label="序号" align="center" type="index" />
                <el-table-column
                    width="160"
                    align="center"
                    prop="typeName"
                    label="机具名称"
                    show-overflow-tooltip
                />
                <el-table-column
                    width="160"
                    align="center"
                    label="规格型号"
                    show-overflow-tooltip
                    prop="specificationType"
                />
                <el-table-column label="设备编码" align="center" prop="maCode">
                    <template slot-scope="scope">
                        <template v-if="!isDetail">
                            <span>{{ scope.row.specificationType + '-' }}</span>
                            <el-input
                                clearable
                                v-model="scope.row.tempCode"
                                :ref="`inputRef_${scope.$index}`"
                                style="width: 260px; margin: 0 5px"
                            />
                            <el-button
                                type="text"
                                icon="el-icon-bottom"
                                v-if="
                                    scope.row.tempCode &&
                                    scope.$index !== codeList.length - 1
                                "
                                @click="
                                    onFillDownwards(
                                        scope.$index,
                                        scope.row.tempCode,
                                    )
                                "
                            ></el-button>
                        </template>

                        <span v-else>{{ scope.row.maCode }}</span>
                    </template>
                </el-table-column>

                <el-table-column
                    width="160"
                    align="center"
                    label="是否为固定资产"
                    show-overflow-tooltip
                    v-if="isDetail"
                >
                    <template slot-scope="{ row }">
                        <el-tag
                            size="small"
                            type="success"
                            v-if="row.fixCode == 0"
                            >是</el-tag
                        >
                        <el-tag size="small" type="warning" v-else>否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="固定资产编码"
                    align="center"
                    prop="assetsCode"
                >
                    <template slot-scope="scope">
                        <template v-if="!isDetail">
                            <el-checkbox
                                v-model="scope.row.fixCode"
                                @change="onChangeCheckBox($event, scope.$index)"
                                >是否为固定资产</el-checkbox
                            >
                            <el-input
                                clearable
                                v-model="scope.row.assetsCode"
                                :disabled="!scope.row.fixCode"
                                :ref="`assetsCode_${scope.$index}`"
                                style="width: 260px; margin-left: 5px"
                            />
                        </template>
                        <span v-else>{{ scope.row.assetsCode || '-' }}</span>
                    </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="() => (open = false)">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getMacodeList,
    editPurchaseMacode,
    getBindCodeDetails,
} from '@/api/store/newBuy'

export default {
    name: 'NewDevicesCode',
    props: {
        codingTaskId: {
            type: [String, Number],
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            taskId: '',
            // 表格数据
            typeList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                keyWord: '',
                typeName: undefined,
            },
            isDetail: false,
            surplusNoBindNum: 0,
            codingLoading: false,
        }
    },
    mounted() {
        this.taskId = this.codingTaskId
        this.getList()
    },
    methods: {
        /** 查询列表 */
        async getList() {
            this.loading = true
            this.queryParams.taskId = this.taskId
            const { data: res } = await getMacodeList(this.queryParams)
            this.typeList = res
            this.loading = false
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /* 编码按钮操作 */
        handleCode(row) {
            this.open = true
            this.title = '编码生成'
            this.isDetail = false

            const { checkNum, typeName, specificationType, typeId, taskId } =
                row
            let codeList = []
            for (let i = 0; i < checkNum; i++) {
                const codeItems = {
                    tempCode: '', // 临时编码  (确定提交时再与规格型号合并)
                    maCode: '', // 机具编码
                    assetsCode: '', // 固定资产编码
                    fixCode: false, // 是否为固定资产  0是 1否  (先设置Boolean值，默认为非固定资产，提交时再转)
                    typeId,
                    taskId,
                    typeName,
                    specificationType,
                }
                codeList.push(codeItems)
            }
            this.codeList = codeList
        },

        /* 提交按钮 */
        submitForm() {
            let isCode = false
            try {
                this.codeList.forEach((e, i) => {
                    if (e.tempCode === '') {
                        this.$modal.msgError(
                            `序号为${i + 1}的编码为空，请编码后再确定提交`,
                        )
                        this.$refs[`inputRef_${i}`].focus()
                        isCode = true
                        throw new Error()
                    }
                    this.codeList.forEach((e, i) => {
                        if (e.fixCode && e.assetsCode === '') {
                            this.$modal.msgError(
                                `序号为${
                                    i + 1
                                }的编码机具已选为固定资产，固定资产编码不能为空`,
                            )
                            this.$refs[`assetsCode_${i}`].focus()
                            isCode = true
                            throw new Error()
                        }
                    })
                })
            } catch (error) {}

            if (isCode) return
            const codeListParams = JSON.parse(JSON.stringify(this.codeList))
            codeListParams.forEach((e) => {
                e.maCode = e.specificationType + e.tempCode
                e.fixCode ? (e.fixCode = '0') : (e.fixCode = '1')
                return e
            })

            this.codingLoading = true

            editPurchaseMacode(codeListParams)
                .then((res) => {
                    if (res.data && res.data.length > 0) {
                        try {
                            res.data.forEach((e, i) => {
                                if (e.maCode === null) {
                                    this.$modal.msgError(
                                        `序号为${i + 1}的编码重复，请重新编码`,
                                    )
                                    this.codeList[i].tempCode = ''
                                    this.$refs[`inputRef_${i}`].focus()
                                    throw new Error()
                                }
                            })
                        } catch (error) {}
                    } else {
                        this.$modal.msgSuccess('编码绑定成功')
                        this.open = false
                        this.getList()
                    }
                })
                .finally(() => {
                    this.codingLoading = false
                })
        },

        async handleBindDetails(row) {
            this.isDetail = true
            this.title = '编码绑定详情'
            getBindCodeDetails({
                taskId: row.taskId,
                typeId: row.typeId,
            }).then((res) => {
                this.codeList = res.data
                this.open = true
            })
        },

        /* 正则处理编码后缀 */
        extractNumber(str) {
            const matches = str.match(/\d+/g) // 匹配所有数字
            return matches ? matches.map(Number) : [] // 转换为数字数组
        },

        /* 向下填充事件 */
        onFillDownwards(index, code) {
            const codeNumList = this.extractNumber(code)
            let newStr = code
            codeNumList.forEach((e) => {
                newStr = newStr.replace(e, e * 1 + 1)
            })
            this.codeList[index + 1].tempCode = newStr
        },

        /* 复选框选择事件 */
        onChangeCheckBox(val, index) {
            if (!val) {
                this.codeList[index].assetsCode = ''
            }
        },
    },
}
</script>
