<template>
    <view>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm">
            <!-- 动态生成发票基本信息 -->
            <el-row :gutter="15" v-for="(item, index_experience) in inputForm.workInvoiceProjectRelationList" :key="index_experience">
                <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="'workInvoiceProjectRelationList[' + index_experience + '].projectName'">
                        <u--input v-model="item.projectName" :disabled="true" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="合同名称" :prop="'workInvoiceProjectRelationList[' + index_experience + '].workContractName'">
                        <u--input v-model="item.workContractName" :disabled="true" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="项目编号" :prop="'workInvoiceProjectRelationList[' + index_experience + '].projectNum'">
                        <u--input v-model="item.projectNum" :disabled="true" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="委托方" :prop="'workInvoiceProjectRelationList[' + index_experience + '].clientName'">
                        <u--input v-model="item.clientName" :disabled="true" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="报告号" :prop="'workInvoiceProjectRelationList[' + index_experience + '].reportDataNum'">
                        <u--input v-model="item.reportDataNum" :disabled="true" clearable></u--input>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="">
                <u-divider :text="`发票详情`"></u-divider>
            </u-form-item>
            <u-form-item label="发票类型" prop="invoiceTypeName">
                <u--input v-model="inputForm.invoiceTypeName" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票类型" prop="newDrawerName">
                <u--input v-model="inputForm.newDrawerName" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="实际开票单位" prop="clientName">
                <u--input v-model="inputForm.clientName" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="纳税人识别号" prop="taxpayerIdentificationNo">
                <u--input v-model="inputForm.taxpayerIdentificationNo" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="地址" prop="address">
                <u--input v-model="inputForm.address" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="电话" prop="telephone">
                <u--input v-model="inputForm.telephone" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="开户银行" prop="bank">
                <u--input v-model="inputForm.bank" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="银行账号" prop="bankNumber">
                <u--input v-model="inputForm.bankNumber" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="收款类型" prop="chargeType">
                <u--input v-model="inputForm.chargeType" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票内容" prop="billingContent">
                <u--input v-model="inputForm.billingContent" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="发票金额(元)" prop="money">
                <u--input v-model="inputForm.money" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票内容要求" prop="content">
                <u--input v-model="inputForm.content" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票人" prop="drawerName">
                <u--input v-model="inputForm.drawerName" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="开票时间" prop="invoiceDate" :required="true">
                <el-date-picker
                        v-model="inputForm.invoiceDate"
                        type="date"
                        placeholder="选择开票时间"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="领票时间" prop="takeDate">
                <el-date-picker
                        v-model="inputForm.takeDate"
                        type="date"
                        placeholder="选择领票时间"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="实际开票人" prop="actualDrawerName">
                <u--input v-model="inputForm.actualDrawerName" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="接收邮箱" prop="actualDrawerEmailAddress">
                <u--input v-model="inputForm.actualDrawerEmailAddress" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="对账人" prop="accountCheckingUserName">
                <u--input v-model="inputForm.accountCheckingUserName" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="对账地区" prop="area">
                <u--input v-model="inputForm.area" :disabled="true" clearable></u--input>
            </u-form-item>
            <u-form-item label="备注" prop="remarks">
                <u--input v-model="inputForm.remarks" :disabled="true" clearable></u--input>
            </u-form-item>

            <el-row  :gutter="15" :key="item.id" v-for="(item,index_experience) in this.inputForm.workAccountList">
                <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="'workAccountList[' + index_experience + '].code'"
                                 :rules="[
				     ]">
                        <u--input v-model="item.code" placeholder="请填写发票代码" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="发票号" :prop="'workAccountList[' + index_experience + '].number'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="item.number" placeholder="请填写发票号" @blur="validateNumber(index_experience)" clearable></u--input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="开票金额(元)" :prop="'workAccountList[' + index_experience + '].account'" :required="true"
                                 :rules="[
                    { validator: validateAmount, trigger: 'blur' }
                 ]">
                        <u-input v-model="item.account" placeholder="请填写开票金额(元)" clearable @input="handleInput($event, index_experience)" @blur="handleBlur($event, index_experience)"></u-input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="税率(%)" :prop="'workAccountList[' + index_experience + '].rate'"
                                 :rules="[
				     ]">
                        <u-input v-model="item.rate" placeholder="请填写税率(%)" @input="handleRateInput($event, index_experience)" @blur="checkRate($event, index_experience)" clearable></u-input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="金额" :prop="'workAccountList[' + index_experience + '].amount'"
                                 :rules="[
				     ]">
                        <u-input v-model="item.amount" placeholder="请填写金额" readonly clearable></u-input>
                    </u-form-item>
                </el-col>
                <el-col :span="24">
                    <u-form-item label="税额" :prop="'workAccountList[' + index_experience + '].tax'"
                                 :rules="[
				     ]">
                        <u-input v-model="item.tax" placeholder="请填写税额" readonly 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(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()" 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.files"
                        :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,'')"
                        :limit="3">
                    <el-button size="small" type="primary" v-if="false">点击上传</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>
                    </template>
                </el-upload>
            </u-form-item>
        </u--form>
    </view>
</template>


<script>
    import ccpmService from '@/api/centerservice/ccpm/CcpmService'
    import OSSService from "@/api/sys/OSSService";
    import moment from "moment";

    export default {
        name: 'DynamicForm',
        props: {
            invoice: {
                type: Array,
                required: true
            },
        },
        data() {
            return {
                inputForm: {
                    workInvoiceProjectRelationList: [],
                    workAccountList: [],
                    invoiceTypeName: "",
                    newDrawerName: "",
                    clientName: "",
                    taxpayerIdentificationNo: "",
                    address: "",
                    telephone: "",
                    bank: "",
                    bankNumber: "",
                    chargeType: "",
                    billingContent: "",
                    money: "",
                    content: "",
                    drawerName: "",
                    invoiceDate: "",
                    takeDate: "",
                    actualDrawerName: "",
                    actualDrawerEmailAddress: "",
                    accountCheckingUserName: "",
                    area: "",
                    remarks: "",
                    files: []
                },
                rules: {
                    invoiceDate: [
                        {
                            required: true,
                            message: '开票时间不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                },
                isDeletingRow: false,  // 标志变量
            };
        },
        ossService: null,
        created() {
            this.ossService = new OSSService();
        },
        watch: {
            invoice: {
                handler(newVal) {
                    this.assignment();
                },
                deep: true,
                immediate: true
            }
        },
        methods: {
            getInputForm() {
                return this.inputForm;
            },
            assignment() {
                if (this.isDeletingRow) {
                    return;  // 如果正在删除行，则不执行此方法
                } else {
                    if (Array.isArray(this.invoice) && this.invoice.length > 0) {
                        this.inputForm = this.recover(this.inputForm, this.invoice[0])
                        // this.inputForm = this.invoice[0];
                        if (this.isEmpty(this.inputForm.invoiceDate)) {
                            this.inputForm.invoiceDate = moment(new Date()).format('YYYY-MM-DD');
                        }
                        if(this.isEmpty(this.inputForm.workAccountList) || this.inputForm.workAccountList.length === 0 ) {
                            this.inputForm.workAccountList.push({
                                code: '',
                                number: '',
                                account: this.inputForm.money,
                                rate: '',
                                amount: '',
                                tax: '',
                                allAmount: ''
                            })
                        }
                    }
                }

            },
            isEmpty(value) {
                return value == null || value === undefined || (typeof value === 'string' && value.trim() === '') || (Array.isArray(value) && value.length === 0);
            },
            isNotEmpty(value) {
                return !this.isEmpty(value);
            },
            shouldShowFile(file) {
                if (this.inputForm.files && this.inputForm.files.length > 0) {
                    return this.inputForm.files.indexOf(file) !== -1;
                }
                return false;
            },
            async handleFileClick(file) {
                await this.ossService.getTemporaryUrl(file.url).then((data) => {
                    file.lsUrl = data;
                });
                if (this.isImage(file.name)) {
                    this.handleImageClick(file.lsUrl);
                } else {
                    window.location.href = file.lsUrl;
                }
            },
            isImage(fileName) {
                const ext = fileName.toLowerCase().split('.').pop();
                return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext);
            },
            handleImageClick(url) {
                uni.previewImage({
                    current: url,
                    urls: [url],
                });
            },
            handleDelete(file) {
                const index = this.inputForm.files.indexOf(file);
                if (index !== -1) {
                    this.inputForm.files.splice(index, 1);
                }
            },
            async validateNumber(index) {
                const numberString = this.inputForm.workAccountList[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.workAccountList.length; i++) {
                        if (index !== i && numberString === this.inputForm.workAccountList[i].number) {
                            uni.showToast({
                                title: '“发票号” 已存在，请重新输入',
                                icon: 'none',
                                duration: 2000
                            });
                            errorDetected = true; // 如果有错误，设置为 true
                            break; // 找到重复即可跳出循环
                        }
                    }

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

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

            },
            // 根据开票金额和税率计算出金额: 开票金额-税率*开票金额
            getAmount(rate,rowIndex) {
                let amount = this.inputForm.workAccountList[rowIndex].amount
                let account = this.inputForm.workAccountList[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.workAccountList[rowIndex], 'amount', amount)
            },
            // 根据开票金额和税率计算出税额: 税率*开票金额
            getTax(rate,rowIndex) {
                let tax = this.inputForm.workAccountList[rowIndex].tax
                let account = this.inputForm.workAccountList[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.workAccountList[rowIndex], 'tax', tax)
            },
            validateAmount(rule, value, callback) {
                const reg = /^\d+(\.\d{1,2})?$/;
                if (!value) {
                    callback(new Error('请输入开票金额'));
                } else if (!reg.test(value)) {
                    callback(new Error('请输入有效的开票金额，最多两位小数'));
                } else {
                    callback();
                }
            },
            handleInput(event, index) {
                const value = event;
                const reg = /^\d*\.?\d{0,2}$/;
                if (!reg.test(value)) {
                    // 保留符合规则的部分
                    const validValue = value.slice(0, -1);

                    this.$nextTick(() => {
                        this.$set(this.inputForm.workAccountList[index], 'account', validValue);
                    });
                } else {
                    this.$set(this.inputForm.workAccountList[index], 'account', value);
                }
            },
            handleBlur(event, index) {
                const value = event;
                if (!value || isNaN(value)) {
                    this.$set(this.inputForm.workAccountList[index], 'account', '');
                } else {
                    const formattedValue = parseFloat(value).toFixed(2);

                    this.$nextTick(() => {
                        this.$set(this.inputForm.workAccountList[index], 'account', formattedValue);
                    });
                }
            },
            handleRateInput(event, rowIndex) {
                const value = event;
                const reg = /^\d*\.?\d{0,2}$/;
                if (!reg.test(value)) {
                    // 保留符合规则的部分
                    const validValue = value.slice(0, -1);

                    this.$nextTick(() => {
                        this.$set(this.inputForm.workAccountList[rowIndex], 'rate', validValue);
                    });
                } else {
                    this.$set(this.inputForm.workAccountList[rowIndex], 'rate', value);
                }
            },
            checkRate(event, rowIndex) {
                const value = event;
                if (!value || isNaN(value)) {
                    this.$set(this.inputForm.workAccountList[rowIndex], 'rate', '');
                } else {
                    let validValue = parseFloat(value);
                    if (!this.isEmpty(value)) {
                        if (validValue < 1 || validValue > 100) {
                            uni.showToast({
                                title: '“税率” 请填写 1 到 100 之间的数字，请重新输入',
                                icon: 'none',
                                duration: 2000
                            });
                            validValue = '';
                        } else {
                            validValue = validValue.toFixed(2);
                        }
                    }

                    this.$nextTick(() => {
                        this.$set(this.inputForm.workAccountList[rowIndex], 'rate', validValue);
                    });
                    this.getAmount(validValue, rowIndex);
                    this.getTax(validValue, rowIndex);
                }

            },
            addRow() {
                this.inputForm.workAccountList.push({
                    code: '',
                    number: '',
                    account: '',
                    rate: '',
                    amount: '',
                    tax: '',
                    allAmount: ''
                })
            },
            removeRow(index) {
                this.isDeletingRow = true;  // 设置标志变量
                this.inputForm.workAccountList.splice(index, 1);
            },
        }
    };
</script>


<style scoped>
    .upload-demo {
        margin-top: 10px;
    }
</style>
