<template>
    <view>
        <cu-custom :backUrl="'/pages/index/index?id=apps'" :isBack="true" bgColor="bg-gradual-blue" >
            <block slot="content">建筑垃圾处理</block>
        </cu-custom>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="!nodeFlag" >


            <u-form-item label="巡视工单" prop="no"
                         :rules="[
				     ]">
                <u--input v-model="inputForm.no" :disabled="true" placeholder="工单编号" clearable></u--input>
            </u-form-item>

            <u-form-item label="处理单位" borderBottom prop="processingUnit" :required="true">
                <jp-picker v-model="inputForm.processingUnit" 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="清运专员" prop="clearUserName"
                         :rules="[
				     ]">
                <u--input v-model="inputForm.clearUserName" :disabled="true" placeholder="清运专员" clearable></u--input>
            </u-form-item>

            <u-form-item label="联系方式" prop="clearUserMobile"
                         :rules="[
				     ]">
                <u--input v-model="inputForm.clearUserMobile" :disabled="true" placeholder="联系方式" clearable></u--input>
            </u-form-item>

            <view class="u-demo-block">
                <text class="u-demo-block__title">基础用法</text>
                <view class="u-demo-block__content">
                    <view class="u-page__upload-item">
                        <u-upload
                                :fileList="fileList1"
                                @afterRead="afterRead"
                                @delete="deletePic"
                                name="1"
                                multiple
                                :maxCount="10"
                        ></u-upload>
                    </view>
                </view>
            </view>

        </u--form>
    </view>
</template>

<script>
    import {mapState, mapMutations, mapActions} from 'vuex'
    import * as $auth from "../../common/auth";
    export default {
        components: {
        },
        computed: mapState({
            userInfo: (state) => state.user.userInfo,
            avatar: (state) => state.user.avatar
        }),
        data () {
            return {
                fileList1: [],
                nodeFlag: false,
                inputForm: {
                    no: '',
                    processingUnit: '',
                    clearUserId: '',
                    clearUserName: '',
                    clearUserMobile: ''
                },
                rules: {
                    /*'billingWorkplaceReal': [
                        {
                            required: true,
                            message: '实际开票单位不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],*/
                }
            }
        },
        /*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: {
            status: {
                type: String,
                default: ''
            }
        },
        watch: {
        },
        methods: {
           init (id) {
               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;
            },

            formatDateNew(date) {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            saveForm(callback) {
                return new Promise((resolve, reject) => {
                    // 表单规则验证
                    // ...

                    let errors = [];


                    /*if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 2000
                            });
                        });
                        reject('Form validation failed');
                    } else {
                        this.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

                    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()
                            })
                        })
                    }
                });
            },*/

            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`fileList${event.name}`].length
                lists.map((item) => {
                    this[`fileList${event.name}`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(url) {
                console.log($auth.getUserToken())
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: 'http://localhost:8000/app/file/upload', // 仅为示例，非真实的接口地址
                        filePath: url,
                        name: 'file',
                        formData: {
                            user: this.$store.state.user.userInfo
                        },
                        header: {
                            'token': $auth.getUserToken(),
                        },
                        success: (res) => {
                            setTimeout(() => {
                                resolve(res.data.data);
                            }, 1000);
                        },
                        fail: (err) => {
                            console.error('Upload failed:', err);
                        }
                    });
                })
            },
        }
    }
</script>

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

    /* 样式示例，您可能需要根据实际情况调整 */
    .upload-demo {
        width: 40%;
    }
    .button-container {
        margin-top: 10px;
        text-align: right;
    }
</style>
