<template>
    <view>
        <cu-custom :backUrl="'/pages/index/index'" :isBack="true" bgColor="bg-gradual-blue">
            <block slot="content">入库修改</block>
        </cu-custom>

        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules"
            ref="inputForm">
            <u-form-item label="入库编号" borderBottom prop="wareHouseNumber">
                <u--input placeholder="自动生成" v-model="inputForm.wareHouseNumber" disabled></u--input>
            </u-form-item>
            <u-form-item label="入库名称" borderBottom prop="wareHouseName" :required="true">
                <u--input placeholder="请填写入库名称" v-model="inputForm.wareHouseName" :disabled="nodeFlag"></u--input>
            </u-form-item>
            <u-form-item label="经办人" borderBottom prop="handledBy">
                <u--input v-model="inputForm.handledBy" disabled></u--input>
            </u-form-item>
            <u-form-item label="经办部门" borderBottom prop="handledByOfficeName">
                <u--input v-model="inputForm.handledByOfficeName" disabled></u--input>
            </u-form-item>
            <u-form-item label="入库时间" borderBottom prop="wareHouseDate" :required="true">
                <el-date-picker v-model="inputForm.wareHouseDate" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择入库时间" style="width:100%" placement="bottom-start" clearable :disabled="nodeFlag">
                </el-date-picker>
            </u-form-item>

            <purchase-selector :inputForm="inputForm" :disabled="nodeFlag" @selected="handlePurchaseSelected">
            </purchase-selector>

            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea placeholder="请填写备注信息" :rows="4" :maxlength="500" v-model="inputForm.remarks"
                    :disabled="nodeFlag"></u--textarea>
            </u-form-item>

            <view v-if="inputForm.purchaseNo" class="section-wrap">
                <view class="section-title">采购详情</view>
                <view v-for="(item, index) in inputForm.detailInfos" :key="item.id || index" class="detail-card">
                    <view class="detail-card-title">采购明细 {{ index + 1 }}</view>
                    <view class="detail-grid">
                     <!--   <view class="detail-item">
                            <text class="detail-label">采购人</text>
                            <text class="detail-value">{{ item.purchaserAgent || '-' }}</text>
                        </view>
                        <view class="detail-item">
                            <text class="detail-label">采购部门</text>
                            <text class="detail-value">{{ item.procurementOffice || '-' }}</text>
                        </view> -->
                        <view class="detail-item">
                            <text class="detail-label">商品名称</text>
                            <text class="detail-value">{{ item.procurementType || '-' }}</text>
                        </view>
        <!--                <view class="detail-item">
                            <text class="detail-label">商品名称</text>
                            <text class="detail-value">{{ item.tradeName || '-' }}</text>
                        </view> -->
                        <view class="detail-item">
                            <text class="detail-label">品牌</text>
                            <text class="detail-value">{{ item.brand || '-' }}</text>
                        </view>
                        <view class="detail-item">
                            <text class="detail-label">规格</text>
                            <text class="detail-value">{{ item.specification || '-' }}</text>
                        </view>
						<view class="detail-item">
						    <text class="detail-label">单位</text>
						    <text class="detail-value">{{ item.company || '-' }}</text>
						</view>
                        <view class="detail-item">
                            <text class="detail-label">商品数量</text>
                            <text class="detail-value">{{ item.tradeNumber || '-' }}</text>
                        </view>
                     <!--   <view class="detail-item">
                            <text class="detail-label">商品单价</text>
                            <text class="detail-value">{{ item.tradePrice || '-' }}</text>
                        </view>
                        <view class="detail-item">
                            <text class="detail-label">商品总价</text>
                            <text class="detail-value">{{ item.priceSum || '-' }}</text>
                        </view> -->
                    </view>
                </view>
            </view>

            <view class="section-wrap">
                <view class="section-title">入库详情</view>
                <view v-for="(item, index) in inputForm.wareHouse" :key="item.id || index" class="detail-card">
                    <view class="detail-card-head">
                        <view class="detail-card-title">入库明细 {{ index + 1 }}</view>
                    </view>

                  <!-- <u-form-item label="入库人" :prop="'wareHouse[' + index + '].wareHouseMan'" :required="true">
                        <u--input v-model="inputForm.wareHouse[index].wareHouseMan" placeholder="请选择入库人"
                            :disabled="nodeFlag" @focus="openUserPullForm(index)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="入库部门" :prop="'wareHouse[' + index + '].wareHouseManOffice'">
                        <u--input v-model="inputForm.wareHouse[index].wareHouseManOffice" disabled></u--input>
                    </u-form-item> -->
                    <ware-house-goods-selector :rowIndex="index" :inputForm="inputForm" :disabled="nodeFlag"
                        @selected="handleGoodsSelected"></ware-house-goods-selector>

                    <u-form-item label="品牌" :prop="'wareHouse[' + index + '].brand'">
                        <u--input v-model="inputForm.wareHouse[index].brand" disabled></u--input>
                    </u-form-item>
                    <u-form-item label="规格" :prop="'wareHouse[' + index + '].specification'">
                        <u--input v-model="inputForm.wareHouse[index].specification" disabled></u--input>
                    </u-form-item>
					<u-form-item label="单位" :prop="'wareHouse[' + index + '].company'">
					    <u--input v-model="inputForm.wareHouse[index].company" placeholder="请输入单位" disabled
					        @blur="markWareHouseModified(index)"></u--input>
					</u-form-item>
                    <u-form-item label="商品数量" :prop="'wareHouse[' + index + '].tradeNumber'" :required="true">
                        <u--input v-model="inputForm.wareHouse[index].tradeNumber" placeholder="请输入商品数量"
                            :disabled="nodeFlag" @blur="onRowInputBlur(index, 'tradeNumber')"></u--input>
                    </u-form-item>

                    <!-- <u-form-item label="包装规格" :prop="'wareHouse[' + index + '].spec'">
                        <u--input v-model="inputForm.wareHouse[index].spec" placeholder="请输入包装规格" :disabled="nodeFlag"
                            @blur="onRowInputBlur(index, 'spec')"></u--input>
                    </u-form-item> -->
                   <!-- <u-form-item label="商品单价(元)" :prop="'wareHouse[' + index + '].tradePrice'">
                        <u--input v-model="inputForm.wareHouse[index].tradePrice" placeholder="请输入商品单价"
                            :disabled="nodeFlag" @blur="onRowInputBlur(index, 'tradePrice')"></u--input>
                    </u-form-item>
                    <u-form-item label="商品总价" :prop="'wareHouse[' + index + '].priceSum'">
                        <u--input v-model="inputForm.wareHouse[index].priceSum" placeholder="自动计算" disabled></u--input>
                    </u-form-item>
                    <u-form-item label="生产日期" :prop="'wareHouse[' + index + '].produceDate'">
                        <el-date-picker v-model="inputForm.wareHouse[index].produceDate" type="date"
                            placeholder="请选择生产日期" style="width:100%" placement="bottom-start" clearable
                            :disabled="nodeFlag" @change="markWareHouseModified(index)">
                        </el-date-picker>
                    </u-form-item>
                    <u-form-item label="保质期" :prop="'wareHouse[' + index + '].shelfLife'">
                        <view class="shelf-life-wrap">
                            <u--input class="shelf-life-input" v-model="inputForm.wareHouse[index].shelfLife"
                                placeholder="请输入保质期" :disabled="nodeFlag" @blur="markWareHouseModified(index)">
                            </u--input>
                            <jp-picker class="shelf-life-unit" placeholder="单位"
                                v-model="inputForm.wareHouse[index].shelfLifeUnit" :disabled="nodeFlag" rangeKey="label"
                                rangeValue="value" @change="markWareHouseModified(index)" :range="shelfLifeUnitOptions">
                            </jp-picker>
                        </view>
                    </u-form-item>
                    <u-form-item label="实际价格" :prop="'wareHouse[' + index + '].actualPrice'">
                        <u--input v-model="inputForm.wareHouse[index].actualPrice" placeholder="请输入实际价格"
                            :disabled="nodeFlag" @blur="onRowInputBlur(index, 'actualPrice')"></u--input>
                    </u-form-item> -->
                    <u-form-item label="备注" :prop="'wareHouse[' + index + '].remarks'">
                        <u--input v-model="inputForm.wareHouse[index].remarks" placeholder="请输入备注" :disabled="nodeFlag"
                            @blur="markWareHouseModified(index)"></u--input>
                    </u-form-item>
                    <u-form-item label="附件上传">
                        <UploadComponent :uploadUrl="`${uploadUrl}/public-modules-server/oss/file/webUpload/upload`"
                            @onRemove="(file, fileList, fileIndex) => handleRemove(file, fileList, index, fileIndex, 'detail')"
                            @onSuccess="(file, fileList) => handleUploadSuccess(file, fileList, index, 'detail')"
                            :fileList="inputForm.wareHouse[index].fileInfoLost" :limit="3" :isDelete="nodeFlag"
                            :isUpload="nodeFlag">
                        </UploadComponent>
                    </u-form-item>

                    <u-form-item label="" v-if="!nodeFlag">
                        <view class="row-action-group">
                            <el-button style="width: 100%" type="danger" plain @click="removeWareHouseRow(index)">
                                删除明细
                            </el-button>
                        </view>
                    </u-form-item>
                </view>

                <u-form-item label="" v-if="!nodeFlag">
                    <el-button style="width: 100%" type="primary" @click="addWareHouseRow()" plain>新增入库明细</el-button>
                </u-form-item>
            </view>

            <u-form-item label="修改原因" borderBottom prop="updateCause" :required="true">
                <u--textarea placeholder="请填写修改原因" :rows="5" :maxlength="500" v-model="inputForm.updateCause"
                    :disabled="nodeFlag"></u--textarea>
            </u-form-item>

            <u-form-item label="附件">
                <UploadComponent :uploadUrl="`${uploadUrl}/public-modules-server/oss/file/webUpload/upload`"
                    @onRemove="(file, fileList, fileIndex) => handleRemove(file, fileList, '', fileIndex, '')"
                    @onSuccess="(file, fileList) => handleUploadSuccess(file, fileList, '', '')"
                    :fileList="inputForm.files" :limit="3" :isDelete="nodeFlag" :isUpload="nodeFlag">
                </UploadComponent>
            </u-form-item>
        </u--form>

        <user-select ref="userPicker" @input="handleUserSelected"></user-select>
        <ba-tree-picker ref="treePicker" :multiple="false" @select-change="selectTypeChange" title="类型选择"
            :localdata="listData" valueKey="value" textKey="label" childrenKey="children" />
    </view>
</template>

<script>
import { mapState } from 'vuex'
import userSelect from '@/components/user-select/user-select-radio.vue'
import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
import UploadComponent from '@/pages/common/UploadComponent.vue'
import upload from '@/utils/upload.js'
import MaterialTypeService from '@/api/psi/MaterialTypeService'
import MaterialManagementService from '@/api/psi/MaterialManagementService'
import WareHouseService from '@/api/psi/WareHouseService'
import CommonApi from '@/api/common/CommonApi'
import PurchaseSelector from './PurchaseSelector.vue'
import WareHouseGoodsSelector from './WareHouseGoodsSelector.vue'

export default {
    name: 'PsiWareHouseUpdateForm',
    components: {
        userSelect,
        baTreePicker,
        UploadComponent,
        PurchaseSelector,
        WareHouseGoodsSelector
    },
    computed: mapState({
        userInfo: (state) => state.user.userInfo
    }),
    props: {
        businessId: {
            type: String,
            default: ''
        },
        formReadOnly: {
            type: Boolean,
            default: false
        },
        status: {
            type: String,
            default: ''
        },
        isCc: {
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            uploadUrl: upload.UPLOAD_URL,
            nodeFlag: false,
            loading: false,
            listData: [],
            materialList: [],
            currentTypeIndex: -1,
            originalWareHouseRows: [],
            inputForm: this.createInputForm(),
            rules: {
                wareHouseName: [
                    {
                        required: true,
                        message: '入库名称不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                updateCause: [
                    {
                        required: true,
                        message: '修改原因不能为空',
                        trigger: ['blur', 'change']
                    }
                ]
            },
            shelfLifeUnitOptions: [
                { label: '年', value: '年' },
                { label: '月', value: '月' },
                { label: '天', value: '天' }
            ]
        }
    },
    materialTypeService: null,
    materialManagementService: null,
    wareHouseService: null,
    commonApi: null,
    created() {
        this.ensureServices()
        this.loadMaterialTypes()
        this.fillUserInfo()
    },
    watch: {
        businessId: {
            handler() {
                if (this.businessId) {
                    this.init(this.businessId)
                } else {
                    this.resetForm()
                    this.nodeFlag = false
                }
            },
            immediate: true,
            deep: false
        }
    },
    async onLoad(options = {}) {
        const id = options.id || options.businessId || ''
        if (!id) {
            return
        }
        await this.init(id)
        if (options.readOnly === 'true' || options.method === 'view') {
            this.nodeFlag = true
        }
    },
    methods: {
        createInputForm() {
            return {
                id: '',
                procInsId: '',
                processDefinitionId: '',
                status: '',
                wareHouseTotalPrice: '',
                wareHouseActualPrice: '',
                tradeTotalPrice: '',
                fileInfoLost: [],
                purchaseNo: '',
                purchaseId: '',
                handledBy: '',
                handledById: '',
                handledByOffice: '',
                handledByOfficeName: '',
                wareHouseName: '',
                wareHouseNumber: '',
                userId: '',
                wareHouseDate: '',
                remarks: '',
                detailInfos: [],
                wareHouse: [],
                files: [],
                functionFlag: '',
                updateCause: ''
            }
        },
        ensureServices() {
            if (!this.materialTypeService) {
                this.materialTypeService = new MaterialTypeService()
            }
            if (!this.materialManagementService) {
                this.materialManagementService = new MaterialManagementService()
            }
            if (!this.wareHouseService) {
                this.wareHouseService = new WareHouseService()
            }
            if (!this.commonApi) {
                this.commonApi = new CommonApi()
            }
        },
        async loadMaterialTypes() {
            try {
                const data = await this.materialTypeService.cgList()
                this.materialList = data || []
                this.listData = this.buildTree(this.materialList)
            } catch (e) {
                this.materialList = []
                this.listData = []
            }
        },
        fillUserInfo() {
            if (!this.userInfo) {
                return
            }
            this.inputForm.handledBy = this.inputForm.handledBy || this.userInfo.name
            this.inputForm.handledById = this.inputForm.handledById || this.userInfo.id
            this.inputForm.userId = this.inputForm.userId || this.userInfo.id
            this.inputForm.handledByOffice = this.inputForm.handledByOffice || (this.userInfo.officeDTO && this.userInfo.officeDTO.id) || ''
            this.inputForm.handledByOfficeName = this.inputForm.handledByOfficeName || (this.userInfo.officeDTO && this.userInfo.officeDTO.name) || ''
        },
        resetForm() {
            this.inputForm = this.createInputForm()
            this.originalWareHouseRows = []
            this.fillUserInfo()
        },
        async init(id) {
            this.ensureServices()
            this.resetForm()
            this.inputForm.id = id
            this.loading = true
            try {
                let data = await this.wareHouseService.findById(id, this.status)
                if (data && data.status === '5' && this.status === 'taskFormDetail') {
                    try {
                        data = await this.wareHouseService.findLastHiByid(id)
                    } catch (e) {
                    }
                }
                this.inputForm = this.normalizeFormData(this.recover(this.createInputForm(), data))
                if (this.isEmpty(this.inputForm.id)) {
                    this.inputForm.id = id
                }
                this.originalWareHouseRows = this.cloneRows(this.inputForm.wareHouse)
                this.fillUserInfo()
                this.nodeFlag = await this.resolveNodeFlag(data)
                this.calculateDetailTotalPrice()
                this.calculateWareHouseTotals()
            } catch (e) {
                this.nodeFlag = true
            } finally {
                this.loading = false
            }
        },
        async resolveNodeFlag(data) {
            if (this.formReadOnly || this.status === 'taskFormDetail' || this.status === 'testSee') {
                return true
            }
            try {
                const taskName = await this.commonApi.getTaskNameByProcInsId((data && data.procInsId) || this.inputForm.procInsId)
                if (this.isNotEmpty(taskName)) {
                    return taskName !== '发起人重新发起申请'
                }
            } catch (e) {
            }
            return false
        },
        normalizeFormData(data) {
            const form = data || this.createInputForm()
            if (this.isNotEmpty(form.wareHouseDate)) {
                form.wareHouseDate = this.formatDate(form.wareHouseDate)
            }
            form.detailInfos = (form.detailInfos || []).map(item => ({
                ...item,
                fileInfoLost: item.fileInfoLost || [],
                priceSum: this.computePriceSum(item.tradePrice, item.tradeNumber)
            }))
            form.wareHouse = (form.wareHouse || [])
                .filter(item => item.upFlag !== '1' && item.upFlag !== '2')
                .map(item => ({
                    ...item,
                    fileInfoLost: item.fileInfoLost || [],
                    upFlag: item.upFlag || '0',
                    produceDate: this.isNotEmpty(item.produceDate) ? new Date(item.produceDate) : '',
                    priceSum: this.computePriceSum(item.tradePrice, item.tradeNumber)
                }))
            return form
        },
        cloneRows(rows) {
            return JSON.parse(JSON.stringify(rows || []))
        },
        buildTree(nodes, parentId = '0') {
            const tree = []
            for (const node of nodes || []) {
                if (String(node.infoType || node.info_type || '') === '1') {
                    continue
                }
                if (node.parentId === parentId) {
                    const children = this.buildTree(nodes, node.id)
                    if (children.length) {
                        node.children = children
                    }
                    tree.push(node)
                }
            }
            return tree
        },
        isEmpty(value) {
            if (value === null || value === undefined) {
                return true
            }
            if (typeof value === 'string' && value.trim() === '') {
                return true
            }
            if (Array.isArray(value) && value.length === 0) {
                return true
            }
            return false
        },
        isNotEmpty(value) {
            return !this.isEmpty(value)
        },
        resolveBusinessId() {
            return this.inputForm.id || this.businessId || ''
        },
        ensureBusinessId() {
            const id = this.resolveBusinessId()
            if (this.isNotEmpty(id) && this.isEmpty(this.inputForm.id)) {
                this.inputForm.id = id
            }
            return id
        },
        computePriceSum(price, number) {
            if (this.isEmpty(price) || this.isEmpty(number)) {
                return ''
            }
            const amount = parseFloat(price || 0) * parseFloat(number || 0)
            if (Number.isNaN(amount)) {
                return ''
            }
            return amount.toFixed(2)
        },
        calculateDetailTotalPrice() {
            const total = (this.inputForm.detailInfos || []).reduce((sum, item) => {
                return sum + parseFloat(item.priceSum || 0)
            }, 0)
            this.inputForm.tradeTotalPrice = total ? total.toFixed(2) : ''
        },
        calculateWareHouseTotals() {
            const totalPrice = (this.inputForm.wareHouse || []).reduce((sum, item) => {
                return sum + parseFloat(item.priceSum || 0)
            }, 0)
            const totalActual = (this.inputForm.wareHouse || []).reduce((sum, item) => {
                return sum + parseFloat(item.actualPrice || 0)
            }, 0)
            this.inputForm.wareHouseTotalPrice = totalPrice ? totalPrice.toFixed(2) : ''
            this.inputForm.wareHouseActualPrice = totalActual ? totalActual.toFixed(2) : ''
        },
        getOriginalWareHouseRow(row) {
            const rowId = row && row.id
            if (this.isEmpty(rowId)) {
                return null
            }
            return (this.originalWareHouseRows || []).find(item => item.id === rowId) || null
        },
        isWareHouseRowChanged(row, originalRow) {
            if (!row || !originalRow) {
                return false
            }
            const fields = [
                'wareHouseManId',
                'wareHouseMan',
                'deptId',
                'wareHouseManOffice',
                'wareHouseTypeId',
                'wareHouseType',
                'tradeName',
                'tradeNumber',
                'company',
                'brand',
                'specification',
                'spec',
                'tradePrice',
                'actualPrice',
                'produceDate',
                'shelfLife',
                'shelfLifeUnit',
                'remarks'
            ]
            return fields.some(field => {
                let nextValue = row[field]
                let oldValue = originalRow[field]
                if (field === 'produceDate') {
                    nextValue = this.formatDate(nextValue)
                    oldValue = this.formatDate(oldValue)
                }
                return String(nextValue || '') !== String(oldValue || '')
            })
        },
        markChangedRowsForSubmit() {
            ;(this.inputForm.wareHouse || []).forEach((row, index) => {
                if (this.isEmpty(row.id) || this.isNotEmpty(row.sourceId)) {
                    return
                }
                const originalRow = this.getOriginalWareHouseRow(row)
                if (this.isWareHouseRowChanged(row, originalRow)) {
                    this.$set(this.inputForm.wareHouse[index], 'upFlag', '1')
                }
            })
        },
        normalizeWareHouseAmounts() {
            ;(this.inputForm.wareHouse || []).forEach((row, index) => {
                this.$set(this.inputForm.wareHouse[index], 'priceSum', this.computePriceSum(row.tradePrice, row.tradeNumber))
            })
            this.calculateWareHouseTotals()
        },
        openUserPullForm(index) {
            if (this.nodeFlag) {
                return
            }
            this.$refs.userPicker.open(index, 'wareHouse')
        },
        handleUserSelected(data, index, type) {
            if (type !== 'wareHouse') {
                return
            }
            this.patchWareHouseRow(index, {
                wareHouseManId: data.id,
                wareHouseMan: data.label,
                wareHouseManOffice: data.parentLabel,
                deptId: data.parentId
            })
        },
        openTypePicker(index) {
            if (this.nodeFlag) {
                return
            }
            this.currentTypeIndex = index
            this.$refs.treePicker._show(index)
        },
        selectTypeChange(ids, names, index) {
            this.patchWareHouseRow(index, {
                wareHouseType: names,
                wareHouseTypeId: ids[0],
                tradeName: '',
                tradePrice: '',
                tradeNumber: '',
                priceSum: '',
                company: '',
                brand: '',
                specification: '',
                spec: '1',
                actualPrice: '',
                surplusNumber: ''
            })
        },
        async handlePurchaseSelected(row) {
            try {
                const data = await this.materialManagementService.findById(row.id)
                if (this.isNotEmpty(this.inputForm.purchaseNo) && this.inputForm.purchaseNo !== data.purchaseNo) {
                    this.inputForm.wareHouse = []
                }
                this.inputForm.purchaseNo = data.purchaseNo || row.purchaseNo
                this.inputForm.purchaseId = row.id
                this.inputForm.detailInfos = (data.detailInfos || []).map(item => ({
                    ...item,
                    fileInfoLost: item.fileInfoLost || [],
                    priceSum: this.computePriceSum(item.tradePrice, item.tradeNumber)
                }))
                this.calculateDetailTotalPrice()
                this.calculateWareHouseTotals()
            } catch (e) {
                uni.showToast({
                    title: '采购详情加载失败',
                    icon: 'none'
                })
            }
        },
        handleGoodsSelected({ index, item }) {
            const tradeName = item.tradeName || item.name || ''
            this.patchWareHouseRow(index, {
                wareHouseType: tradeName,
                wareHouseTypeId: item.id || '',
                tradeName,
                goodsName: tradeName,
                brand: item.brand || '',
                specification: item.specification || '',
                company: item.company || '',
                spec: '1'
            })
        },
        createWareHouseRow() {
            return {
                id: '',
                wareHouseManId: this.userInfo && this.userInfo.id,
                wareHouseMan: this.userInfo && this.userInfo.name,
                wareHouseManOffice: this.userInfo && this.userInfo.officeDTO && this.userInfo.officeDTO.name,
                deptId: this.userInfo && this.userInfo.officeDTO && this.userInfo.officeDTO.id,
                wareHouseType: '',
                wareHouseTypeId: '',
                tradeName: '',
                tradeNumber: '',
                company: '',
                brand: '',
                specification: '',
                spec: '1',
                tradePrice: '',
                priceSum: '',
                produceDate: '',
                shelfLife: '',
                shelfLifeUnit: '',
                actualPrice: '',
                remarks: '',
                fileInfoLost: [],
                upFlag: '0',
                sourceId: ''
            }
        },
        addWareHouseRow() {
            this.inputForm.wareHouse.push(this.createWareHouseRow())
            this.calculateWareHouseTotals()
        },
        patchWareHouseRow(index, patch, markChanged = true) {
            const row = (this.inputForm.wareHouse || [])[index] || {}
            const nextRow = {
                ...row,
                ...patch
            }
            if (markChanged) {
                if (this.isNotEmpty(row.id) && this.isEmpty(row.sourceId)) {
                    nextRow.upFlag = '1'
                } else {
                    nextRow.upFlag = row.upFlag || '0'
                }
            }
            if (Object.prototype.hasOwnProperty.call(patch, 'tradePrice') || Object.prototype.hasOwnProperty.call(patch, 'tradeNumber')) {
                nextRow.priceSum = this.computePriceSum(nextRow.tradePrice, nextRow.tradeNumber)
            }
            this.$set(this.inputForm.wareHouse, index, nextRow)
            this.calculateWareHouseTotals()
        },
        markWareHouseModified(index) {
            const row = (this.inputForm.wareHouse || [])[index]
            if (!row) {
                return
            }
            if (this.isNotEmpty(row.id) && this.isEmpty(row.sourceId) && row.upFlag !== '1') {
                this.$set(this.inputForm.wareHouse[index], 'upFlag', '1')
            }
        },
        removeWareHouseRow(index) {
            this.inputForm.wareHouse.splice(index, 1)
            this.calculateWareHouseTotals()
        },
        onRowInputBlur(index, field) {
            const row = (this.inputForm.wareHouse || [])[index]
            if (!row) {
                return
            }
            let value = row[field]
            if (['tradeNumber', 'tradePrice', 'actualPrice'].includes(field)) {
                value = this.formatNumberInput(value)
            }
            if (field === 'spec') {
                value = this.formatIntegerInput(value)
            }
            this.patchWareHouseRow(index, {
                [field]: value
            })
        },
        formatNumberInput(inputValue, decimalLimit = 2) {
            if (this.isEmpty(inputValue)) {
                return ''
            }
            const valueText = String(inputValue)
            if (!/^\d*\.?\d*$/.test(valueText)) {
                return ''
            }
            let value = valueText.replace(/[^\d.]/g, '')
            const dotIndex = value.indexOf('.')
            if (dotIndex !== -1) {
                const substr = value.substr(dotIndex + 1)
                if (substr.indexOf('.') !== -1) {
                    value = value.substr(0, dotIndex + 1) + substr.replace(/\./g, '')
                }
            }
            if (dotIndex !== -1) {
                const integerPart = value.substring(0, dotIndex)
                const decimalPart = value.substring(dotIndex + 1, dotIndex + 1 + decimalLimit)
                value = integerPart + '.' + decimalPart
            }
            return value
        },
        formatIntegerInput(inputValue) {
            if (this.isEmpty(inputValue)) {
                return ''
            }
            return String(inputValue).replace(/[^\d]/g, '')
        },
        handleUploadSuccess(file, fileList, index, type) {
            if (type === 'detail') {
                this.inputForm.wareHouse[index].fileInfoLost = fileList
                this.markWareHouseModified(index)
            } else {
                this.inputForm.files = fileList
            }
        },
        handleRemove(file, fileList, lineIndex, fileIndex, type) {
            if (type === 'detail') {
                this.inputForm.wareHouse[lineIndex].fileInfoLost.splice(fileIndex, 1)
                this.markWareHouseModified(lineIndex)
            } else {
                this.inputForm.files.splice(fileIndex, 1)
            }
        },
        formatDate(date) {
            if (this.isEmpty(date)) {
                return ''
            }
            const dateNew = new Date(date)
            if (Number.isNaN(dateNew.getTime())) {
                return ''
            }
            const year = dateNew.getFullYear()
            const month = `${dateNew.getMonth() + 1}`.padStart(2, '0')
            const day = `${dateNew.getDate()}`.padStart(2, '0')
            return `${year}-${month}-${day}`
        },
        toSubmitData() {
            const businessId = this.ensureBusinessId()
            this.normalizeWareHouseAmounts()
            this.markChangedRowsForSubmit()
            const data = JSON.parse(JSON.stringify(this.inputForm))
            data.id = data.id || businessId
            data.wareHouseDate = this.formatDate(this.inputForm.wareHouseDate)
            data.tradeTotalPrice = this.normalizeOptionalNumber(data.tradeTotalPrice)
            data.wareHouseTotalPrice = this.normalizeOptionalNumber(data.wareHouseTotalPrice)
            data.wareHouseActualPrice = this.normalizeOptionalNumber(data.wareHouseActualPrice)
            data.wareHouse = (this.inputForm.wareHouse || []).map(item => ({
                ...JSON.parse(JSON.stringify(item)),
                produceDate: this.formatDate(item.produceDate),
                priceSum: this.normalizeOptionalNumber(this.computePriceSum(item.tradePrice, item.tradeNumber)),
                tradeTotalPrice: this.normalizeOptionalNumber(item.tradeTotalPrice),
                actualPrice: this.normalizeOptionalNumber(item.actualPrice)
            }))
            return data
        },
        normalizeOptionalNumber(value) {
            if (this.isEmpty(value)) {
                return null
            }
            return value
        },
        validateBaseForm() {
            if (this.isEmpty(this.inputForm.wareHouseDate)) {
                this.$message.error('入库时间不能为空')
                return false
            }
            return true
        },
        validateBusinessId() {
            if (this.isEmpty(this.ensureBusinessId())) {
                this.$message.error('入库数据ID为空，请返回列表重新进入')
                return false
            }
            return true
        },
        validateWareHouseRows() {
            if (this.isEmpty(this.inputForm.wareHouse)) {
                return true
            }
            const rows = this.inputForm.wareHouse
            for (let i = 0; i < rows.length; i++) {
                const row = rows[i]
                const lineNo = i + 1
                if (this.isEmpty(row.wareHouseMan)) {
                    this.$message.error(`入库详情第${lineNo}行请选择入库人`)
                    return false
                }
                if (this.isEmpty(row.wareHouseType)) {
                    this.$message.error(`入库详情第${lineNo}行请选择入库类型`)
                    return false
                }
                if (this.isEmpty(row.tradeName)) {
                    this.$message.error(`入库详情第${lineNo}行请填写商品名称`)
                    return false
                }
                if (this.isEmpty(row.tradeNumber)) {
                    this.$message.error(`入库详情第${lineNo}行请填写商品数量`)
                    return false
                }
            }
            for (let i = 0; i < rows.length; i++) {
                for (let j = i + 1; j < rows.length; j++) {
                    if (rows[i].wareHouseTypeId === rows[j].wareHouseTypeId &&
                        rows[i].tradeName === rows[j].tradeName) {
                        this.$message.warning('入库详情中，同种入库类型的商品名称只能输入一条')
                        return false
                    }
                }
            }
            return true
        },
        async saveForm(callback) {
            try {
                if (!this.validateBaseForm()) {
                    return
                }
                if (!this.validateBusinessId()) {
                    return
                }
                await this.$refs.inputForm.validate()
                if (!this.validateWareHouseRows()) {
                    return
                }
                this.loading = true
                this.calculateDetailTotalPrice()
                this.calculateWareHouseTotals()
                const submitData = this.toSubmitData()
                submitData.status = '1'
                submitData.functionFlag = ''
                this.inputForm.status = '1'
                const data = await this.wareHouseService.save(submitData)
                callback(data.businessTable, data.businessId, submitData)
            } finally {
                this.loading = false
            }
        },
        async startForm(callback) {
            this.loading = true
            try {
                const id = this.ensureBusinessId()
                if (this.isNotEmpty(id)) {
                    const data = await this.wareHouseService.findById(id)
                    if (this.isNotEmpty(data.status) && !['0', '1', '3', '5'].includes(data.status)) {
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error('invalid status')
                    }
                }
                await this.startFormTrue(callback)
            } finally {
                this.loading = false
            }
        },
        async startFormTrue(callback) {
            if (!this.validateBaseForm()) {
                return
            }
            if (!this.validateBusinessId()) {
                return
            }
            await this.$refs.inputForm.validate()
            if (!this.validateWareHouseRows()) {
                return
            }
            this.calculateDetailTotalPrice()
            this.calculateWareHouseTotals()
            const submitData = this.toSubmitData()
            submitData.status = '2'
            submitData.functionFlag = 'start'
            this.inputForm.status = '2'
            this.inputForm.functionFlag = 'start'
            const data = await this.wareHouseService.save(submitData)
            this.inputForm.id = data.businessId
            callback(data.businessTable, data.businessId, submitData)
        },
        async reapplyForm(callback) {
            this.loading = true
            try {
                const id = this.ensureBusinessId()
                if (this.isEmpty(id)) {
                    this.$message.error('入库数据ID为空，请返回列表重新进入')
                    throw new Error('missing business id')
                }
                const data = await this.wareHouseService.findById(id)
                if (data.status !== '4') {
                    this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                    throw new Error('invalid status')
                }
                await this.startFormTrue(callback)
            } finally {
                this.loading = false
            }
        },
        async agreeForm(callback) {
            this.loading = true
            try {
                if (!this.validateBaseForm()) {
                    return
                }
                if (!this.validateBusinessId()) {
                    return
                }
                await this.$refs.inputForm.validate()
                if (!this.validateWareHouseRows()) {
                    return
                }
                this.calculateDetailTotalPrice()
                this.calculateWareHouseTotals()
                const submitData = this.toSubmitData()
                submitData.status = '5'
                submitData.functionFlag = 'agree'
                this.inputForm.status = '5'
                this.inputForm.functionFlag = 'agree'
                const data = await this.wareHouseService.save(submitData)
                callback(data.businessTable, data.businessId, submitData)
            } finally {
                this.loading = false
            }
        },
        async updateStatusById(type, callback) {
            this.loading = true
            try {
                const id = this.ensureBusinessId()
                if (this.isEmpty(id)) {
                    this.$message.error('入库数据ID为空，请返回列表重新进入')
                    throw new Error('missing business id')
                }
                if (type === 'reject' || type === 'reback') {
                    const data = await this.wareHouseService.findById(id)
                    if (data.status !== '2') {
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error('invalid status')
                    }
                    const status = type === 'reject' ? '4' : '3'
                    this.inputForm.status = status
                    await this.wareHouseService.updateStatusById({
                        status,
                        id
                    })
                    callback()
                } else if (type === 'hold') {
                    const data = await this.wareHouseService.findById(id)
                    if (data.status !== '4') {
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error('invalid status')
                    }
                    await this.wareHouseService.backSourceData(id)
                    callback()
                }
            } finally {
                this.loading = false
            }
        }
    }
}
</script>

<style scoped>
.section-wrap {
    margin-top: 24rpx;
}

.section-title {
    margin-bottom: 16rpx;
    padding-left: 8rpx;
    font-size: 30rpx;
    font-weight: 700;
    color: #1f2937;
    border-left: 6rpx solid #2979ff;
}

.detail-card {
    margin-bottom: 20rpx;
    padding: 24rpx;
    background: #fff;
    border-radius: 20rpx;
    box-shadow: 0 10rpx 30rpx rgba(15, 23, 42, 0.05);
}

.detail-card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;
}

.detail-card-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #0f172a;
}

.detail-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16rpx;
}

.detail-item {
    display: flex;
    flex-direction: column;
    padding: 18rpx 20rpx;
    background: #f8fafc;
    border-radius: 16rpx;
}

.detail-label {
    font-size: 22rpx;
    color: #64748b;
}

.detail-value {
    margin-top: 8rpx;
    font-size: 26rpx;
    line-height: 1.5;
    color: #0f172a;
    word-break: break-all;
}

.row-action-group {
    display: flex;
    gap: 16rpx;
    width: 100%;
}

.shelf-life-wrap {
    display: flex;
    width: 100%;
    gap: 16rpx;
}

.shelf-life-input {
    flex: 1;
    min-width: 0;
}

.shelf-life-unit {
    flex: 0 0 128rpx;
    width: 128rpx;
}


@media (max-width: 768px) {
    .detail-grid {
        grid-template-columns: repeat(1, minmax(0, 1fr));
    }
}
</style>
