<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" v-if="!nodeFlag">
            <u-form-item label="报销项" borderBottom prop="reimbursementType" :required="true">
                <u-radio-group v-model="inputForm.reimbursementType">
                    <u-radio :disabled="testFlag" :customStyle="{ marginRight: '16px' }"
                        v-for="(item, index) in radiolist1" :key="index" :label="item.name" :name="item.value"
                        @change="reimbursementTypeChange"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="经办人" borderBottom prop="userName">
                <u--input placeholder='请填写经办人' v-model="inputForm.userName" disabled></u--input>
            </u-form-item>
            <u-form-item label="报销编号" borderBottom prop="no">
                <u--input placeholder='自动生成' v-model="inputForm.no" disabled></u--input>
            </u-form-item>
            <u-form-item label="所属部门" borderBottom prop="departmentName">
                <u--input placeholder='请选择所属部门' v-model="inputForm.departmentName" disabled></u--input>
            </u-form-item>
            <u-form-item label="报销日期" borderBottom prop="reimDate" :required="true">
                <el-date-picker :disabled="testFlag" v-model="inputForm.reimDate" type="date" placeholder="选择日期"
                    style="width:100%" size="default" placement="bottom-start" clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="报销类型" borderBottom prop="sourceType" :required="true">
                <jp-picker v-model="inputForm.sourceType" rangeKey="label" rangeValue="value" :disabled="testFlag"
                    :range="[
                        { label: '项目报销', value: '1' },
                        { label: '报告报销', value: '3' },
                        { label: '其他报销', value: '4' },
                    ]" @input="handlePickerChange"></jp-picker>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks"
                    :disabled="testFlag"></u--textarea>
            </u-form-item>
            <el-row :gutter="15" :key="index_experience" v-for="(item, index_experience) in this.inputForm.detailInfos">
                <el-col :span="24">
                    <u-form-item label="">
                        <u-divider :text="'项目报销详情 ' + (index_experience + 1)"></u-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="报销人" :prop="'detailInfos[' + index_experience + '].userName'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].userName" :disabled="testFlag"
                            @focus="showUserCheck(index_experience, 'project')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销部门" :prop="'detailInfos[' + index_experience + '].deptName'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].deptName" disabled placeholder=""
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销类别" :prop="'detailInfos[' + index_experience + '].typeName'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].typeName" :disabled="testFlag"
                            placeholder="请选择报销类别" @focus="showPicker(index_experience, 'project')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销项目" :prop="'detailInfos[' + index_experience + '].projectName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].projectName" :disabled="testFlag"
                            placeholder="请选择报销项目" @focus="showProject(index_experience, 'project')"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="费用(元)" :prop="'detailInfos[' + index_experience + '].number'" :required="true"
                        :rules="[]">
                        <u-input v-model="inputForm.detailInfos[index_experience].number" :disabled="testFlag"
                            placeholder="" @blur="startValidation(index_experience, 'project')" clearable></u-input>
                    </u-form-item>
                    <u-form-item label="收据张数" :prop="'detailInfos[' + index_experience + '].receiptNumber'" :rules="[
                    ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].receiptNumber" :disabled="testFlag"
                            placeholder="" @blur="numberValidate(index_experience, 'project')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="出差天数" :prop="'detailInfos[' + index_experience + '].days'" :rules="[
                    ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].days" :disabled="testFlag"
                            @blur="daysValidate(index_experience, 'project')" placeholder="" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="内容" :prop="'detailInfos[' + index_experience + '].content'" :rules="[
                    ]">
                        <u--textarea placeholder='请填写备注' :maxlength="500" :disabled="testFlag"
                            v-model="inputForm.detailInfos[index_experience].content" clearable></u--textarea>
                    </u-form-item>
                </el-col>

                <el-col :span="24" style="text-align: center">
                    <u-form-item label="">
                        <el-button style="width: 100%" type="danger" :disabled="testFlag"
                            @click="removeRow(index_experience, 'project')" plain>删除项目报销详情 {{ index_experience +
                                1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="" v-if="inputForm.sourceType === '1'">
                <el-button style="width: 100%" type="primary" :disabled="testFlag" @click="addRow('project')"
                    plain>新增项目报销详情</el-button>
            </u-form-item>
            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.detailInfoReports">
                <el-col :span="24">
                    <u-form-item label="">
                        <u-divider :text="'报告报销详情 ' + (index_experience + 1)"></u-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="报销人" :prop="'detailInfoReports[' + index_experience + '].userName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].userName" :disabled="testFlag"
                            @focus="showUserCheck(index_experience, 'report')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销部门" :prop="'detailInfoReports[' + index_experience + '].deptName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].deptName" disabled
                            placeholder="" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销类别" :prop="'detailInfoReports[' + index_experience + '].typeName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].typeName" :disabled="testFlag"
                            placeholder="请选择报销类别" @focus="showPicker(index_experience, 'report')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销项目" :prop="'detailInfoReports[' + index_experience + '].projectName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].projectName"
                            :disabled="testFlag" placeholder="请选择报销项目" @focus="showProject(index_experience, 'report')"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报告号" :prop="'detailInfoReports[' + index_experience + '].reportNumber'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].reportNumber"
                            :disabled="testFlag" placeholder="请选择报告号" @focus="showReport(index_experience)"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="费用(元)" :prop="'detailInfoReports[' + index_experience + '].number'"
                        :required="true" :rules="[]">
                        <u-input v-model="inputForm.detailInfoReports[index_experience].number" :disabled="testFlag"
                            placeholder="" @blur="startValidation(index_experience, 'report')" clearable></u-input>
                    </u-form-item>
                    <u-form-item label="收据张数" :prop="'detailInfoReports[' + index_experience + '].receiptNumber'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].receiptNumber"
                            :disabled="testFlag" placeholder="" @blur="numberValidate(index_experience, 'report')"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="出差天数" :prop="'detailInfoReports[' + index_experience + '].days'" :rules="[
                    ]">
                        <u--input v-model="inputForm.detailInfoReports[index_experience].days" :disabled="testFlag"
                            placeholder="" @blur="daysValidate(index_experience, 'report')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="内容" :prop="'detailInfoReports[' + index_experience + '].content'" :rules="[
                    ]">
                        <u--textarea placeholder='请填写备注' :maxlength="500" :disabled="testFlag"
                            v-model="inputForm.detailInfoReports[index_experience].content" clearable></u--textarea>
                    </u-form-item>
                </el-col>

                <el-col :span="24" style="text-align: center">
                    <u-form-item label="">
                        <el-button style="width: 100%" type="danger" :disabled="testFlag"
                            @click="removeRow(index_experience, 'report')" plain>删除报告报销详情 {{ index_experience +
                                1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="" v-if="inputForm.sourceType === '3'">
                <el-button style="width: 100%" type="primary" :disabled="testFlag" @click="addRow('report')"
                    plain>新增报告报销详情</el-button>
            </u-form-item>
            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.detailInfoOthers">
                <el-col :span="24">
                    <u-form-item label="">
                        <u-divider :text="'其他报销详情 ' + (index_experience + 1)"></u-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="报销人" :prop="'detailInfoOthers[' + index_experience + '].userName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoOthers[index_experience].userName" :disabled="testFlag"
                            @focus="showUserCheck(index_experience, 'other')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销部门" :prop="'detailInfoOthers[' + index_experience + '].deptName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoOthers[index_experience].deptName" disabled
                            placeholder="" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销类别" :prop="'detailInfoOthers[' + index_experience + '].typeName'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.detailInfoOthers[index_experience].typeName" :disabled="testFlag"
                            placeholder="请选择报销类别" @focus="showPicker(index_experience, 'other')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报销详情" :prop="'detailInfoOthers[' + index_experience + '].projectName'" :rules="[
                    ]">
                        <u--textarea placeholder='请填写报销详情' :maxlength="500" :disabled="testFlag"
                            v-model="inputForm.detailInfoOthers[index_experience].projectName" clearable></u--textarea>
                    </u-form-item>
                    <u-form-item label="费用(元)" :prop="'detailInfoOthers[' + index_experience + '].number'"
                        :required="true" :rules="[]">
                        <u-input v-model="inputForm.detailInfoOthers[index_experience].number" :disabled="testFlag"
                            placeholder="" @blur="startValidation(index_experience, 'other')" clearable></u-input>
                    </u-form-item>
                    <u-form-item label="收据张数" :prop="'detailInfoOthers[' + index_experience + '].receiptNumber'" :rules="[
                    ]">
                        <u--input v-model="inputForm.detailInfoOthers[index_experience].receiptNumber"
                            :disabled="testFlag" placeholder="" @blur="numberValidate(index_experience, 'other')"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="出差天数" :prop="'detailInfoOthers[' + index_experience + '].days'" :rules="[
                    ]">
                        <u--input v-model="inputForm.detailInfoOthers[index_experience].days" :disabled="testFlag"
                            placeholder="" @blur="daysValidate(index_experience, 'other')" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="内容" :prop="'detailInfoOthers[' + index_experience + '].content'" :rules="[
                    ]">
                        <u--textarea placeholder='请填写内容' :maxlength="500" :disabled="testFlag"
                            v-model="inputForm.detailInfoOthers[index_experience].content" clearable></u--textarea>
                    </u-form-item>
                </el-col>

                <el-col :span="24" style="text-align: center">
                    <u-form-item label="">
                        <el-button style="width: 100%" type="danger" @click="removeRow(index_experience, 'other')"
                            :disabled="testFlag" plain>删除其他报销详情 {{ index_experience + 1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="" v-if="inputForm.sourceType === '4'">
                <el-button style="width: 100%" type="primary" :disabled="testFlag" @click="addRow('other')"
                    plain>新增其他报销详情</el-button>
            </u-form-item>
            <el-row :gutter="15" :key="index_experience" v-for="(item, index_experience) in this.inputForm.amountInfos">
                <el-col :span="24">
                    <u-form-item label="">
                        <u-divider :text="'专用发票信息详情 ' + (index_experience + 1)"></u-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="发票代码" :prop="'amountInfos[' + index_experience + '].code'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.amountInfos[index_experience].code" :disabled="testFlag"
                            @blur="onInputCode(index_experience, $event, 'code')" placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="发票号" :prop="'amountInfos[' + index_experience + '].number'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.amountInfos[index_experience].number" :disabled="testFlag"
                            @blur="onInputCode(index_experience, $event, 'number')" placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="金额" :prop="'amountInfos[' + index_experience + '].amount'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.amountInfos[index_experience].amount" :disabled="testFlag"
                            @blur="onInputCode(index_experience, $event, 'amount')" :maxlength="15" placeholder=""
                            clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="税额" :prop="'amountInfos[' + index_experience + '].taxAmount'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.amountInfos[index_experience].taxAmount" :disabled="testFlag"
                            @blur="onInputCode(index_experience, $event, 'taxAmount')" :maxlength="15" placeholder=""
                            clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="价税合计" :prop="'amountInfos[' + index_experience + '].count'" :rules="[
                    ]">
                        <u--input v-model="inputForm.amountInfos[index_experience].count" :disabled="testFlag"
                            placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>

                <el-col :span="24" style="text-align: center">
                    <u-form-item label="">
                        <el-button style="width: 100%" type="danger" :disabled="testFlag"
                            @click="removeRow(index_experience, 'specialInvoice')" plain>删除专用发票信息详情 {{ index_experience
                                +
                                1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="" v-if="inputForm.reimbursementType === '0'">
                <el-button style="width: 100%" type="primary" :disabled="testFlag" @click="addRow('specialInvoice')"
                    plain>新增专用发票信息</el-button>
            </u-form-item>

            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.invoiceReimbursements">
                <el-col :span="24">
                    <u-form-item label="">
                        <u-divider :text="'数电发票信息详情 ' + (index_experience + 1)"></u-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="发票类型" :prop="'invoiceReimbursements[' + index_experience + '].invoiceType'"
                        :required="true" :rules="[
                        ]">
                        <jp-picker v-model="inputForm.invoiceReimbursements[index_experience].invoiceType"
                            :disabled="testFlag" rangeKey="label" rangeValue="value" :range="[
                                { label: '增值税专用发票', value: '01' },
                                { label: '普通发票', value: '02' },
                            ]"></jp-picker>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="发票项目名"
                        :prop="'invoiceReimbursements[' + index_experience + '].invoiceProjectName'" :required="true"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.invoiceReimbursements[index_experience].invoiceProjectName"
                            :disabled="true" placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="发票号" :prop="'invoiceReimbursements[' + index_experience + '].number'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.invoiceReimbursements[index_experience].number" :disabled="true"
                            placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="开票日期" :prop="'invoiceReimbursements[' + index_experience + '].invoiceDate'"
                        :required="true" :rules="[
                        ]">
                        <el-date-picker :disabled="true"
                            v-model="inputForm.invoiceReimbursements[index_experience].invoiceDate" type="date"
                            style="width:100%" size="default" placement="bottom-start" clearable>
                        </el-date-picker>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="开票单位" :prop="'invoiceReimbursements[' + index_experience + '].invoiceUnit'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.invoiceReimbursements[index_experience].invoiceUnit"
                            :disabled="true" placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="金额" :prop="'invoiceReimbursements[' + index_experience + '].amount'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.invoiceReimbursements[index_experience].amount" :disabled="true"
                            placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="税额" :prop="'invoiceReimbursements[' + index_experience + '].taxAmount'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.invoiceReimbursements[index_experience].taxAmount" :disabled="true"
                            placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="价税合计" :prop="'invoiceReimbursements[' + index_experience + '].count'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.invoiceReimbursements[index_experience].count" :disabled="true"
                            placeholder="" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="备注" :prop="'invoiceReimbursements[' + index_experience + '].remarks'" :rules="[
                    ]">
                        <u--textarea placeholder='请填写备注' :maxlength="250" :disabled="testFlag"
                            v-model="inputForm.invoiceReimbursements[index_experience].remarks" clearable></u--textarea>
                    </u-form-item>
                </el-col>

            </el-row>

            <u-form-item label="电子发票附件" v-if="inputForm.reimbursementType === '1'" :required="true">
                <!-- <el-upload class="upload-demo"
                    :action="`http://cpaoa.xgccpm.com/api/public-modules-server/oss/file/disposeXmlFileApp`"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, '电子')"
                    :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList, '电子')"
                    :file-list="inputForm.invoiceReimbursementFiles" :limit="3" :before-upload="beforeUpload">
                    <el-button size="small" type="primary" v-if="!testFlag">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                    <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file, '电子') || testFlag">
                        <span @click="handleFileClick(file)">{{ file.name }}</span>
                        <el-button type="text" @click="handleDelete(file, '电子')">✕</el-button>
                    </template>
</el-upload> -->
                <!-- 新版上传 -->
                <UploadComponent :uploadUrl="`${uploadUrl}/public-modules-server/oss/file/disposeXmlFileApp`"
                    @onRemove="(file, fileList, fileIndex) => handleDelete(file, fileList, '电子', fileIndex)"
                    @onSuccess="(file, fileList) => handleUploadSuccess(file, fileList, '电子')"
                    :fileList="inputForm.invoiceReimbursementFiles" :limit="3" :isDelete="testFlag"
                    :isUpload="testFlag">
                </UploadComponent>
            </u-form-item>
            <u-form-item label="附件">

                <!-- <el-upload class="upload-demo"
                    :action="`http://cpaoa.xgccpm.com/api/public-modules-server/oss/file/webUpload/upload`"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, '')" :file-list="inputForm.files"
                    :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList, '')"
                    :limit="3">
                    <el-button size="small" type="primary" v-if="!testFlag">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                    <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file) || testFlag">
                        <span @click="handleFileClick(file)">{{ file.name }}</span>
                        <el-button type="text" @click="handleDelete(file, '')"> ✕ </el-button>
                    </template>
                </el-upload> -->

                <!-- <button @click="handleUploadClick">上传123</button>
                <xe-upload ref="XeUpload" :options="uploadOptions" @callback="handleUploadCallback"></xe-upload> -->
                <!-- 新版上传 -->
                <UploadComponent :uploadUrl="`${uploadUrl}/public-modules-server/oss/file/webUpload/upload`"
                    @onRemove="(file, fileList, fileIndex) => handleDelete(file, fileList, '', fileIndex)"
                    @onSuccess="(file, fileList) => handleUploadSuccess(file, fileList, '')" :limit="3"
                    :isDelete="testFlag" :isUpload="testFlag" :fileList="inputForm.files">
                </UploadComponent>
            </u-form-item>
        </u--form>
        <user-select ref="userPicker" @input="handleEvent"></user-select>
        <ReimbursementChoose ref="reimbursementChoose" :multiple='false' @select-change="selectChange" title="报销类型选择"
            :localdata="listData" valueKey="value" textKey="label" childrenKey="children" />
        <CwProjectChoose ref="cwProjectChoose" @input="selectProjectChange" title="报销项目选择" />
        <CwReportChoose ref="cwReportChoose" @input="selectReportChange" title="报告号选择" />
    </view>
</template>

<script>
import OSSService from "@/api/sys/OSSService"
import moment from 'moment'
import ReimbursementChoose from './ReimbursementChoose'
import CwProjectChoose from './CwProjectChoose'
import CwReportChoose from './CwReportChoose'
import userSelect from '@/components/user-select/user-select-radio.vue'
import reimbursementApprovalService from '@/api/cw/reimbursementApproval/ReimbursementApprovalService'
import ReimbursementApprovalTypeService from '@/api/cw/reimbursementApproval/ReimbursementApprovalTypeService'
import CommonApi from '@/api/common/CommonApi'
import { mapState, mapMutations, mapActions } from 'vuex'
import UploadComponent from '@/pages/common/UploadComponent.vue';
import upload from '@/utils/upload.js'
export default {
    components: {
        userSelect,
        ReimbursementChoose,
        CwProjectChoose,
        CwReportChoose,
        UploadComponent
    },
    computed: mapState({
        userInfo: (state) => state.user.userInfo,
        avatar: (state) => state.user.avatar
    }),
    data() {
        return {
            uploadUrl: upload.UPLOAD_URL,
            uploadDelFlag: false, //控制数电发票 文件重复上传
            showFileList: [], // 控制每个文件是否显示的数组
            showFileList2: [], // 控制每个文件是否显示的数组
            radiolist1: [{
                name: '普通报销',
                value: '0',
                disabled: false
            }, {
                name: '数电发票报销',
                value: '1',
                disabled: false
            },
            ],
            listData: [],
            reimbursementList: [],
            inputForm: {
                type: '',
                userName: '',
                id: '',
                procInsId: '',
                reimbursementType: '0',
                no: '',
                department: '',
                departmentName: '',
                reimDate: moment(new Date()).format('YYYY-MM-DD'),
                sourceType: '',
                remarks: '',
                detailInfos: [],
                detailInfoReports: [],
                detailInfoOthers: [],
                amountInfos: [],
                files: [], // 附件信息
                invoiceReimbursementFiles: [], // 电子发票附件信息
                invoiceReimbursements: [], // 电子发票信息

            },
            rules: {
                'reimbursementType': [
                    {
                        required: true,
                        message: '报销项不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'reimDate': [
                    {
                        required: true,
                        message: '报销日期不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'sourceType': [
                    {
                        required: true,
                        message: '报销类型不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
            },
            nodeFlag: false,
            testFlag: false,
        }
    },
    ossService: null,
    commonApi: null,
    ReimbursementApprovalTypeService: null,
    // 页面加载时执行
    created() {
        console.log(this.uploadUrl);

        this.ossService = new OSSService()
        this.commonApi = new CommonApi()
        this.reimbursementApprovalTypeService = new ReimbursementApprovalTypeService()
        this.inputForm.userName = this.userInfo.name
        this.inputForm.department = this.userInfo.officeDTO.id
        this.inputForm.departmentName = this.userInfo.officeDTO.name
        // this.bxList()
    },
    props: {
        businessId: {
            type: String,
            default: ''
        },
        formReadOnly: {
            type: Boolean,
            default: false
        },
        status: {
            type: String,
            default: ''
        }
    },
    watch: {
        'businessId': {
            handler(newVal) {
                if (this.businessId) {
                    this.init(this.businessId)
                } else {
                    this.$nextTick(() => {
                        // this.$refs.inputForm.reset()
                    })
                }
            },
            immediate: true,
            deep: false
        }
    },
    methods: {
        async bxList(type) {
            try {
                const data = await this.reimbursementApprovalTypeService.bxList({ like: type });
                this.reimbursementList = data;
            } catch (e) {
                throw e;
            }
        },
        handleEvent(data, index, type) {
            // 在这里处理子组件传递过来的数据
            if (type === 'project') {
                this.inputForm.detailInfos[index].userId = data.id
                this.inputForm.detailInfos[index].userName = data.label
                this.inputForm.detailInfos[index].deptName = data.parentLabel
                this.inputForm.detailInfos[index].deptId = data.parentId
            } else if (type === 'report') {
                this.inputForm.detailInfoReports[index].userId = data.id
                this.inputForm.detailInfoReports[index].userName = data.label
                this.inputForm.detailInfoReports[index].deptName = data.parentLabel
                this.inputForm.detailInfoReports[index].deptId = data.parentId
            } else if (type === 'other') {
                this.inputForm.detailInfoOthers[index].userId = data.id
                this.inputForm.detailInfoOthers[index].userName = data.label
                this.inputForm.detailInfoOthers[index].deptName = data.parentLabel
                this.inputForm.detailInfoOthers[index].deptId = data.parentId
            }

            // 进行进一步处理...
        },
        init(id) {
            this.nodeFlag = true
            this.inputForm.id = id
            if (id) {
                reimbursementApprovalService.findById(id).then((data) => {

                    // 只有从我发起的还有已办事项抄送给我 进入流程页面的时候才会有这个值
                    console.log('this.status', this.status)
                    if (this.status === 'testSee') {
                        this.nodeFlag = false
                        this.testFlag = true
                    } else {
                        this.commonApi.getTaskNameByProcInsId(data.procInsId).then((data) => {
                            if (this.isNotEmpty(data)) {
                                if (data === '发起人重新申请' || this.isEmpty(data)) {
                                    this.nodeFlag = false
                                    this.testFlag = false
                                } else if (data === '综合管理部主任审批' || data === '公司领导审批' || data === '部门主任审批') {
                                    this.testFlag = true
                                    this.nodeFlag = false
                                } else {
                                    this.nodeFlag = true
                                }
                            }
                        })

                        if (this.userInfo.id === data.projectManager) {
                            this.testFlag = true
                        } else {
                            this.testFlag = false
                        }
                    }




                    this.inputForm = this.recover(this.inputForm, data)

                    if (this.inputForm.files) {
                        this.inputForm.files.forEach((item, index) => {
                            this.$set(this.showFileList, index, true);
                        })
                    }
                    if (this.inputForm.invoiceReimbursementFiles) {
                        this.inputForm.invoiceReimbursementFiles.forEach((item, index) => {
                            this.$set(this.showFileList2, index, true);
                        })
                    }
                })
            }
        },
        isEmpty(value) {
            let result = false;
            if (value == null || value == undefined) {
                result = true;
            }
            if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
                result = true;
            }
            if (typeof value == "object" && value instanceof Array && value.length === 0) {
                result = true;
            }
            return result;
        },
        isNotEmpty(value) {
            return !this.isEmpty(value)
        },
        /**
         * 判断是否为空
         */
        isNull(val) {
            if (val instanceof Array) {
                if (val.length === 0) return true;
            } else if (val instanceof Object) {
                if (JSON.stringify(val) === "{}") return true;
            } else {
                if (
                    val === "null" ||
                    val == null ||
                    val === "undefined" ||
                    val === undefined ||
                    val === ""
                )
                    return true;
                return false;
            }
            return false;
        },
        formatDate(date) {
            const dateNew = new Date(date); // 将日期字符串转换为 Date 对象
            const year = dateNew.getFullYear();
            const month = (dateNew.getMonth() + 1).toString().padStart(2, '0');
            const day = dateNew.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        formatDateNew(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        saveForm(callback) {

            // 所有验证通过，执行保存操作
            if (this.isNotEmpty(this.inputForm.reimDate)) {
                this.inputForm.reimDate = this.formatDate(this.inputForm.reimDate);
            }
            return new Promise(async (resolve, reject) => {

                let errors = [];

                if (this.isEmpty(this.inputForm.sourceType)) {
                    errors.push('报销类型不能为空!');
                } else if (this.isEmpty(this.inputForm.detailInfos) && this.isEmpty(this.inputForm.detailInfoReports) &&
                    this.isEmpty(this.inputForm.detailInfoOthers)) {
                    errors.push('至少填写一条报销详情信息!');
                } else if (this.isNotEmpty(this.inputForm.detailInfos)) {
                    let i = this.inputForm.detailInfos.length;
                    for (let j = 0; j < i; j++) {
                        let k = j + 1;
                        await this.validateDetailInfo(this.inputForm.detailInfos[j], '项目报销详情', k, errors);
                    }
                } else if (this.isNotEmpty(this.inputForm.detailInfoReports)) {
                    let i = this.inputForm.detailInfoReports.length;
                    for (let j = 0; j < i; j++) {
                        let k = j + 1;
                        await this.validateDetailInfo(this.inputForm.detailInfoReports[j], '报告报销详情', k, errors);
                    }
                } else if (this.isNotEmpty(this.inputForm.detailInfoOthers)) {
                    let i = this.inputForm.detailInfoOthers.length;
                    for (let j = 0; j < i; j++) {
                        let k = j + 1;
                        await this.validateDetailInfo(this.inputForm.detailInfoOthers[j], '其他报销详情', k, errors);
                    }
                } else if (this.inputForm.invoiceReimbursementFiles.length <= 0 && "1" === this.inputForm.reimbursementType) {
                    errors.push('请上传数电发票发票xml文件!');
                } else if (this.inputForm.invoiceReimbursementFiles.length > 0 && "1" === this.inputForm.reimbursementType) {
                    let i = this.inputForm.invoiceReimbursementFiles.length
                    let j = this.inputForm.invoiceReimbursements.length
                    if (i !== j) {
                        errors.push('已填写数电发票信息，请上传对应发票的xml文件!');
                    } else {
                        for (let k = 0; k < j; k++) {
                            let z = k + 1;
                            if (this.isEmpty(this.inputForm.invoiceReimbursements[k].invoiceType)) {
                                errors.push('数电发票信息第' + z + '行发票类型不能为空');
                            } else if (this.isEmpty(this.inputForm.invoiceReimbursements[k].invoiceProjectName)) {
                                errors.push('数电发票信息第' + z + '行发票项目名不能为空');
                            } else if (this.isEmpty(this.inputForm.invoiceReimbursements[k].number)) {
                                errors.push('数电发票信息第' + z + '行发票号不能为空');
                            } else if (this.isEmpty(this.inputForm.invoiceReimbursements[k].invoiceDate)) {
                                errors.push('数电发票信息第' + z + '行开票日期不能为空');
                            } else if (this.isEmpty(this.inputForm.invoiceReimbursements[k].invoiceUnit)) {
                                errors.push('数电发票信息第' + z + '行开票单位不能为空');
                            } else if (this.isEmpty(this.inputForm.invoiceReimbursements[k].amount)) {
                                errors.push('数电发票信息第' + z + '行金额不能为空');
                            } else if (this.isEmpty(this.inputForm.invoiceReimbursements[k].taxAmount)) {
                                errors.push('数电发票信息第' + z + '行税额不能为空');
                            }
                        }
                    }

                }


                if (errors.length > 0) {
                    // 存在错误，显示提示信息
                    errors.forEach(error => {
                        uni.showToast({
                            title: error,
                            icon: 'none',
                            duration: 1500
                        });
                    });
                    reject('Form validation failed');
                } else {

                    // 如果正在提交中，则直接返回，避免重复提交
                    if (this.submitting) return;

                    // 设置提交状态为 true
                    this.submitting = true;

                    this.$refs.inputForm.validate().then(res => {
                        this.inputForm.type = '2'
                        this.inputForm.userId = this.userInfo.id
                        reimbursementApprovalService.save(this.inputForm).then((data) => {
                            this.inputForm.id = data.businessId
                            this.inputForm.assignee = this.inputForm.projectManager
                            callback(data.businessTable, data.businessId, this.inputForm)
                            this.$refs.inputForm.resetFields()

                            // 重置提交状态为 false
                            this.submitting = false;
                        }).catch(() => {
                            this.$refs.inputForm.resetFields()
                            // 重置提交状态为 false
                            this.submitting = false;
                        }).catch((e) => {
                            // 重置提交状态为 false
                            this.submitting = false;
                        })
                    })
                }
            });
        },

        validateDetailInfo(detailInfo, detailType, k, errors) {
            return new Promise((resolve, reject) => {
                if (this.isEmpty(detailInfo.userName)) {
                    errors.push(detailType + '第' + k + '行请选择报销人');
                } else if (this.isEmpty(detailInfo.typeName)) {
                    errors.push(detailType + '第' + k + '行请选择报销类别');
                } else if (this.isEmpty(detailInfo.projectName)) {
                    errors.push(detailType + '第' + k + '行请选择报销项目');
                } else if (detailType === '报告报销详情' && this.isEmpty(detailInfo.reportNumber)) {
                    errors.push(detailType + '第' + k + '行请选择报告号');
                } else if (this.isEmpty(detailInfo.number)) {
                    errors.push(detailType + '第' + k + '行请输入费用(元)');
                }
                resolve();
            });
        },

        // 修改状态
        async updateStatusById(type, callback) {
            if (type === 'reject') {
                reimbursementApprovalService.findById(this.inputForm.id).then((data) => {
                    if (data.type !== '2') { // status的值不等于“审核中”，就弹出提示
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error()
                    } else {
                        this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((name) => {
                            if (this.isNotEmpty(name)) {
                                if (name === '项目经理审批' || name === '项目经理重新审批') {
                                    this.inputForm.type = '4'
                                }
                            }
                            reimbursementApprovalService.updateStatusById(this.inputForm).then(() => {
                                callback()
                            })
                        })
                    }
                })
            } else if (type === 'hold') {
                reimbursementApprovalService.findById(this.inputForm.id).then((data) => {
                    if (data.type !== '4') { // status的值不等于“驳回”就弹出提示
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error()
                    } else {
                        // 终止
                        let param = { status: '1', id: this.inputForm.id }
                        reimbursementApprovalService.updateStatusById(param).then(() => {
                            callback()
                        })
                    }
                })
            }
        },
        reapplyForm(callback) {
            reimbursementApprovalService.findById(this.inputForm.id).then((data) => {
                if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
                    this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                    throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                } else {
                    this.startFormTrue(callback)
                }
            })
        },
        // 送审
        async startFormTrue(callback) {

            return new Promise((resolve, reject) => {

                let errors = [];

                if (errors.length > 0) {
                    // 存在错误，显示提示信息
                    errors.forEach(error => {
                        uni.showToast({
                            title: error,
                            icon: 'none',
                            duration: 2000
                        });
                    });
                    reject('Form validation failed');
                } else {
                    this.$refs.inputForm.validate().then(res => {
                        this.inputForm.type = '2'
                        reimbursementApprovalService.save(this.inputForm).then((data) => {
                            this.inputForm.id = data.businessId
                            this.inputForm.assignee = this.inputForm.projectManager
                            callback(data.businessTable, data.businessId, this.inputForm)
                            this.$refs.inputForm.resetFields()
                        }).catch(() => {
                            this.$refs.inputForm.resetFields()
                        }).catch((e) => {

                        })
                    })
                }
            });
        },
        // 通过
        async agreeForm(callback) {
            this.$refs.inputForm.validate().then(res => {
                this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
                    if (this.isNotEmpty(data)) {
                        if (data === '公司领导审批') {
                            this.inputForm.type = '5'
                        } else {
                            this.inputForm.type = '2'
                        }
                    }
                    reimbursementApprovalService.save(this.inputForm).then((data) => {
                        callback(data.businessTable, data.businessId, this.inputForm)
                        this.$refs.inputForm.resetFields()
                    }).catch(() => {
                        this.$refs.inputForm.resetFields()
                    })
                })
            })
        },
        async addRow(type) {
            // 点击新增按钮时，向表格中添加一行空数据
            if (type === 'project') {
                this.inputForm.detailInfos.push({ userId: this.userInfo.id, userName: this.userInfo.name, deptName: this.userInfo.officeDTO.name, deptId: this.userInfo.officeDTO.id });
                await this.bxList('1'); // 等待异步操作完成
                // 报销类型数据
                let valueData = this.reimbursementList;
                // 将扁平数据转换为树形结构
                const result = this.buildTree(valueData);
                this.listData = result;
            }
            if (type === 'report') {
                this.inputForm.detailInfoReports.push({ userId: this.userInfo.id, userName: this.userInfo.name, deptName: this.userInfo.officeDTO.name, deptId: this.userInfo.officeDTO.id });
                await this.bxList('1'); // 等待异步操作完成
                // 报销类型数据
                let valueData = this.reimbursementList;
                // 将扁平数据转换为树形结构
                const result = this.buildTree(valueData);
                this.listData = result;
            }
            if (type === 'other') {
                this.inputForm.detailInfoOthers.push({ userId: this.userInfo.id, userName: this.userInfo.name, deptName: this.userInfo.officeDTO.name, deptId: this.userInfo.officeDTO.id });
                await this.bxList('1'); // 等待异步操作完成
                // 报销类型数据
                let valueData = this.reimbursementList;
                // 将扁平数据转换为树形结构
                const result = this.buildTree(valueData);
                this.listData = result;
            }
            if (type === 'specialInvoice') {
                this.inputForm.amountInfos.push({});
            }
        },
        removeRow(index, type) {
            // 点击删除按钮时，从表格中移除指定行
            if (type === 'project') {
                this.inputForm.detailInfos.splice(index, 1);
            }
            if (type === 'report') {
                this.inputForm.detailInfoReports.splice(index, 1);
            }
            if (type === 'other') {
                this.inputForm.detailInfoOthers.splice(index, 1);
            }
            if (type === 'specialInvoice') {
                this.inputForm.amountInfos.splice(index, 1);
            }

        },
        showUserCheck(index, type) {

            this.$refs.userPicker.open(index, type);
        },
        // 显示报销类别选择器
        showPicker(index, type) {
            this.$refs.reimbursementChoose._show(index, type);
        },
        // 显示报销项目选择器
        showProject(index, type) {
            if (type === 'project') {
                if (this.isEmpty(this.inputForm.detailInfos[index].typeName)) {
                    uni.showToast({
                        title: '请选择报销类型',
                        icon: 'none',
                        duration: 2000
                    });
                } else {
                    this.$refs.cwProjectChoose.init(index, type);
                }
            }
            if (type === 'report') {
                if (this.isEmpty(this.inputForm.detailInfoReports[index].typeName)) {
                    uni.showToast({
                        title: '请选择报销类型',
                        icon: 'none',
                        duration: 2000
                    });
                } else {
                    this.$refs.cwProjectChoose.init(index, type);
                }
            }


        },
        // 显示报告号选择器
        showReport(index) {
            if (this.isEmpty(this.inputForm.detailInfoReports[index].projectName)) {
                uni.showToast({
                    title: '请选择报销项目',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                this.$refs.cwReportChoose.init(index, this.inputForm.detailInfoReports[index].projectId);
            }


        },
        //监听选择
        selectChange(ids, names, index, type) {
            if (type === 'project') {
                this.$set(this.inputForm.detailInfos, index, {
                    ...this.inputForm.detailInfos[index],
                    typeName: names,
                    typeId: ids[0]
                });
            }
            if (type === 'report') {
                this.$set(this.inputForm.detailInfoReports, index, {
                    ...this.inputForm.detailInfoReports[index],
                    typeName: names,
                    typeId: ids[0]
                });
            }
            if (type === 'other') {
                this.$set(this.inputForm.detailInfoOthers, index, {
                    ...this.inputForm.detailInfoOthers[index],
                    typeName: names,
                    typeId: ids[0]
                });
            }

        },
        selectProjectChange(ids, names, index, type) {
            if (type === 'project') {
                this.$set(this.inputForm.detailInfos, index, {
                    ...this.inputForm.detailInfos[index],
                    projectName: names,
                    projectId: ids
                });
            }
            if (type === 'report') {
                this.$set(this.inputForm.detailInfoReports, index, {
                    ...this.inputForm.detailInfoReports[index],
                    projectName: names,
                    projectId: ids
                });
            }

        },
        selectReportChange(ids, reportNo, index) {

            this.$set(this.inputForm.detailInfoReports, index, {
                ...this.inputForm.detailInfoReports[index],
                reportNumber: reportNo
            });

        },
        buildTree(nodes, parentId = '0') {
            const tree = [];
            for (const node of nodes) {
                if (node.parentId === parentId) {
                    const children = this.buildTree(nodes, node.id);
                    if (children.length) {
                        node.children = children;
                    }
                    tree.push(node);
                }
            }
            return tree;
        },
        // 在输入时开始验证
        startValidation(index, type) {
            let value
            if (type === 'project') {
                value = this.inputForm.detailInfos[index].number
            } else if (type === 'report') {
                value = this.inputForm.detailInfoReports[index].number
            } else if (type === 'other') {
                value = this.inputForm.detailInfoOthers[index].number
            }
            const reg = /^(([1-9]\d*)|0)(\.\d{1,2})?$/;
            if (this.isEmpty(value)) {
                uni.showToast({
                    title: '费用(元)不能为空',
                    icon: 'none',
                    duration: 2000
                });
            } else if (reg.test(value)) {
                // callback();
            } else {
                if (type === 'project') {
                    this.inputForm.detailInfos[index].number = ''
                } else if (type === 'report') {
                    this.inputForm.detailInfoReports[index].number = ''
                } else if (type === 'other') {
                    this.inputForm.detailInfoOthers[index].number = ''
                }
                uni.showToast({
                    title: '请输入数字且最多保留两位小数',
                    icon: 'none',
                    duration: 2000
                });

            }
        },
        // 只能输入数字验证
        daysValidate(index, type) {
            let value
            if (type === 'project') {
                value = this.inputForm.detailInfos[index].days;
            } else if (type === 'report') {
                value = this.inputForm.detailInfoReports[index].days
            } else if (type === 'other') {
                value = this.inputForm.detailInfoOthers[index].days
            }

            // 正则表达式匹配整数
            const reg = /^[1-9]\d*$/;
            if (!reg.test(value) && this.isNotEmpty(value)) {
                // 输入不是整数，显示错误消息
                // this.$refs.form.$setErrorMessage(this.index_experience, 'days', '请输入整数');
                if (type === 'project') {
                    this.inputForm.detailInfos[index].days = ''
                } else if (type === 'report') {
                    this.inputForm.detailInfoReports[index].days = ''
                } else if (type === 'other') {
                    this.inputForm.detailInfoOthers[index].days = ''
                }
                uni.showToast({
                    title: '请输入整数',
                    icon: 'none',
                    duration: 2000
                });
            } else {
            }
        },
        // 只能输入数字验证
        numberValidate(index, type) {
            let value
            if (type === 'project') {
                value = this.inputForm.detailInfos[index].receiptNumber;
            } else if (type === 'report') {
                value = this.inputForm.detailInfoReports[index].receiptNumber
            } else if (type === 'other') {
                value = this.inputForm.detailInfoOthers[index].receiptNumber
            }

            // 正则表达式匹配整数
            const reg = /^[1-9]\d*$/;
            if (!reg.test(value) && this.isNotEmpty(value)) {
                // 输入不是整数，显示错误消息
                // this.$refs.form.$setErrorMessage(this.index_experience, 'receiptNumber', '请输入整数');
                if (type === 'project') {
                    this.inputForm.detailInfos[index].receiptNumber = ''
                } else if (type === 'report') {
                    this.inputForm.detailInfoReports[index].receiptNumber = ''
                } else if (type === 'other') {
                    this.inputForm.detailInfoOthers[index].receiptNumber = ''
                }
                uni.showToast({
                    title: '请输入整数',
                    icon: 'none',
                    duration: 2000
                });
            } else {
            }
        },
        handlePickerChange(value) {
            // 在这里处理选择器的值改变事件
            if (value === 1 || value === '1') {
                this.inputForm.detailInfoReports = []
                this.inputForm.detailInfoOthers = []
            } else if (value === 3 || value === '3') {
                this.inputForm.detailInfos = []
                this.inputForm.detailInfoOthers = []
            } else if (value === 4 || value === '4') {
                this.inputForm.detailInfos = []
                this.inputForm.detailInfoReports = []
            }
        },
        reimbursementTypeChange(value) {
            // 在这里处理选择器的值改变事件
            if (value === 0 || value === '0') {
                this.inputForm.invoiceReimbursementFiles = []
                this.inputForm.invoiceReimbursements = []
            } else if (value === 1 || value === '1') {
                this.inputForm.amountInfos = []
            }
        },
        // 通用的输入限制和格式化方法
        formatInput(inputValue, decimalLimit = 2) {
            // 如果输入值不是数字或者不是有效的小数，则返回空字符串
            if (!/^\d*\.?\d*$/.test(inputValue)) {
                return '';
            }

            // 只保留数字和一个小数点
            let value = inputValue.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, '');
                }
            }
            // 限制小数位数为指定的decimalLimit位数
            if (dotIndex !== -1) {
                const integerPart = value.substring(0, dotIndex);
                const decimalPart = value.substring(dotIndex + 1);
                value = integerPart + '.' + decimalPart.slice(0, decimalLimit);
            }
            return value;
        },
        // 输入值改变事件处理程序
        onInputCode(index, event, type) {
            const inputValue = event
            const formattedValue = this.formatInput(inputValue);
            if (type === 'code') {
                this.inputForm.amountInfos[index].code = formattedValue;
            }
            if (type === 'number') {

                //判断发票号是否已经存在
                reimbursementApprovalService.checkNumber(formattedValue).then((data) => {
                    if (data) {
                        uni.showToast({
                            title: '该发票号已存在',
                            icon: 'none',
                            duration: 2000
                        });
                        this.inputForm.amountInfos[index].number = ''
                    } else {
                        this.inputForm.amountInfos[index].number = formattedValue;
                    }
                })
            }
            if (type === 'amount') {
                this.$set(this.inputForm.amountInfos[index], 'amount', formattedValue)
                if (this.isNotEmpty(formattedValue)) {
                    if (this.isEmpty(this.inputForm.amountInfos[index].taxAmount)) {
                        this.$set(this.inputForm.amountInfos[index], 'count', parseFloat(formattedValue))
                    } else {
                        let taxValue = this.isNotEmpty(parseFloat(this.inputForm.amountInfos[index].taxAmount)) ? parseFloat(this.inputForm.amountInfos[index].taxAmount) : 0
                        this.$set(this.inputForm.amountInfos[index], 'count', parseFloat(formattedValue) + taxValue)
                    }
                } else {
                    if (this.isNotEmpty(this.inputForm.amountInfos[index].taxAmount)) {
                        let taxValue = this.isNotEmpty(parseFloat(this.inputForm.amountInfos[index].taxAmount)) ? parseFloat(this.inputForm.amountInfos[index].taxAmount) : 0
                        this.$set(this.inputForm.amountInfos[index], 'count', taxValue)
                    } else {
                        this.$set(this.inputForm.amountInfos[index], 'count', '')
                    }
                }
            }
            if (type === 'taxAmount') {
                this.$set(this.inputForm.amountInfos[index], 'taxAmount', formattedValue)
                if (this.isNotEmpty(formattedValue)) {
                    if (this.isEmpty(this.inputForm.amountInfos[index].amount)) {
                        this.$set(this.inputForm.amountInfos[index], 'count', parseFloat(formattedValue))
                    } else {
                        let taxValue = this.isNotEmpty(parseFloat(this.inputForm.amountInfos[index].amount)) ? parseFloat(this.inputForm.amountInfos[index].amount) : 0
                        this.$set(this.inputForm.amountInfos[index], 'count', parseFloat(formattedValue) + taxValue)
                    }
                } else {
                    if (this.isNotEmpty(this.inputForm.amountInfos[index].amount)) {
                        let taxValue = this.isNotEmpty(parseFloat(this.inputForm.amountInfos[index].amount)) ? parseFloat(this.inputForm.amountInfos[index].amount) : 0
                        this.$set(this.inputForm.amountInfos[index], 'count', taxValue)
                    } else {
                        this.$set(this.inputForm.amountInfos[index], 'count', '')
                    }
                }
            }
        },
        handleUploadSuccess(file, fileList, type) {
            // 将 fileList 转换为你期望的格式
            const formattedFiles = fileList.map(fileItem => {
                return {
                    name: fileItem.name,
                    size: fileItem.size,
                    url: fileItem.response ? '/' + fileItem.response.url : fileItem.url,
                    lsUrl: fileItem.response ? fileItem.response.lsUrl : fileItem.lsUrl, // 如果没有 lsUrl，可以根据需要设置为空字符串或其他默认值
                    createBy: this.userInfo,
                    by: this.userInfo.id,
                    createTime: this.formatDateNew(new Date())
                };
            });
            const dzFormattedFiles = fileList.map(fileItem => {
                return {
                    name: fileItem.name,
                    size: fileItem.size,
                    url: fileItem.response ? '/' + fileItem.response.url : fileItem.url,
                    lsUrl: fileItem.response ? fileItem.response.lsUrl : fileItem.lsUrl, // 如果没有 lsUrl，可以根据需要设置为空字符串或其他默认值
                    createBy: this.userInfo,
                    by: this.userInfo.id,
                    createTime: this.formatDateNew(new Date())
                };
            });
            if (type === '电子') {
                reimbursementApprovalService.getEffectiveDataByInvoiceNumber(file.response.InvoiceNumber).then((decide) => {
                    if (!decide.success) {

                        uni.showToast({
                            title: decide.message,
                            icon: 'none',
                            duration: 2000
                        });
                        //删除上传的附件信息
                        fileList.pop();
                    } else {
                        this.inputForm.invoiceReimbursementFiles = dzFormattedFiles
                        //电子发票详情赋值操作
                        const newInvoiceReimbursement = {
                            invoiceType: file.response.InherentLabelGeneralOrSpecialVATLabelCode,
                            invoiceProjectName: file.response.IssuItemInformationItemName,
                            number: file.response.InvoiceNumber,
                            invoiceDate: file.response.IssueTime,
                            invoiceUnit: file.response.SellerInformationSellerName,
                            amount: file.response.BasicInformationTotalAmWithoutTax,
                            taxAmount: file.response.BasicInformationTotalTaxAm,
                            count: file.response.BasicInformationTotalTaxincludedAmount
                        };

                        this.inputForm.invoiceReimbursements.push(newInvoiceReimbursement);

                        fileList.forEach((item, index) => {
                            if (item === file) {
                                this.$set(this.showFileList2, index, true);
                            }
                        });
                    }
                })

            } else {
                this.inputForm.files = formattedFiles
                fileList.forEach((item, index) => {
                    if (item === file) {
                        this.$set(this.showFileList, index, true);
                    }
                });
            }


            // 强制更新视图
            this.$forceUpdate();
        },
        shouldShowFile(file, type) {

            if (type === '电子') {
                if (this.inputForm.invoiceReimbursementFiles && this.inputForm.invoiceReimbursementFiles.length > 0) {
                    // 返回一个布尔值，确定是否显示上传成功后的文件
                    return this.showFileList2[this.inputForm.invoiceReimbursementFiles.indexOf(file)];
                }
            } else {
                if (this.inputForm.files && this.inputForm.files.length > 0) {
                    // 返回一个布尔值，确定是否显示上传成功后的文件
                    return this.showFileList[this.inputForm.files.indexOf(file)];
                }
            }


            return false; // 默认返回 false 或者其他适当的
        },
        handleDelete(file, fileList, type, fileIndex) {
            // const formattedFiles = fileList.map(fileItem => {
            //     return {
            //         name: fileItem.name,
            //         size: fileItem.size,
            //         url: '/' + fileItem.response.url,
            //         createBy: this.userInfo,
            //         by: this.userInfo.id,
            //         createTime: this.formatDateNew(new Date())
            //     };
            // });
            // if (type === '电子') {
            //     this.inputForm.invoiceReimbursementFiles = formattedFiles
            // } else {
            //     this.inputForm.files = formattedFiles
            // }
            // 处理删除文件的逻辑
            // 从文件列表中移除文件
            if (type === '电子') {
                this.inputForm.invoiceReimbursementFiles.splice(fileIndex, 1);
                this.showFileList2.splice(fileIndex, 1); // 从showFileList中移除对应的元素
                //电子发票详情赋值操作
                this.inputForm.invoiceReimbursements.splice(fileIndex, 1);
            } else {
                this.inputForm.files.splice(fileIndex, 1);
                this.showFileList.splice(fileIndex, 1); // 从showFileList中移除对应的元素
            }
        },
        async handleFileClick(file) {
            await this.ossService.getTemporaryUrl(file.url).then((data) => {
                file.lsUrl = data
            })
            if (this.isImage(file.name)) {
                // 如果是图片文件，则执行放大显示图片的逻辑
                this.handleImageClick(file);
            } else {
                // window.open(file.lsUrl, '_blank')
                window.location.href = file.lsUrl
                // 如果不是图片文件，则执行其他操作，比如下载文件等
            }
        },
        // 判断文件是否是图片类型
        isImage(fileName) {
            const ext = fileName.toLowerCase().split('.').pop(); // 获取文件的后缀名
            return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext); // 判断后缀名是否是图片类型
        },
        handleImageClick(file) {
            // 在点击图片时执行放大显示的逻辑
            this.$alert(`<img src="${file.lsUrl}" style="max-width: 100%; max-height: 100%;" />`, '图片详情', {
                dangerouslyUseHTMLString: true,
                customClass: 'custom-alert'
            });
        },
        handleRemove(file, fileList, type) {
            // 处理移除文件逻辑
            // file 是移除的文件
            // fileList 是当前文件列表
            const formattedFiles = fileList.map(fileItem => {
                return {
                    name: fileItem.name,
                    size: fileItem.size,
                    url: '/' + fileItem.response.url,
                    createBy: this.userInfo,
                    by: this.userInfo.id,
                    createTime: this.formatDateNew(new Date())
                };
            });
            if (type === '电子') {
                fileList.forEach((item, index) => {
                });
                this.inputForm.invoiceReimbursementFiles = formattedFiles
            } else {
                this.inputForm.files = formattedFiles
            }
        },
        beforeUpload(file) {
            const isXML = file.type === 'text/xml' || file.name.endsWith('.xml');
            if (!isXML) {
                uni.showToast({
                    title: '只能上传 XML 文件',
                    icon: 'none',
                    duration: 2000
                });
                return false;
            } else {
                if (this.inputForm.invoiceReimbursementFiles.length > 0) {
                    for (let i = 0; i < this.inputForm.invoiceReimbursementFiles.length; i++) {
                        if (this.inputForm.invoiceReimbursementFiles[i].name === file.name) {
                            uni.showToast({
                                title: '该文件已上传，请勿重复上传',
                                icon: 'none',
                                duration: 2000
                            });
                            return false;
                        }
                    }
                }
                //将文件进行保存操作
                return true
            }
        },
    }
}
</script>

<style>
.cu-form-group .title {
    min-width: calc(4em + 40px);
}
</style>
