<template>
    <popup v-model:show="showValue" class="execute-popup" closeable>
        <div class="popup-content">
            <div class="time-wrap">
                <div class="name pb-10">
                    请选择实际执行时间
                </div>
                <div class="time-input">
                    <el-date-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="executeTime"
                        :disabled-date="disabledDate" size="large" style="width: 100%" type="date" placeholder="请选择日期"
                        :editable="false" />
                </div>
            </div>
            <div class="upload-wrap" :class="{ 'upload-cont': fileList.length }">
                <div class="name">农事凭证</div>
                <div class="sub-name">请上传农事执行现场照片及所用药肥凭证照片</div>
                
                <uploader class="uploader" v-model="fileList" multiple :max-count="5" :after-read="afterRead" @delete="handleDelete"
                    @click="handleClick('rg')">
                    <img class="img" v-show="!fileList.length" src="@/assets/img/home/example-4.png" alt="" />
                    <img class="plus" src="@/assets/img/home/plus.png" alt="" />
                </uploader>
                <div class="service-input">
                    <el-input v-model="serviceInput" placeholder="请输入农资机构名称" />
                </div>
            </div>
            <div class="button-wrap">
                <div @click="closeTask" class="button primary">确认上传</div>
            </div>
        </div>
    </popup>

    <popup v-model:show="showRemindValue" class="execute-popup" closeable>
        <div class="popup-content">
            <div class="name">
                <span class="required">*</span>请选择下次提醒时间
            </div>
            <div class="time-number-input">
                <el-input-number v-model="remindTime" :min="1" :max="30" :step="1" size="large" style="width: 100%" />
                <span class="time-unit">天后</span>
            </div>
            <div class="button-wrap">
                <div @click="handleRemind" class="button primary">确认</div>
            </div>
        </div>
    </popup>

</template>

<script setup>
import { Popup, Uploader } from "vant";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getFileExt } from "@/utils/util";
import UploadFile from "@/utils/upliadFile";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

const store = useStore();
const miniUserId = store.state.home.miniUserId;
const router = useRouter();

const props = defineProps({
    executionData: {
        type: Object,
        default: () => ({}),
    },
});

const showValue = ref(false);
const fileList = ref([]);
const fileArr = ref([]);
const sourceEvidenceList = ref([]);
const sourceAuditStatusList = ref([]);
const executeTime = ref("");
const serviceInput = ref("");
const uploadFileObj = new UploadFile();

const emit = defineEmits(['executeSuccess']);

const afterRead = (file) => {
    // 处理多张照片的情况：file 可能是数组
    const files = Array.isArray(file) ? file : [file];

    files.forEach((item) => {
        // 将文件上传至服务器
        let fileVal = item.file;
        if (!fileVal) return; // 如果没有 file 属性，跳过

        item.status = "uploading";
        item.message = "上传中...";
        let ext = getFileExt(fileVal.name);
        let key = `birdseye-look-mini/${miniUserId}/${new Date().getTime()}.${ext}`;
        uploadFileObj.put(key, fileVal).then((resFilename) => {
            item.status = "done";
            item.message = "";
            fileArr.value.push(resFilename);
        }).catch(() => {
            item.status = 'failed';
            item.message = '上传失败';
            ElMessage.error('图片上传失败，请稍后再试！')
        });
    });
};

function handleDelete(file) {
    // fileList.value = fileList.value.filter(item => item.filePath !== file.filePath);
    // fileArr.value = fileArr.value.filter(item => item !== file.filePath);
    
    console.log("fileList", fileList.value);
    if (isEdit.value) {
        fileArr.value = fileList.value.map(item => item.filePath);
    }
}

function closeTask() {
    // stepIndex.value = 2
    if (!fileArr.value.length) return ElMessage.warning('请上传农事凭证')
    if (!executeTime.value) return ElMessage.warning('请选择实际执行时间')
    if (!serviceInput.value) return ElMessage.warning('请输入农资机构名称')

    const params = {
        recordId: recordId.value,
        executorOrganizationName: serviceInput.value,
        executeDate: executeTime.value,
        executeEvidence: fileArr.value,
    }
    console.log("params", params);
    VE_API.report.addExecuteImgAndComplete(params).then((res) => {
        if (res.code === 0) {
            ElMessage.success('上传成功')
            showValue.value = false;
            setTimeout(() => {
                emit('executeSuccess');
            }, 800)
        } else {
            ElMessage.error(res.msg)
        }
    }).catch((err) => {
        ElMessage.error('操作失败')
    })
}

const handleClick = () => {
    // 预留点击上传区域的埋点或其它逻辑
};

const disabledDate = (time) => {
    // 示例：不允许选择未来日期
    return time.getTime() > Date.now();
};

const showRemindValue = ref(false);
const remindTime = ref(1);

function showRemindPopup() {
    showRemindValue.value = true;
}

function handleRemind() {
    if (!remindTime.value) return ElMessage.warning('请选择下次提醒时间')
    showRemindValue.value = false;
}

const recordId = ref(null);
const isEdit = ref(false);
function openPopup(id, extraData = {}) {
    showValue.value = true;
    recordId.value = id;
    fileArr.value = extraData.evidenceList.map(item => item.filePath);
    fileList.value = extraData.evidenceList
    isEdit.value = extraData.isEdit
    executeTime.value = extraData.executeDate
    serviceInput.value = extraData.executorOrganizationName
    // sourceEvidenceList.value = Array.isArray(extraData.evidenceList) ? extraData.evidenceList : [];

    // sourceAuditStatusList.value = Array.isArray(extraData.auditStatusList) ? extraData.auditStatusList : [];
}

defineExpose({
    openPopup,
    showRemindPopup,
});
</script>

<style lang="scss" scoped>
.execute-popup {
    width: 90%;
    border-radius: 8px;

    .popup-content {
        padding: 24px 16px 20px 16px;
        background: linear-gradient(360deg, #FFFFFF 74.2%, #D1EBFF 100%);
        border-radius: 8px;
    }
}

.pb-10 {
    padding-bottom: 12px;
}

.name {
    color: #000000;
    font-size: 16px;
    font-weight: 500;
    // padding-bottom: 12px;

    .required {
        color: #ff4d4f;
        margin-right: 2px;
    }
}

.sub-name {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.4);
    padding-bottom: 12px;
}

.tips-text {
    color: #FA7406;
    padding: 5px 10px;
    border: 1px solid #FA7406;
    border-radius: 5px;
    margin-bottom: 10px;
    background: #fff;
}

.service-input {
    padding-top: 12px;
}

.upload-wrap {

    &.upload-cont {
        ::v-deep {
            .van-uploader__wrapper {
                // flex-wrap: nowrap;
            }
        }
    }

    .img {
        width: 80px;
        height: 80px;
        margin-right: 12px;
    }

    .plus {
        margin-right: 12px;
        width: 80px;
        height: 80px;
    }
}

.upload-wrap {
    ::v-deep {
        .van-image__img {
            border-radius: 8px;
        }

        .avatar-uploader .el-upload {
            width: 100%;
            border: 1px dashed #dddddd;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        // .van-uploader__input-wrapper
        .van-uploader,
        .van-uploader__wrapper {
            width: 100%;
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100%;
            height: 128px;
            text-align: center;
            background: #f6f6f6;
        }
    }
}

.button-wrap {
    display: flex;
    justify-content: center;
    margin: 24px 4px 0 4px;

    .button {
        border-radius: 20px;
        color: #fff;
        padding: 7px 0;
        text-align: center;
        font-size: 16px;

        &.primary {
            flex: 1;
            background: #2199f8;
            color: #fff;
        }
    }
}

.time-wrap {
    margin-bottom: 12px;

    .time-input {
        width: 100%;
    }
}

.time-number-input {
    display: flex;
    align-items: center;
    width: 100%;

    .time-unit {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.4);
        flex: none;
        margin-left: 8px;
    }
}
</style>