<template>
    <view>
        <cu-custom :backUrl="'/pages/index/index?id=apps'" :isBack="true" bgColor="bg-gradual-blue" v-if="!nodeFlag">
            <block slot="content">建筑垃圾巡查</block>
        </cu-custom>

        <!-- First Section: 巡查工单 to 联系方式 -->
        <view class="form-section">
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="!nodeFlag">

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

                <u-form-item label="处理单位" borderBottom prop="processingUnit" :required="true" v-if="!disFlag">
                    <jp-picker v-model="inputForm.processingUnit" rangeKey="label" rangeValue="value" :range="processingUnits" @input="getOfficeOnHamlet"></jp-picker>
                </u-form-item>

                <u-form-item label="处理单位" borderBottom prop="processingUnitName" :required="true" v-else-if="disFlag">
                    <u--input v-model="inputForm.processingUnitName" :disabled="true" placeholder="处理单位" clearable></u--input>
                </u-form-item>

                <u-form-item label="村负责人" prop="clearUserName">
                    <u--input v-model="inputForm.clearUserName" :disabled="true" placeholder="村负责人" clearable></u--input>
                </u-form-item>

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

            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="nodeFlag">

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

                <u-form-item label="处理单位" borderBottom prop="processingUnit" :required="true" v-if="!disFlag">
                    <jp-picker v-model="inputForm.processingUnit" rangeKey="label" rangeValue="value" :range="processingUnits" @input="getOfficeOnHamlet"></jp-picker>
                </u-form-item>

                <u-form-item label="处理单位" borderBottom prop="processingUnitName" :required="true" v-else-if="disFlag">
                    <u--input v-model="inputForm.processingUnitName" :disabled="true" placeholder="处理单位" clearable></u--input>
                </u-form-item>

                <u-form-item label="村负责人" prop="clearUserName">
                    <u--input v-model="inputForm.clearUserName" :disabled="true" placeholder="村负责人" clearable></u--input>
                </u-form-item>

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

        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="!nodeFlag">
            <text class="u-demo-block__title">现场照片</text>
            <view class="u-page__upload-item">
                <u-upload
                        :fileList="fileList1"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="1"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>
        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="nodeFlag">
            <text class="u-demo-block__title">清理前照片</text>
            <view class="u-page__upload-item">
                <u-upload
                        :disabled="true"
                        :fileList="fileList1"
                        name="1"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>

        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="nodeFlag">
            <text class="u-demo-block__title">清理中照片</text>
            <view class="u-page__upload-item" v-if="showFlag">
                <u-upload
                        :disabled="true"
                        :fileList="fileList2"
                        name="2"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
            <view class="u-page__upload-item" v-else>
                <u-upload
                        :fileList="fileList2"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="2"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>

        <!-- Second Section: 上传图片 -->
        <view class="form-section" v-if="nodeFlag">
            <text class="u-demo-block__title">清理后照片</text>
            <view class="u-page__upload-item" v-if="showFlag">
                <u-upload
                        :disabled="true"
                        :fileList="fileList3"
                        name="3"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
            <view class="u-page__upload-item" v-else>
                <u-upload
                        :fileList="fileList3"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="3"
                        multiple
                        :maxCount="10"
                ></u-upload>
            </view>
        </view>

        <!-- Third Section: 备注 -->
        <view class="form-section">
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="!nodeFlag">
                <u-form-item label="备注" borderBottom prop="remarks">
                    <u--textarea placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks"></u--textarea>
                </u-form-item>

                <!--<view class="button-container">
                    <u-button
                            text="提交"
                            size="large"
                            type="primary"
                            @click="saveForm"
                    ></u-button>
                </view>-->
                <!-- 遮罩层 -->
                <view v-if="isProcessing" class="mask"></view>
            </u--form>
            <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="nodeFlag">
                <u-form-item label="备注" borderBottom prop="remarks">
                    <u--textarea placeholder='请填写备注' :maxlength="500" :disabled="true" v-model="inputForm.remarks"></u--textarea>
                </u-form-item>

                <view class="button-container" v-if="!showFlag">
                    <u-button
                            text="确认"
                            size="large"
                            type="primary"
                            @click="savePhoto"
                    ></u-button>
                </view>
            </u--form>
        </view>
    </view>
</template>

<script>
    import overService from '@/api/garbageClearance/overService'
    import {mapState, mapMutations, mapActions} from 'vuex'
    import * as $auth from "../../common/auth";
    import { EventBus } from '@/store/eventBus.js';
    export default {
        components: {
        },
        computed: mapState({
            userInfo: (state) => state.user.userInfo,
            avatar: (state) => state.user.avatar
        }),
        data () {
            return {
                disFlag: true,  // 启用动态获取处理单位则设置为false
                showFlag: false,
                isProcessing: false,  // 遮罩层
                uploadFlag: true,  // 上传判定值
                processingUnits: [],
                fileList1: [],
                fileList2: [],
                fileList3: [],
                nodeFlag: false,
                inputForm: {
                    id: '',
                    no: '',
                    processingUnit: '',
                    processingUnitName: '',
                    clearUserId: '',
                    clearUserName: '',
                    clearUserMobile: '',
                    remarks: '',
                },
                rules: {
                    'processingUnit': [
                        {
                            required: true,
                            message: '处理单位不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                }
            }
        },
        // 页面加载时执行
        async created() {
            if('乡镇巡查员' === this.userInfo.roleNames){
                this.disFlag = false
                // 不动态获取  根据当前登录人去查
                await overService.getOfficeOnHamlet()
                    .then(data => {
                        this.processingUnits = []
                        for (const value of data) {
                            this.processingUnits.push({
                                label: value.officeName,
                                value: value.officeId
                            });
                        }
                    })
                    .catch(e => {
                        throw e;
                    });
            }
            if(!this.nodeFlag){
                let data = await overService.getMaxNo();
                this.inputForm.no = data;
                /*if (data) {
                    let newNo = parseInt(data, 10) + 1;
                    this.inputForm.no = 'XS-J' + newNo;
                } else {
                    // 获取当前年份
                    let nowY = new Date().getFullYear();
                    this.inputForm.no = 'XS-J' + nowY + '0001';
                }*/

                // 如果要使用动态获取处理单位则设置为true
                if (false) {
                    let units = await overService.getProcessingUnit();
                    let childs = units[0].children;

                    if (childs) {
                        this.processingUnits = [];  // 初始化数组

                        for (let i = 0; i < childs.length; i++) {
                            this.processingUnits.push({
                                label: childs[i].name,
                                value: childs[i].id
                            });
                        }
                    }
                }

                this.inputForm.processingUnit = this.userInfo.officeDTO.id
                this.inputForm.processingUnitName = this.userInfo.officeDTO.name
                // 不动态获取  根据当前登录人去查
                await overService.getUserInfoByOffId(this.userInfo.officeDTO.id)
                    .then(data => {
                        this.inputForm.clearUserId = data.id
                        this.inputForm.clearUserName = data.name
                        this.inputForm.clearUserMobile = data.mobile
                    })
                    .catch(e => {
                        throw e;
                    });
            }



        },
        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
            },
        },
        onLoad(options) {
            // 从 options 中获取 id 参数
            this.showFlag = options.showFlag;
            this.id = options.id;
            // 这里可以调用初始化方法
            this.init(this.id);
        },
        methods: {
            async init (id) {
                if(id){
                    this.nodeFlag = true
                    this.inputForm.id = id
                    if (id) {

                        await overService.queryById(id).then((data) => {

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

                            if (data.beforeFileList) {
                                this.fileList1 = []
                                data.beforeFileList.forEach(
                                    (item) => {
                                        const newItem = {
                                            attachmentName: item.name,
                                            fileSize: item.size,
                                            url: item.temporaryUrl,
                                            type: item.type,      // 如果不需要，可以不写
                                        };
                                        this.fileList1.push(newItem);
                                    }
                                );
                            }
                            if (data.betweenFileList) {
                                this.fileList2 = []
                                data.betweenFileList.forEach(
                                    (item) => {
                                        const newItem = {
                                            attachmentName: item.name,
                                            fileSize: item.size,
                                            url: item.temporaryUrl,
                                            type: item.type,      // 如果不需要，可以不写
                                        };
                                        this.fileList2.push(newItem);
                                    }
                                );
                            }
                            if (data.afterFileList) {
                                this.fileList3 = []
                                data.afterFileList.forEach(
                                    (item) => {
                                        const newItem = {
                                            attachmentName: item.name,
                                            fileSize: item.size,
                                            url: item.temporaryUrl,
                                            type: item.type,      // 如果不需要，可以不写
                                        };
                                        this.fileList3.push(newItem);
                                    }
                                );
                            }
                        })

                    }
                }

            },
            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) {
                this.isProcessing = true; // 显示遮罩层

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

                    let errors = [];

                    if(!this.uploadFlag){
                        errors.push("图片未上传完成，请等待上传完后在提交")
                    }

                    if (this.fileList1 && this.fileList1.length > 0) {
                        // 将 fileList1 中的每个文件对象的属性名调整为新的属性名
                        this.inputForm.fileList1 = this.fileList1.map(file => {
                            return {
                                attachmentName: file.name,
                                fileSize: file.size,
                                url: file.url,
                                type: file.type,      // 如果不需要，可以不写
                                attachmentFlag: 'before',      // 如果不需要，可以不写
                            };
                        });
                    }

                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 2000
                            });
                        });
                        this.isProcessing = false;
                        reject('Form validation failed');
                    } else {
                        // 所有验证通过，执行保存操作
                        this.$refs.inputForm.validate().then(() => {
                            uni.showLoading();

                            this.inputForm.status = '2'
                            overService.save(this.inputForm).then(data => {

                                uni.showToast({
                                    title: "提交成功",
                                    icon: "success",
                                    duration: 1000  // 提示持续时间为1秒（1000毫秒）
                                });

                                // 延迟1秒后再跳转到上一页
                                setTimeout(() => {
                                    this.isProcessing = false; // 显示遮罩层
                                    this.inputForm.assignee = this.inputForm.clearUserId
                                    callback(data.businessTable, data.businessId,this.inputForm);
                                    resolve('Form saved successfully');
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }, 1000);
                            }).catch(error => {
                                reject('Save operation failed');
                            });
                        }).catch(() => {
                            reject('Form validation failed');
                        });
                    }
                });
            },
            savePhoto() {

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

                    let errors = [];

                    if(!this.uploadFlag){
                        errors.push("图片未上传完成，请等待上传完后在提交")
                    }


                    if (this.fileList2 && this.fileList2.length > 0) {
                        // 将 fileList1 中的每个文件对象的属性名调整为新的属性名
                        this.inputForm.fileList2 = this.fileList2.map(file => {
                            return {
                                attachmentName: file.name,
                                fileSize: file.size,
                                url: file.url,
                                type: file.type,      // 如果不需要，可以不写
                                attachmentFlag: 'between',      // 如果不需要，可以不写
                            };
                        });
                    }

                    if (this.fileList3 && this.fileList3.length > 0) {
                        // 将 fileList1 中的每个文件对象的属性名调整为新的属性名
                        this.inputForm.fileList3 = this.fileList3.map(file => {
                            return {
                                attachmentName: file.name,
                                fileSize: file.size,
                                url: file.url,
                                type: file.type,      // 如果不需要，可以不写
                                attachmentFlag: 'after',      // 如果不需要，可以不写
                            };
                        });
                    }

                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 2000
                            });
                        });
                        this.isProcessing = false;
                        reject('Form validation failed');
                    } else {
                        //数据保存
                        this.$refs.inputForm.validate().then(() => {
                            uni.showLoading();

                            overService.savePhoto(this.inputForm).then(data => {
                                EventBus.$emit('refreshPhoto');
                                uni.showToast({
                                    title: "提交成功",
                                    icon: "success",
                                    duration: 1000  // 提示持续时间为1秒（1000毫秒）
                                });

                                // 延迟1秒后再跳转到上一页
                                setTimeout(() => {
                                    this.isProcessing = false; // 显示遮罩层
                                    resolve('Form saved successfully');
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }, 1000);
                            }).catch(error => {
                                reject('Save operation failed');
                            });
                        }).catch(() => {
                            reject('Form validation failed');
                        });
                    }
                });
            },

            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                try {
                    this.uploadFlag = false
                    // 当设置 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, fileListLen)
                        let item = this[`fileList${event.name}`][fileListLen]
                        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                            status: 'success',
                            message: '',
                            url: result
                        }))
                        fileListLen++
                    }
                    this.uploadFlag = true
                } catch (error) {
                    console.error('上传失败:', error);
                } finally {
                    this.uploadFlag = true
                }
            },
            uploadFilePromise(url, index) {
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: 'http://dttz.xgccpm.cn/api/app/file/webUpload/fileUpload', // 仅为示例，非真实的接口地址
                        filePath: url,
                        name: 'file',
                        formData: {
                            user: this.$store.state.user.userInfo
                        },
                        header: {
                            'token': $auth.getUserToken(),
                        },
                        success: (res) => {

                            // this.fileList1[index].url = url

                            setTimeout(() => {
                                const dataObj = JSON.parse(res.data);
                                const url = dataObj.url;
                                resolve(url);
                            }, 1000);
                        },
                        fail: (err) => {
                            console.error('Upload failed:', err);
                        }
                    });
                })
            },
            getOfficeOnHamlet(value){
                // 根据组织ID 获取 该村的 村支书
                overService.getUserInfoByOffId(value)
                    .then(data => {
                        this.inputForm.clearUserId = data.id
                        this.inputForm.clearUserName = data.name
                        this.inputForm.clearUserMobile = data.mobile
                    })
                    .catch(e => {
                        throw e;
                    });
            }
        }
    }
</script>

<style>
    .form-section {
        padding: 10px 15px;
        margin-bottom: 10px;
        background-color: #ffffff;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .u-page__upload-item {
        margin-top: 10px;
    }

    .button-container {
        margin-top: 20px;
        text-align: center;
    }

    .cu-form-group .title {
        min-width: 100px;
    }
    /* 遮罩层样式 */
    .mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.05); /* 半透明遮罩 */
        z-index: 9999; /* 确保遮罩层在最顶层 */
    }
</style>
