<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">


            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.financeInvoiceBaseDTOList">
                <el-col :span="24">
                    <u-form-item label="">
                        <el-divider content-position="left"> 基本信息详情 {{ index_experience + 1 }}</el-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="项目名称" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].programName'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].programName"
                            placeholder="请选择项目名称" @focus="showProject(index_experience)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="合同名称" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].contractName'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].contractName"
                            :readonly="true" placeholder="请填写合同名称" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="项目编号" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].programNo'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].programNo"
                            :readonly="true" placeholder="请填写项目编号" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报告号" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].reportNo'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].reportNo"
                            :readonly="true" placeholder="请填写报告号" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="发票金额(元)" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].account'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].account"
                            @blur="onInputCode(index_experience, $event, 'account')" 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" @click="removeRow('base', index_experience)"
                            plain>删除基本信息 {{ index_experience + 1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="">
                <el-button style="width: 100%" type="primary" @click="addRow('base')" plain>新增基本信息</el-button>
            </u-form-item>
            <u-form-item label="">
                <el-divider content-position="left"> 发票详情</el-divider>
            </u-form-item>
            <u-form-item label="发票类型" borderBottom prop="type" :required="true">
                <u-radio-group v-model="inputForm.type">
                    <u-radio :customStyle="{ marginRight: '16px' }" v-for="(item, index) in typeList" :key="index"
                        :label="item.name" :name="item.value"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="发票申请编号" prop="no" :rules="[
            ]">
                <u--input v-model="inputForm.no" :disabled="true" placeholder="请填写发票申请编号" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票类型" borderBottom prop="billingType" :required="true">
                <u-radio-group v-model="inputForm.billingType">
                    <u-radio :customStyle="{ marginRight: '16px' }" v-for="(item, index) in billingTypeList"
                        :key="index" :label="item.name" :name="item.value" @change="reimbursementTypeChange"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="实际开票单位" prop="billingWorkplaceReal" v-if="inputForm.billingType === '1'"
                :required="true" :rules="[
                ]">
                <u--input v-model="inputForm.billingWorkplaceReal" @focus="showWorkplace()" placeholder="请填写实际开票单位"
                    clearable></u--input>
            </u-form-item>
            <template v-if="inputForm.type === '1'">
                <u-form-item label="纳税人识别号" prop="taxpayerIdentificationNo" v-if="inputForm.billingType === '1'"
                    :required="true" :rules="[
                    ]">
                    <u--input v-model="inputForm.taxpayerIdentificationNo" placeholder="请填写纳税人识别号" clearable></u--input>
                </u-form-item>

                <u-form-item label="地址" prop="address" v-if="inputForm.billingType === '1'" :required="true" :rules="[
                ]">
                    <u--input v-model="inputForm.address" placeholder="请填写地址" clearable></u--input>
                </u-form-item>
                <u-form-item label="电话" prop="telPhone" v-if="inputForm.billingType === '1'" :required="true" :rules="[
                ]">
                    <u--input v-model="inputForm.telPhone" placeholder="请填写电话" clearable></u--input>
                </u-form-item>

                <u-form-item label="开户银行" borderBottom v-if="inputForm.billingType === '1'" prop="openBank"
                    :required="true">
                    <jp-picker v-model="inputForm.openBank" @input="changeBank" rangeKey="label" rangeValue="value"
                        :range=bankList></jp-picker>
                </u-form-item>


                <u-form-item label="银行账号" borderBottom v-if="inputForm.billingType === '1'" prop="bankAccount"
                    :required="true">
                    <u--input v-model="inputForm.bankAccount" :disabled="true" placeholder="请填写银行账号"
                        clearable></u--input>
                </u-form-item>

            </template>
            <template v-if="inputForm.type !== '1'">
                <u-form-item label="纳税人识别号" v-if="inputForm.billingType === '1'" prop="taxpayerIdentificationNo" :rules="[
                ]">
                    <u--input v-model="inputForm.taxpayerIdentificationNo" placeholder="请填写纳税人识别号" clearable></u--input>
                </u-form-item>
                <u-form-item label="地址" prop="address" v-if="inputForm.billingType === '1'" :rules="[
                ]">
                    <u--input v-model="inputForm.address" placeholder="请填写地址" clearable></u--input>
                </u-form-item>
                <u-form-item label="电话" prop="telPhone" v-if="inputForm.billingType === '1'" :rules="[
                ]">
                    <u--input v-model="inputForm.telPhone" placeholder="请填写电话" clearable></u--input>
                </u-form-item>
                <u-form-item label="开户银行" borderBottom v-if="inputForm.billingType === '1'" prop="openBank">
                    <jp-picker v-model="inputForm.openBank" @input="changeBank" rangeKey="label" rangeValue="value"
                        :range=bankList></jp-picker>
                </u-form-item>
                <u-form-item label="银行账号" v-if="inputForm.billingType === '1'" borderBottom prop="bankAccount">
                    <u--input v-model="inputForm.bankAccount" :disabled="true" placeholder="请填写银行账号"
                        clearable></u--input>
                </u-form-item>

            </template>

            <u-form-item label="姓名" v-if="inputForm.billingType === '2'" prop="nameShow" :required="true" :rules="[
            ]">
                <u--input v-model="inputForm.nameShow" placeholder="请选择" @focus="openUserPullForm('', '姓名')"
                    clearable></u--input>
            </u-form-item>

            <u-form-item label="收款类型" borderBottom prop="receivablesType" :required="true">
                <jp-picker v-model="inputForm.receivablesType" rangeKey="label" rangeValue="value" :range="[
                    { label: '单一收费', value: '1' },
                    { label: '合并收费', value: '2' },
                ]"></jp-picker>
            </u-form-item>
            <u-form-item label="开票内容" borderBottom prop="billingContent" :required="true">
                <jp-picker v-model="inputForm.billingContent" rangeKey="label" rangeValue="value" :range="[
                    { label: '审计费', value: '1' },
                    { label: '工程审核费', value: '2' },
                    { label: '咨询费', value: '3' },
                    { label: '预算编制费', value: '4' },
                    { label: '招标代理费', value: '5' },
                    { label: '司法鉴定费', value: '6' },
                    { label: '其他', value: '8' },
                    { label: '技术服务费', value: '9' },
                    { label: '鉴证咨询服务*评估费', value: '10' },
                    { label: '其他咨询服务*专家咨询费', value: '11' },
                    { label: '会计服务', value: '12' },
                    { label: '竣工决算编制费', value: '13' },
                    { label: '*信息技术服务*技术服务费', value: '14' },
                ]"></jp-picker>
            </u-form-item>
            <u-form-item label="发票金额(元)" borderBottom prop="accountTotal" :required="true">
                <u--input v-model="inputForm.accountTotal" :disabled="true" placeholder="请填写发票金额" clearable></u--input>
            </u-form-item>
            <u-form-item label="报备类型" borderBottom prop="reportType" :required="true">
                <jp-picker v-model="inputForm.reportType" rangeKey="label" rangeValue="value" :range="[
                    { label: '上市公司审计', value: '1' },
                    { label: '国有大型企业审计', value: '2' },
                    { label: '新三板企业审计', value: '3' },
                    { label: '一般企业审计', value: '4' },
                    { label: '事业单位审计', value: '5' },
                    { label: '民间非营利组织等其他单位审计', value: '6' },
                    { label: '内控审计报告', value: '7' },
                    { label: '内控鉴证报告', value: '8' },
                    { label: '其他报告', value: '9' },
                    { label: '专项审计业务', value: '10' },
                    { label: '验资业务', value: '11' },
                ]"></jp-picker>
            </u-form-item>
            <u-form-item label="是否多张开票" borderBottom prop="isMultiple" :required="true">
                <u-radio-group v-model="inputForm.isMultiple">
                    <u-radio :customStyle="{ marginRight: '16px' }" v-for="(item, index) in yesNoFlag" :key="index"
                        :label="item.name" :name="item.value"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="开票内容要求" borderBottom prop="billingContentTerms">
                <u--textarea placeholder='开票内容要求' :maxlength="500"
                    v-model="inputForm.billingContentTerms"></u--textarea>
            </u-form-item>
            <u-form-item label="开票人" borderBottom prop="billingPeople">
                <u--input v-model="inputForm.billingPeople" :disabled="true" placeholder="请选择开票人" clearable></u--input>
            </u-form-item>
            <!--<u-form-item label="开票时间" prop="billingDate" v-if="addFlag" :required="true"
                         :rules="[
				     ]">
                <el-date-picker
                        v-model="inputForm.billingDate"
                        type="date"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="领票时间" prop="collectDate" v-if="addFlag"
                         :rules="[
				     ]">
                <el-date-picker
                        v-model="inputForm.collectDate"
                        type="date"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>-->
            <u-form-item label="实际开票人" prop="billingPeopleRealName" :required="true" :rules="[
            ]">
                <u--input v-model="inputForm.billingPeopleRealName" placeholder="请选择实际开票人"
                    @focus="openUserPullForm('', '实际')" clearable></u--input>
            </u-form-item>
            <u-form-item label="接收邮箱" prop="actualDrawerEmailAddress" :rules="[
            ]">
                <u--input v-model="inputForm.actualDrawerEmailAddress" placeholder="请输入接收邮箱" clearable></u--input>
                <view class="button-container">
                    <button @click="openDia">完善邮箱</button>
                </view>
            </u-form-item>
            <u-form-item label="对账人" prop="reconciliationPeopleName" :required="true" :rules="[
            ]">
                <u--input v-model="inputForm.reconciliationPeopleName" placeholder="请选择对账人"
                    @focus="openUserPullForm('', '对账')" clearable></u--input>
            </u-form-item>
            <u-form-item label="对账地区" borderBottom prop="reconciliationArea" :required="true">
                <jp-area-select v-model="inputForm.reconciliationArea"></jp-area-select>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks"></u--textarea>
            </u-form-item>

            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.financeInvoiceDetailDTOList">
                <el-col :span="24">
                    <u-form-item label="">
                        <el-divider content-position="left"> 发票明细详情 {{ index_experience + 1 }}</el-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="发票代码" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].code'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].code"
                            placeholder="请填写发票代码" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="发票号" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].number'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].number"
                            @blur="validateNumber(index_experience)" placeholder="请填写发票号" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="开票金额(元)" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].account'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].account"
                            placeholder="请填写开票金额(元)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="税率(%)" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].rate'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].rate"
                            @blur="checkRate($event, index_experience)" placeholder="请填写税率(%)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="金额" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].amount'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].amount"
                            :readonly="true" placeholder="请填写金额" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="税额" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].tax'" :rules="[
                    ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].tax" :readonly="true"
                            placeholder="请填写税额" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="累计登记金额"
                        :prop="'financeInvoiceDetailDTOList[' + index_experience + '].allAmount'" :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].allAmount"
                            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="true"
                            @click="removeRow('detail', index_experience)" plain>删除发票明细 {{ index_experience +
                                1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="">
                <el-button style="width: 100%" :disabled="true" type="primary" @click="addRow('detail')"
                    plain>新增发票明细</el-button>
                <!--                <el-button style="width: 100%" :disabled="true" type="primary" @click="downloadTpl" plain>下载模板</el-button>-->
            </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.workAttachmentDtoList"
                    :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList)"
                    :limit="3">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                    <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file)">
                        <span @click="handleFileClick(file)">{{ file.name }}</span>
                        <el-button type="text" icon="el-icon-close" @click="handleDelete(file)">✕</el-button>
                    </template>
                </el-upload> -->
                <UploadComponent
                    :uploadUrl="`http://cpaoa.xgccpm.com/api/public-modules-server/oss/file/webUpload/upload`"
                    @onRemove="handleDelete" @onSuccess="handleUploadSuccess"
                    :fileList="inputForm.workAttachmentDtoList" :limit="3">
                </UploadComponent>
            </u-form-item>
        </u--form>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules"
            ref="inputForm" v-if="nodeFlag">


            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.financeInvoiceBaseDTOList">
                <el-col :span="24">
                    <u-form-item label="">
                        <el-divider content-position="left"> 基本信息详情 {{ index_experience + 1 }}</el-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="项目名称" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].programName'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].programName"
                            :disabled="true" placeholder="请选择项目名称" @focus="showProject(index_experience)"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="合同名称" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].contractName'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].contractName"
                            :disabled="true" :readonly="true" placeholder="请填写合同名称" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="项目编号" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].programNo'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].programNo"
                            :disabled="true" :readonly="true" placeholder="请填写项目编号" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="报告号" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].reportNo'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].reportNo"
                            :disabled="true" :readonly="true" placeholder="请填写报告号" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="发票金额(元)" :prop="'financeInvoiceBaseDTOList[' + index_experience + '].account'"
                        :required="true" :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceBaseDTOList[index_experience].account"
                            :disabled="true" @blur="onInputCode(index_experience, $event, 'account')"
                            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="true"
                            @click="removeRow('base', index_experience)" plain>删除基本信息 {{ index_experience +
                                1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="">
                <el-button style="width: 100%" type="primary" :disabled="true" @click="addRow('base')"
                    plain>新增基本信息</el-button>
            </u-form-item>
            <u-form-item label="">
                <el-divider content-position="left"> 发票详情</el-divider>
            </u-form-item>
            <u-form-item label="发票类型" borderBottom prop="type" :required="true">
                <u-radio-group v-model="inputForm.type">
                    <u-radio :disabled="true" :customStyle="{ marginRight: '16px' }" v-for="(item, index) in typeList"
                        :key="index" :label="item.name" :name="item.value"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="发票申请编号" prop="no" :rules="[
            ]">
                <u--input v-model="inputForm.no" :disabled="true" placeholder="请填写发票申请编号" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票类型" borderBottom prop="billingType" :required="true">
                <u-radio-group v-model="inputForm.billingType">
                    <u-radio :disabled="true" :customStyle="{ marginRight: '16px' }"
                        v-for="(item, index) in billingTypeList" :key="index" :label="item.name" :name="item.value"
                        @change="reimbursementTypeChange"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="实际开票单位" prop="billingWorkplaceReal" v-if="inputForm.billingType === '1'"
                :required="true" :rules="[
                ]">
                <u--input v-model="inputForm.billingWorkplaceReal" :disabled="true" @focus="showWorkplace()"
                    placeholder="请填写实际开票单位" clearable></u--input>
            </u-form-item>
            <template v-if="inputForm.type === '1'">
                <u-form-item label="纳税人识别号" prop="taxpayerIdentificationNo" v-if="inputForm.billingType === '1'"
                    :required="true" :rules="[
                    ]">
                    <u--input v-model="inputForm.taxpayerIdentificationNo" :disabled="true" placeholder="请填写纳税人识别号"
                        clearable></u--input>
                </u-form-item>

                <u-form-item label="地址" prop="address" v-if="inputForm.billingType === '1'" :required="true" :rules="[
                ]">
                    <u--input v-model="inputForm.address" :disabled="true" placeholder="请填写地址" clearable></u--input>
                </u-form-item>
                <u-form-item label="电话" prop="telPhone" v-if="inputForm.billingType === '1'" :required="true" :rules="[
                ]">
                    <u--input v-model="inputForm.telPhone" :disabled="true" placeholder="请填写电话" clearable></u--input>
                </u-form-item>

                <u-form-item label="开户银行" borderBottom v-if="inputForm.billingType === '1'" prop="openBank"
                    :required="true">
                    <jp-picker v-model="inputForm.openBank" :disabled="true" @input="changeBank" rangeKey="label"
                        rangeValue="value" :range=bankList></jp-picker>
                </u-form-item>


                <u-form-item label="银行账号" borderBottom v-if="inputForm.billingType === '1'" prop="bankAccount"
                    :required="true">
                    <u--input v-model="inputForm.bankAccount" :disabled="true" placeholder="请填写银行账号"
                        clearable></u--input>
                </u-form-item>

            </template>
            <template v-if="inputForm.type !== '1'">
                <u-form-item label="纳税人识别号" v-if="inputForm.billingType === '1'" prop="taxpayerIdentificationNo" :rules="[
                ]">
                    <u--input v-model="inputForm.taxpayerIdentificationNo" :disabled="true" placeholder="请填写纳税人识别号"
                        clearable></u--input>
                </u-form-item>
                <u-form-item label="地址" prop="address" v-if="inputForm.billingType === '1'" :rules="[
                ]">
                    <u--input v-model="inputForm.address" :disabled="true" placeholder="请填写地址" clearable></u--input>
                </u-form-item>
                <u-form-item label="电话" prop="telPhone" v-if="inputForm.billingType === '1'" :rules="[
                ]">
                    <u--input v-model="inputForm.telPhone" :disabled="true" placeholder="请填写电话" clearable></u--input>
                </u-form-item>
                <u-form-item label="开户银行" borderBottom v-if="inputForm.billingType === '1'" prop="openBank">
                    <jp-picker v-model="inputForm.openBank" :disabled="true" @input="changeBank" rangeKey="label"
                        rangeValue="value" :range=bankList></jp-picker>
                </u-form-item>
                <u-form-item label="银行账号" v-if="inputForm.billingType === '1'" borderBottom prop="bankAccount">
                    <u--input v-model="inputForm.bankAccount" :disabled="true" placeholder="请填写银行账号"
                        clearable></u--input>
                </u-form-item>

            </template>

            <u-form-item label="姓名" v-if="inputForm.billingType === '2'" prop="nameShow" :required="true" :rules="[
            ]">
                <u--input v-model="inputForm.nameShow" :disabled="true" placeholder="请选择"
                    @focus="openUserPullForm('', '姓名')" clearable></u--input>
            </u-form-item>

            <u-form-item label="收款类型" borderBottom prop="receivablesType" :required="true">
                <jp-picker v-model="inputForm.receivablesType" :disabled="true" rangeKey="label" rangeValue="value"
                    :range="[
                        { label: '单一收费', value: '1' },
                        { label: '合并收费', value: '2' },
                    ]"></jp-picker>
            </u-form-item>
            <u-form-item label="开票内容" borderBottom prop="billingContent" :required="true">
                <jp-picker v-model="inputForm.billingContent" rangeKey="label" :disabled="true" rangeValue="value"
                    :range="[
                        { label: '审计费', value: '1' },
                        { label: '工程审核费', value: '2' },
                        { label: '咨询费', value: '3' },
                        { label: '预算编制费', value: '4' },
                        { label: '招标代理费', value: '5' },
                        { label: '司法鉴定费', value: '6' },
                        { label: '其他', value: '8' },
                        { label: '技术服务费', value: '9' },
                        { label: '鉴证咨询服务*评估费', value: '10' },
                        { label: '其他咨询服务*专家咨询费', value: '11' },
                        { label: '会计服务', value: '12' },
                        { label: '竣工决算编制费', value: '13' },
                        { label: '*信息技术服务*技术服务费', value: '14' },
                    ]"></jp-picker>
            </u-form-item>
            <u-form-item label="发票金额(元)" borderBottom prop="accountTotal" :required="true">
                <u--input v-model="inputForm.accountTotal" :disabled="true" placeholder="请填写发票金额" clearable></u--input>
            </u-form-item>
            <u-form-item label="报备类型" borderBottom prop="reportType" :required="true">
                <jp-picker v-model="inputForm.reportType" :disabled="true" rangeKey="label" rangeValue="value" :range="[
                    { label: '上市公司审计', value: '1' },
                    { label: '国有大型企业审计', value: '2' },
                    { label: '新三板企业审计', value: '3' },
                    { label: '一般企业审计', value: '4' },
                    { label: '事业单位审计', value: '5' },
                    { label: '民间非营利组织等其他单位审计', value: '6' },
                    { label: '内控审计报告', value: '7' },
                    { label: '内控鉴证报告', value: '8' },
                    { label: '其他报告', value: '9' },
                    { label: '专项审计业务', value: '10' },
                    { label: '验资业务', value: '11' },
                ]"></jp-picker>
            </u-form-item>
            <u-form-item label="是否多张开票" borderBottom prop="isMultiple" :required="true">
                <u-radio-group v-model="inputForm.isMultiple">
                    <u-radio :disabled="true" :customStyle="{ marginRight: '16px' }" v-for="(item, index) in yesNoFlag"
                        :key="index" :label="item.name" :name="item.value"></u-radio>
                </u-radio-group>
            </u-form-item>
            <u-form-item label="开票内容要求" borderBottom prop="billingContentTerms">
                <u--textarea placeholder='开票内容要求' :disabled="true" :maxlength="500"
                    v-model="inputForm.billingContentTerms"></u--textarea>
            </u-form-item>
            <u-form-item label="开票人" borderBottom prop="billingPeople">
                <u--input v-model="inputForm.billingPeople" :disabled="true" placeholder="请选择开票人" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票时间" prop="billingDate" v-if="addFlag" :required="true" :rules="[
            ]">
                <el-date-picker :disabled="testFlag" v-model="inputForm.billingDate" type="date" style="width:100%"
                    size="default" placement="bottom-start" clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="领票时间" prop="collectDate" v-if="addFlag" :rules="[
            ]">
                <el-date-picker :disabled="testFlag" v-model="inputForm.collectDate" type="date" style="width:100%"
                    size="default" placement="bottom-start" clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="实际开票人" prop="billingPeopleRealName" :required="true" :rules="[
            ]">
                <u--input v-model="inputForm.billingPeopleRealName" :disabled="true" placeholder="请选择实际开票人"
                    @focus="openUserPullForm('', '实际')" clearable></u--input>
            </u-form-item>
            <u-form-item label="接收邮箱" prop="actualDrawerEmailAddress" :rules="[
            ]">
                <u--input v-model="inputForm.actualDrawerEmailAddress" :disabled="true" placeholder="请输入接收邮箱"
                    clearable></u--input>
                <view class="button-container">
                    <button :disabled="true" @click="openDia">完善邮箱</button>
                </view>
            </u-form-item>
            <u-form-item label="对账人" prop="reconciliationPeopleName" :required="true" :rules="[
            ]">
                <u--input v-model="inputForm.reconciliationPeopleName" :disabled="true" placeholder="请选择对账人"
                    @focus="openUserPullForm('', '对账')" clearable></u--input>
            </u-form-item>
            <u-form-item label="对账地区" borderBottom prop="reconciliationArea" :required="true">
                <jp-area-select :disabled="true" v-model="inputForm.reconciliationArea"></jp-area-select>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea placeholder='请填写备注' :disabled="true" :maxlength="500"
                    v-model="inputForm.remarks"></u--textarea>
            </u-form-item>

            <el-row :gutter="15" :key="index_experience"
                v-for="(item, index_experience) in this.inputForm.financeInvoiceDetailDTOList">
                <el-col :span="24">
                    <u-form-item label="">
                        <el-divider content-position="left"> 发票明细详情 {{ index_experience + 1 }}</el-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="发票代码" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].code'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].code"
                            :disabled="testFlag" placeholder="请填写发票代码" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="发票号" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].number'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].number"
                            :disabled="testFlag" @blur="validateNumber(index_experience)" placeholder="请填写发票号"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="开票金额(元)" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].account'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].account"
                            :disabled="testFlag" placeholder="请填写开票金额(元)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="税率(%)" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].rate'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].rate"
                            :disabled="testFlag" @blur="checkRate($event, index_experience)" placeholder="请填写税率(%)"
                            clearable></u--input>
                    </u-form-item>
                    <u-form-item label="金额" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].amount'"
                        :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].amount"
                            :disabled="testFlag" :readonly="true" placeholder="请填写金额" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="税额" :prop="'financeInvoiceDetailDTOList[' + index_experience + '].tax'" :rules="[
                    ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].tax"
                            :disabled="testFlag" :readonly="true" placeholder="请填写税额" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="累计登记金额"
                        :prop="'financeInvoiceDetailDTOList[' + index_experience + '].allAmount'" :rules="[
                        ]">
                        <u--input v-model="inputForm.financeInvoiceDetailDTOList[index_experience].allAmount"
                            :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('detail', index_experience)" plain>删除基本信息 {{ index_experience +
                                1 }}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="">
                <el-button style="width: 100%" type="primary" :disabled="testFlag" @click="addRow('detail')"
                    plain>新增发票明细</el-button>
                <!--                <el-button style="width: 100%" :disabled="testFlag" type="primary" @click="downloadTpl" plain>下载模板</el-button>-->
            </u-form-item>


            <u-form-item label="附件">
                <!-- <el-upload :disabled="true" 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.workAttachmentDtoList"
                    :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList)"
                    :limit="3">
                    <el-button size="small" :disabled="true" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                    <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file)">
                        <span @click="handleFileClick(file)">{{ file.name }}</span>
                        <el-button type="text" icon="el-icon-close" @click="handleDelete(file)">✕</el-button>
                    </template>
                </el-upload> -->
                <UploadComponent
                    :uploadUrl="`http://cpaoa.xgccpm.com/api/public-modules-server/oss/file/webUpload/upload`"
                    @onRemove="handleDelete" @onSuccess="handleUploadSuccess"
                    :fileList="inputForm.workAttachmentDtoList" :limit="3">
                </UploadComponent>
            </u-form-item>
        </u--form>
        <user-select ref="userPicker" @input="handleEvent"></user-select>
        <InvoiceProjectChoose ref="invoiceProjectChoose" @input="selectProjectChange" title="报告项目选择" />
        <WorkPlaceChoose ref="workPlaceChoose" @input="getWorkClient" title="客户选择" />
        <EmailForm ref="emailForm" @input="emailForm" title="完善邮箱" />
    </view>
</template>

<script>
import financeInvoiceService from '@/api/cw/invoice/CwFinanceInvoiceService'
var graceChecker = require("@/common/graceChecker.js");
import workClientService from '@/api/cw/workClientInfo/WorkClientService'
import InvoiceProjectChoose from './InvoiceProjectChoose'
import WorkPlaceChoose from './WorkPlaceChoose'
import EmailForm from './EmailForm'
import userSelect from '@/components/user-select/user-select-radio.vue'
import OSSService from "@/api/sys/OSSService"
import MaterialTypeService from '@/api/materialManagement/MaterialTypeService'
import WareHouseService from '@/api/materialManagement/WareHouseService'
import CommonApi from '@/api/common/CommonApi'
import { mapState, mapMutations, mapActions } from 'vuex'
import UploadComponent from '@/pages/common/UploadComponent.vue';
export default {
    components: {
        EmailForm,
        userSelect,
        InvoiceProjectChoose,
        WorkPlaceChoose,
        UploadComponent
    },
    computed: mapState({
        userInfo: (state) => state.user.userInfo,
        avatar: (state) => state.user.avatar
    }),
    data() {
        return {
            nodeFlag: false,
            isPreInvoice: '',
            yesNoFlag: [{ name: '否', value: '0' }, { name: '是', value: '1' }],
            bj1: "",
            areaList: [],
            typeList: [{
                name: '专票',
                value: '1',
                disabled: false
            }, {
                name: '普票',
                value: '2',
                disabled: false
            }],
            billingTypeList: [{
                name: '企业开票',
                value: '1',
                disabled: false
            }, {
                name: '个人开票',
                value: '2',
                disabled: false
            }],
            showFileList: [], // 控制每个文件是否显示的数组
            testFlag: false,
            addFlag: false,
            bankList: [],
            inputForm: {
                account: '',
                accountTotal: '',//发票汇总金额
                financeInvoiceBaseDTOList: [],
                financeInvoiceDetailDTOList: [],
                workAttachmentDtoList: [], // 附件信息
                procInsId: '',
                type: '1',
                no: '',
                billingType: '1',
                billingWorkplaceReal: '',
                billingWorkplaceRealId: '',
                taxpayerIdentificationNo: '',
                address: '',
                telPhone: '',
                billingId: '',
                openBank: '',
                bankAccount: '',
                receivablesType: '',
                billingContent: '',
                reportType: '',
                isMultiple: '0',
                billingContentTerms: '',
                billingPeople: '',
                billingPeopleRealName: '',
                billingPeopleReal: '',
                actualDrawerEmailAddress: '',
                reconciliationPeopleName: '',
                reconciliationPeople: '',
                reconciliationArea: '',
                remarks: '',
                name: '',
                nameShow: '',
                billingDate: '',
                collectDate: '',
                programId: '',
            },
            rules: {
                'billingWorkplaceReal': [
                    {
                        required: true,
                        message: '实际开票单位不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'taxpayerIdentificationNo': [
                    {
                        required: true,
                        message: '纳税人识别号不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'billingContent': [
                    {
                        required: true,
                        message: '开票内容不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'billingPeopleRealName': [
                    {
                        required: true,
                        message: '实际开票人不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'reconciliationPeopleName': [
                    {
                        required: true,
                        message: '对账人不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'reconciliationArea': [
                    {
                        required: true,
                        message: '对账地区不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'billingDate': [
                    {
                        required: true,
                        message: '开票时间不能为空',
                        trigger: ['blur', 'change']
                    }
                ],
                'telPhone': [
                    {
                        required: true,
                        message: '电话不能为空',
                        trigger: ['blur', 'change']
                    },
                    {
                        validator: (rule, value, callback) => this.validatePhone(value, callback),
                        trigger: ['blur', 'change']
                    }
                ],
                'actualDrawerEmailAddress': [
                    {
                        validator: (rule, value, callback) => this.checkEmail(value, callback),
                        trigger: ['blur']
                    }
                ],
            }
        }
    },
    ossService: null,
    materialTypeService: null,
    wareHouseService: null,
    commonApi: null,
    // 页面加载时执行
    created() {
        this.ossService = new OSSService()
        this.commonApi = new CommonApi()
        this.materialTypeService = new MaterialTypeService()
        this.wareHouseService = new WareHouseService()

        this.inputForm.actualDrawerEmailAddress = this.userInfo.email
        this.inputForm.handledBy = this.userInfo.name
        this.inputForm.handledById = this.userInfo.id
        this.inputForm.handledByOffice = this.userInfo.officeDTO.id
        this.inputForm.handledByOfficeName = this.userInfo.officeDTO.name

    },
    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: {
        init(id) {
            console.log('this.status', this.status)

            this.nodeFlag = true
            this.inputForm.id = id
            if (id) {
                financeInvoiceService.queryById(id).then((data) => {

                    if (this.status === 'testSee') {
                        this.nodeFlag = true
                        this.testFlag = true
                    } else {
                        this.commonApi.getTaskNameByProcInsId(data.procInsId).then((data) => {
                            if (this.isNotEmpty(data)) {
                                if (data === '发起人重新申请' || this.isEmpty(data)) {
                                    this.nodeFlag = false
                                } else if (data === '发票管理员审核') {
                                    this.nodeFlag = true
                                    this.addFlag = true
                                }
                            } else {
                                this.testFlag = true
                                this.addFlag = true
                                console.log('没有')
                            }
                        })
                    }


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

                    if (this.inputForm.workAttachmentDtoList) {
                        this.inputForm.workAttachmentDtoList.forEach((item, index) => {
                            this.$set(this.showFileList, index, true);
                        })
                    }

                    let i = this.inputForm.financeInvoiceBaseDTOList.length
                    let sun = 0
                    for (let j = 0; j < i; j++) {
                        sun = (100 * sun + 100 * this.inputForm.financeInvoiceBaseDTOList[j].account) / 100
                    }

                    this.inputForm.accountTotal = sun
                    this.inputForm.billingDate = this.formatDate(new Date())
                    if (!this.nodeFlag && this.status !== 'testSee') {
                        this.inputForm.financeInvoiceDetailDTOList.push({
                            code: '',
                            number: '',
                            account: sun,
                            rate: '',
                            amount: '',
                            tax: '',
                            allAmount: ''
                        })
                    }

                    if (!this.isEmpty(this.inputForm.billingWorkplaceRealId)) {
                        this.bankList = []
                        workClientService.queryById(this.inputForm.billingWorkplaceRealId).then((data) => {
                            if (this.isNotEmpty(data.cwWorkClientBillingDTOList)) {
                                data.cwWorkClientBillingDTOList.forEach(i => {
                                    i.ourBank = i.accountHolder
                                    let test = { label: i.ourBank, value: i.id, account: i.account }
                                    this.bankList.push(test)
                                    this.$set(this.inputForm, 'openBank', i.id);
                                })
                            } else {
                                this.bankList = []
                            }
                        })
                    }
                })
            }
        },
        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}`;
        },
        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;
        },
        addRow(type) {
            if (type === 'base') {
                if (this.inputForm.financeInvoiceBaseDTOList.length === 0) {
                    this.inputForm.financeInvoiceBaseDTOList.push({
                        recipientAgent: this.userInfo.name,
                        recipientAgentId: this.userInfo.id, recipientOffice: this.userInfo.officeDTO.name
                    });
                } else {
                    if (this.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programName)) {
                        this.inputForm.financeInvoiceBaseDTOList.push({
                            recipientAgent: this.userInfo.name,
                            recipientAgentId: this.userInfo.id, recipientOffice: this.userInfo.officeDTO.name
                        });
                    } else {
                        uni.showToast({
                            title: '非项目,只能有一条非项目数据',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            } else if (type === 'detail') {
                console.log('this.inputForm.accountTotal', this.inputForm.accountTotal)
                this.inputForm.financeInvoiceDetailDTOList.push({
                    code: '',
                    number: '',
                    account: this.inputForm.accountTotal,
                    rate: '',
                    amount: '',
                    tax: '',
                    allAmount: ''
                })
            }

            // 点击新增按钮时，向表格中添加一行空数据
            // this.inputForm.financeInvoiceBaseDTOList.push({ recipientAgent: this.userInfo.name,
            //     recipientAgentId: this.userInfo.id, recipientOffice: this.userInfo.officeDTO.name });

        },
        removeRow(type, index) {
            if (type === 'base') {
                // 点击删除按钮时，从表格中移除指定行
                this.inputForm.financeInvoiceBaseDTOList.splice(index, 1);

                let currentAccountTotal = 0; // 初始化为 0

                // 遍历 financeInvoiceBaseDTOList，累加每一行的 account
                this.inputForm.financeInvoiceBaseDTOList.forEach(item => {
                    currentAccountTotal += parseFloat(item.account || 0); // 获取当前行的 account，若为空则设为 0
                });

                // 设置新的 accountTotal
                this.$set(this.inputForm, 'accountTotal', currentAccountTotal);
            } else if (type === 'detail') {
                this.inputForm.financeInvoiceDetailDTOList.splice(index, 1);
            }

        },

        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}`;
        },
        handleUploadSuccess(file, fileList) {
            this.inputForm.workAttachmentDtoList = fileList
            // 强制更新视图
            this.$forceUpdate();
        },
        handleRemove(file, fileList) {
            // 处理移除文件逻辑
            // file 是移除的文件
            // fileList 是当前文件列表
            console.log(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())
                };
            });
            this.inputForm.workAttachmentDtoList = formattedFiles
        },
        saveForm(callback) {
            return new Promise((resolve, reject) => {
                // 表单规则验证
                // ...

                let errors = [];

                if (this.isEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
                    errors.push('至少新增一条基本信息');
                } else if (this.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList)) {
                    let i = this.inputForm.financeInvoiceBaseDTOList.length;
                    for (let j = 0; j < i; j++) {
                        let k = j + 1;
                        if (this.isEmpty(this.inputForm.financeInvoiceBaseDTOList[j].programName)) {
                            errors.push('第' + k + '行的基本信息不能为空');
                        }
                        if (this.isEmpty(this.inputForm.financeInvoiceBaseDTOList[j].account)) {
                            errors.push('第' + k + '行的发票金额不能为空');
                        }

                    }
                } else {
                    if (this.inputForm.type === '1') {
                        if (this.isEmpty(this.inputForm.address)) {
                            errors.push('地址不能为空');
                        }
                        if (this.isEmpty(this.inputForm.telPhone)) {
                            errors.push('电话不能为空');
                        }
                        if (this.isEmpty(this.inputForm.openBank)) {
                            errors.push('开户银行不能为空');
                        }
                        if (this.isEmpty(this.inputForm.bankAccount)) {
                            errors.push('银行账号不能为空');
                        }
                    }

                }


                //验证邮箱

                if (this.isNotEmpty(this.inputForm.actualDrawerEmailAddress)) {
                    var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                    if (!reg.test(this.inputForm.actualDrawerEmailAddress)) {
                        errors.push('请输入正确的邮箱地址');
                    }
                }


                if (errors.length > 0) {
                    // 存在错误，显示提示信息
                    errors.forEach(error => {
                        uni.showToast({
                            title: error,
                            icon: 'none',
                            duration: 2000
                        });
                    });
                    reject('Form validation failed');
                } else {
                    this.inputForm.account = this.inputForm.accountTotal
                    // 所有验证通过，执行保存操作
                    this.$refs.inputForm.validate().then(() => {
                        uni.showLoading();
                        this.inputForm.status = '2';
                        financeInvoiceService.saveForm(this.inputForm).then(data => {
                            callback(data.businessTable, data.businessId);
                            resolve('Form saved successfully');
                        }).catch(error => {
                            reject('Save operation failed');
                        });
                    }).catch(() => {
                        reject('Form validation failed');
                    });
                }
            });
        },

        // 修改状态
        async updateStatusById(type, callback) {
            if (type === 'reject' || type === 'reback') {
                financeInvoiceService.queryById(this.inputForm.id).then((data) => {
                    if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
                        this.loading = false
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error()
                    } else {
                        if (type === 'reject') {
                            // 驳回
                            this.inputForm.status = '4'
                        }
                        if (type === 'reback') {
                            // 撤回
                            this.inputForm.status = '3'
                        }
                        if (type === 'reject' || type === 'reback') {
                            let param = { status: this.inputForm.status, id: this.inputForm.id }
                            financeInvoiceService.updateStatusById(param).then(() => {
                                this.loading = false
                                callback()
                            })
                        }
                    }
                })
            } else if (type === 'hold') {
                financeInvoiceService.queryById(this.inputForm.id).then((data) => {
                    if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                        this.loading = false
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error()
                    } else {
                        // 终止
                        let param = { status: '1', id: this.inputForm.id }
                        financeInvoiceService.updateStatusById(param).then(() => {
                            this.loading = false
                            callback()
                        })
                    }
                })
            }
        },
        reapplyForm(callback) {
            this.loading = true
            financeInvoiceService.queryById(this.inputForm.id).then((data) => {
                if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
                    this.loading = false
                    this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                    throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                } else {
                    this.startFormTrue(callback)
                }
            })
        },
        // 送审
        async startFormTrue(callback) {
            this.$refs.inputForm.validate().then(res => {
                this.inputForm.status = '2'
                financeInvoiceService.saveForm(this.inputForm).then((data) => {
                    this.inputForm.id = data.businessId
                    callback(data.businessTable, data.businessId, this.inputForm)
                    this.$refs.inputForm.resetFields()
                    this.loading = false
                }).catch(() => {
                    this.$refs.inputForm.resetFields()
                }).catch((e) => {

                })
            })
        },
        // 通过
        async agreeForm(callback) {

            return new Promise((resolve, reject) => {
                // 表单规则验证
                // ...

                let errors = [];
                let acc = 0
                let i = this.inputForm.financeInvoiceDetailDTOList.length;
                for (let j = 0; j < i; j++) {
                    let k = j + 1;
                    if (this.isEmpty(this.inputForm.financeInvoiceDetailDTOList[j].number)) {
                        errors.push('发票明细中第' + k + ' 条数据的 “发票号” 为空');
                    }
                    if (this.isEmpty(this.inputForm.financeInvoiceDetailDTOList[j].account)) {
                        errors.push('发票明细中第' + k + ' 条数据的 “开票金额” 为空');
                    }
                    acc = (acc + parseFloat(parseFloat(this.inputForm.financeInvoiceDetailDTOList[j].account).toFixed(2)))
                }

                if (parseFloat(acc).toFixed(2) !== parseFloat(this.inputForm.account).toFixed(2)) {
                    errors.push('发票明细中 “开票金额”总和 与发票详情中 “发票金额” 不等');
                }

                this.inputForm.financeInvoiceDetailDTOList.forEach((item, index) => {
                    this.inputForm.financeInvoiceDetailDTOList.forEach((item2, index2) => {
                        if (index !== index2) {
                            if (item.number === item2.number) {
                                errors.push('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 存在重复');
                            }
                        }
                    })
                })

                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.status = '5'
                        financeInvoiceService.saveForm(this.inputForm).then((data) => {
                            callback(data.businessTable, data.businessId, this.inputForm)
                            this.$refs.inputForm.resetFields()
                            this.loading = false
                        }).catch(() => {
                            this.loading = false
                            this.$refs.inputForm.resetFields()
                        })
                    })
                }
            });
        },
        shouldShowFile(file) {
            if (this.inputForm.workAttachmentDtoList && this.inputForm.workAttachmentDtoList.length > 0) {
                // 返回一个布尔值，确定是否显示上传成功后的文件
                return this.showFileList[this.inputForm.workAttachmentDtoList.indexOf(file)];
            }
            return false; // 默认返回 false 或者其他适当的
        },
        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
                // 如果不是图片文件，则执行其他操作，比如下载文件等
            }
        },
        handleImageClick(file) {
            // 在点击图片时执行放大显示的逻辑
            this.$alert(`<img src="${file.lsUrl}" style="max-width: 100%; max-height: 100%;" />`, '图片详情', {
                dangerouslyUseHTMLString: true,
                customClass: 'custom-alert'
            });
        },
        // 判断文件是否是图片类型
        isImage(fileName) {
            const ext = fileName.toLowerCase().split('.').pop(); // 获取文件的后缀名
            return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext); // 判断后缀名是否是图片类型
        },
        handleDelete(file, fileList, index) {
            // this.handleRemove(file, fileList)
            // 从文件列表中移除文件
            this.inputForm.workAttachmentDtoList.splice(index, 1);
        },
        // 输入值改变事件处理程序
        onInputCode(index, event, type) {
            const inputValue = event
            const formattedValue = this.formatInput(inputValue);
            if (type === 'account') {
                this.$set(this.inputForm.financeInvoiceBaseDTOList[index], 'account', formattedValue)
                // 计算 accountTotal 的新值
                const currentAccountTotal = parseFloat(this.inputForm.accountTotal || 0); // 获取当前 accountTotal，若为空则设为 0
                const newAccountTotal = currentAccountTotal + parseFloat(formattedValue);

                // 设置新的 accountTotal
                this.$set(this.inputForm, 'accountTotal', newAccountTotal);
            }
        },
        // 通用的输入限制和格式化方法
        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;
        },
        reimbursementTypeChange(value) {
            this.inputForm.address = ''
            this.inputForm.telPhone = ''
            this.inputForm.billingId = ''
            this.inputForm.billingWorkplaceReal = ''
            this.inputForm.billingWorkplaceRealId = ''
            this.inputForm.taxpayerIdentificationNo = ''
            this.bankList = []
            this.inputForm.bankAccount = ''
            this.inputForm.openBank = ''
            this.inputForm.name = ''
        },
        openUserPullForm(index, type) {
            // 点击 "采购人" 输入框时打开userPullForm页面，传入index用于区分不同的行
            // uni.navigateTo({
            //     url: '/pages/materialManagement/collect/UserPullForm?index=' + index // userPullForm页面的路径
            // });
            this.$refs.userPicker.open(index, type);
        },
        handleEvent(data, index, type) {
            if (type === '实际') {
                this.inputForm.billingPeopleRealName = data.label
                this.inputForm.billingPeopleReal = data.id
            } else if (type === '对账') {
                this.inputForm.reconciliationPeopleName = data.label
                this.inputForm.reconciliationPeople = data.id
            } else if (type === '姓名') {
                this.inputForm.nameShow = data.label
                this.inputForm.name = data.id
            }

        },
        // 显示  项目选择器
        showProject(index) {
            if (this.inputForm.financeInvoiceBaseDTOList.length > 0 && this.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList[0].programName)) {
                if (this.isNotEmpty(this.inputForm.financeInvoiceBaseDTOList[0].reportNo)) {
                    this.$refs.invoiceProjectChoose.init(index, '2');
                } else {
                    this.$refs.invoiceProjectChoose.init(index, '1');

                }
            } else {
                this.$refs.invoiceProjectChoose.init(index);
            }

        },
        // 实际开票单位选择
        showWorkplace() {
            this.$refs.workPlaceChoose.init();

        },
        selectProjectChange(rows, index) {
            if (rows.length > 0) {
                rows.forEach((item, rowIndex) => {
                    this.inputForm.programId = item.id;
                    if (rowIndex === 0) {
                        let r = this.inputForm.financeInvoiceBaseDTOList[index];
                        if (!r) {
                            r = {};
                        }
                        r.programName = item.projectName;
                        r.contractName = item.contractName;
                        r.programNo = item.projectNumber;
                        r.contractId = item.contractId;
                        r.programId = item.id;
                        r.reportNo = item.reportNo;
                        r.reportType = item.reportType;
                        r.isPreInvoice = item.isPreInvoice;
                        this.$set(this.inputForm.financeInvoiceBaseDTOList, index, r);
                    } else {
                        let r = {
                            programName: item.projectName,
                            contractName: item.contractName,
                            programNo: item.projectNumber,
                            contractId: item.contractId,
                            programId: item.id,
                            reportNo: item.reportNo,
                            reportType: item.reportType,
                            isPreInvoice: item.isPreInvoice
                        }
                        this.inputForm.financeInvoiceBaseDTOList.push(r);
                    }
                });
            } else {
                let r = {
                    programName: rows.projectName,
                    contractName: rows.contractName,
                    programNo: rows.projectNumber,
                    contractId: rows.contractId,
                    programId: rows.id,
                    reportNo: rows.reportNo,
                    reportType: rows.reportType,
                    isPreInvoice: rows.isPreInvoice
                }
                if (!this.inputForm.detailInfoReports) {
                    this.$set(this.inputForm, 'detailInfoReports', []);
                }
                this.$set(this.inputForm.detailInfoReports, index, r);
                this.isPreInvoice = rows.isPreInvoice;
                this.inputForm.programId = rows.id;
            }
        },
        getWorkClient(row) {
            this.bankList = []
            this.inputForm.billingWorkplaceReal = row.name // 实际开票单位姓名
            this.inputForm.billingWorkplaceRealId = row.id // 实际开票单位id ‘客户id’
            this.inputForm.taxpayerIdentificationNo = this.isEmpty(row.uscCode) ? '' : row.uscCode // 纳税人识别号 ‘统一社会信用代码’
            this.inputForm.address = this.isEmpty(row.address) ? '' : row.address // 地址
            this.inputForm.telPhone = this.isEmpty(row.mobile) ? '' : row.mobile // 电话
            this.inputForm.billingId = '' // 实际开票单位的开票信息id
            // this.inputForm.telPhone = '' // 电话
            for (let i = 0; i < row.cwWorkClientBillingDTOList.length; i++) {
                row.cwWorkClientBillingDTOList[i].ourBank = row.cwWorkClientBillingDTOList[i].accountHolder
                let test = { label: row.cwWorkClientBillingDTOList[i].ourBank, value: row.cwWorkClientBillingDTOList[i].id, account: row.cwWorkClientBillingDTOList[i].account }
                this.bankList.push(test)
            }
            // row.cwWorkClientBillingDTOList.forEach(item => {
            //     item.ourBank = item.accountHolder
            //     this.bankList.push(item)
            // })
            this.inputForm.bankAccount = ''
            this.inputForm.openBank = ''
            this.$forceUpdate()
        },
        changeBank(value) {
            this.bankList.forEach(item => {
                if (item.value === value) {
                    this.inputForm.bankAccount = item.account
                }
            })
        },
        validatePhone(str, callback) {
            const phone = /(^(\d{3,4}-)?\d{6,8}$)|(^(\d{3,4}-)?\d{6,8}(-\d{1,5})?$)|(^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$)/
            if (str && !phone.test(str)) {
                callback(new Error('请输入正确的电话号码'))
            } else {
                callback()
            }
        },
        checkEmail(str, callback) {
            if (!this.isNotEmpty(str)) {
                callback(); // 输入框为空时不进行验证，直接清除错误提示
                return;
            }

            var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
            if (!reg.test(str)) {
                callback(new Error('请输入正确的邮箱地址'))
            } else {
                callback()
            }
        },
        openDia() {
            let id = this.userInfo.id
            let userEmail = this.inputForm.actualDrawerEmailAddress
            this.$refs.emailForm.init(id, userEmail);
        },
        emailForm(row) {
            this.inputForm.actualDrawerEmailAddress = row
        },
        checkRate(rate, rowIndex) {
            if (!this.isEmpty(rate)) {
                if (parseFloat(rate) < 1 || parseFloat(rate) > 100) {
                    uni.showToast({
                        title: '“税率” 请填写 1 到 100 之间的数字，请重新输入',
                        icon: 'none',
                        duration: 2000
                    });
                    rate = ''
                }
            }
            this.getAmount(rate, rowIndex)
            this.getTax(rate, rowIndex)
        },
        // 根据开票金额和税率计算出金额: 开票金额-税率*开票金额
        getAmount(rate, rowIndex) {
            let amount = this.inputForm.financeInvoiceDetailDTOList[rowIndex].amount
            let account = this.inputForm.financeInvoiceDetailDTOList[rowIndex].account
            if (!this.isEmpty(account) && !this.isEmpty(rate)) {
                amount = parseFloat((parseFloat(account) - parseFloat((parseFloat(account) * parseFloat((parseFloat(rate) / 100).toFixed(4))).toFixed(4))).toFixed(2))
            } else {
                amount = ''
            }
            this.$set(this.inputForm.financeInvoiceDetailDTOList[rowIndex], 'amount', amount)
        },
        // 根据开票金额和税率计算出税额: 税率*开票金额
        getTax(rate, rowIndex) {
            let tax = this.inputForm.financeInvoiceDetailDTOList[rowIndex].tax
            let account = this.inputForm.financeInvoiceDetailDTOList[rowIndex].account
            if (!this.isEmpty(account) && !this.isEmpty(rate)) {
                tax = parseFloat((parseFloat(account) * parseFloat((parseFloat(rate) / 100).toFixed(4))).toFixed(2))
            } else {
                tax = ''
            }
            this.$set(this.inputForm.financeInvoiceDetailDTOList[rowIndex], 'tax', tax)
        },
        // 下载模板
        downloadTpl() {
            financeInvoiceService.exportTemplate().then((res) => {
                console.log('res', res)
                // 将二进制流文件写入excel表，以下为重要步骤
                this.downloadExcel(res, '发票明细导入模板')
            }).catch(function (err) {
                if (err.response) {
                    console.log(err.response)
                }
            })
        },
        downloadExcel(data, filename) {
            if (filename.indexOf(".xls") === -1) {
                filename = filename + ".xls"
            }
            var blob = new Blob([data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            }); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); // 创建下载的链接
            downloadElement.href = href;
            downloadElement.download = filename; // 下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); // 点击下载
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
        },
        async validateNumber(index) {
            const numberString = this.inputForm.financeInvoiceDetailDTOList[index].number.trim(); // 去除空格
            let errorDetected = false; // 布尔变量用于检测是否有错误发生

            if (this.isNotEmpty(numberString)) {
                if (!/^\d+$/.test(numberString)) { // 使用正则表达式检查是否只包含数字字符
                    uni.showToast({
                        title: '发票号只能输入整数',
                        icon: 'none',
                        duration: 2000
                    });
                    errorDetected = true; // 如果有错误，设置为 true
                }

                // 验证发票号是否大于 8 位
                if (parseInt(numberString) > 99999999) {
                    uni.showToast({
                        title: '“发票号” 不可以大于 8 位，请重新输入',
                        icon: 'none',
                        duration: 2000
                    });
                    errorDetected = true; // 如果有错误，设置为 true
                }

                // 验证是否重复
                for (let i = 0; i < this.inputForm.financeInvoiceDetailDTOList.length; i++) {
                    if (index !== i && numberString === this.inputForm.financeInvoiceDetailDTOList[i].number) {
                        uni.showToast({
                            title: '“发票号” 已存在，请重新输入',
                            icon: 'none',
                            duration: 2000
                        });
                        errorDetected = true; // 如果有错误，设置为 true
                        break; // 找到重复即可跳出循环
                    }
                }

                // 查询是否已存在
                await financeInvoiceService.queryByNumber(numberString, '').then((data) => {
                    if (data === true) {
                        uni.showToast({
                            title: '“发票号” 已存在，请重新输入',
                            icon: 'none',
                            duration: 2000
                        });
                        errorDetected = true; // 如果有错误，设置为 true
                    }
                });

                // 只在发生错误时清空输入字段
                if (errorDetected) {
                    this.$set(this.inputForm.financeInvoiceDetailDTOList[index], 'number', '');
                }
            }

        }



    }
}
</script>

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

/* 样式示例，您可能需要根据实际情况调整 */
.upload-demo {
    width: 40%;
}

.button-container {
    margin-top: 10px;
    text-align: right;
}
</style>
