<template>
    <hc-sys :isNavBar="false">
        <uni-notice-bar text="请上传MP4、MOV格式的视频文件，文件大小不超过500M，只能上传1个视频文件" v-if="formData.type === 1"/>
        <uni-notice-bar text="请上传JPG、JPEG、PNG格式的图片文件，大小不超过30M，最多10张图片文件" v-if="formData.type === 2"/>
        <view class="relative bg-white mt-1 hc-p">
            <!-- 图片文件上传 -->
            <view class="hc-flex flex-wrap pb-3 mb-5" un-border-b="1 solid gray-2" v-if="formData.type === 2">
                <template v-for="(item, index) in fileList" :key="index">
                    <view class="hc-flex h-120 w-120 b-rounded mr-2 mt-2" @click="previewImg(index)">
                        <hc-img :src="item" width="60" height="60" class="b-rounded"/>
                        <view class="hc-tr bg-red-5 text-white text-center w-38 h-38 b-rounded-lb-1 b-rounded-tr-1" @click.stop="delFileClick(index)">
                            <text class="relative cuIcon-close top--2 text-24"/>
                        </view>
                    </view>
                </template>
                <template v-if="fileList.length < 10">
                    <view class="hc-flex-center h-120 w-120 b-rounded mt-2" un-border="2 dashed gray-2" @click="addFileClick">
                        <text class="i-iconoir-plus text-70 text-gray-4"/>
                    </view>
                </template>
            </view>
            <!-- 视频文件上传 -->
            <view class="hc-flex pb-3 mb-5" un-border-b="1 solid gray-2" v-if="formData.type === 1">
                <template v-for="(item, index) in fileList" :key="index">
                    <view class="hc-flex h-120 w-full b-rounded">
                        <video class="w-full h-full b-rounded" :src="item"/>
                        <view class="hc-tr bg-red-5 text-white text-center w-38 h-38 b-rounded-lb-1 b-rounded-tr-1 z-24" @click.stop="delFileClick(index)">
                            <text class="relative cuIcon-close top--2 text-24"/>
                        </view>
                    </view>
                </template>
                <template v-if="fileList.length < 1">
                    <view class="hc-flex-center h-120 w-full b-rounded" un-border="2 dashed gray-2" @click="addVideoFileClick">
                        <text class="i-iconoir-plus text-70 text-gray-4"/>
                    </view>
                </template>
            </view>
            <!-- 表单 -->
            <uni-forms ref="formRef" :rules="formRules" :modelValue="formData" :label-width="82">
                <uni-forms-item label="题名" required name="title">
                    <uni-easyinput v-model="formData.title" placeholder="请输入题名" />
                </uni-forms-item>
                <uni-forms-item label="文字说明" required name="textContent">
                    <uni-easyinput type="textarea" v-model="formData.textContent" placeholder="请输入文字说明" />
                </uni-forms-item>
                <uni-forms-item label="拍摄时间" required name="shootingTimeStr">
                    <uni-datetime-picker type="date" v-model="formData.shootingTimeStr" :end="dateEnd"/>
                </uni-forms-item>
                <uni-forms-item label="上传日期" required name="uploadTime">
                    <uni-datetime-picker type="date" v-model="formData.uploadTime" :end="dateEnd"/>
                </uni-forms-item>
                <uni-forms-item label="拍摄者" required name="shootingUser">
                    <uni-easyinput v-model="formData.shootingUser" placeholder="请输入拍摄者" />
                </uni-forms-item>
                <template v-if="formData.type === 2">
                    <uni-forms-item label="照片号">
                        <uni-easyinput v-model="formData.photoCode" placeholder="请输入照片号" />
                    </uni-forms-item>
                    <uni-forms-item label="底片号">
                        <uni-easyinput v-model="formData.filmCode" placeholder="请输入底片号" />
                    </uni-forms-item>
                    <uni-forms-item label="参见号">
                        <uni-easyinput v-model="formData.seeAlsoCode" placeholder="请输入参见号" />
                    </uni-forms-item>
                </template>
            </uni-forms>
        </view>
        <!-- 底部操作栏 -->
        <HcTabbarBlock :height="70"/>
        <hc-tabbars class="flex items-center">
            <template v-if="!dataId">
                <view class="flex-1 mr-2">
                    <button hover-class="none" class="cu-btn block bg-orange text-white" @click="continueAdd">继续新增</button>
                </view>
                <view class="flex-1 ml-2">
                    <button hover-class="none" class="cu-btn block bg-purple-8 text-white" @click="saveAdd">提交保存</button>
                </view>
            </template>
            <template v-else>
                <button hover-class="none" class="cu-btn flex-1 bg-purple-8 text-white" @click="saveClick">提交保存</button>
            </template>
        </hc-tabbars>
    </hc-sys>
</template>

<script setup>
import {ref} from "vue";
import {onLoad, onReady} from '@dcloudio/uni-app'
import mainApi from '~api/image/index';
import {uploadApi} from '~api/upload';
import {getObjValue, isString} from "js-fast-way";
import {errorToast, formValidate, successToast} from "@/utils/tools";
import {chooseImage, chooseVideo} from "@/utils/utils";
import {useAppStore} from "@/store";
import dayjs from "dayjs";

//初始变量
const store = useAppStore()
const userInfo = ref(store.userInfo);
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);

//基础变量
const dataId = ref('');
const fileList = ref([])
const pdfList = ref([])

const dateEnd = ref(dayjs().format("YYYY-MM-DD"));

//页面启动
onLoad((options) => {
    const {id, node} = getObjValue(options)
    dataId.value = id ?? '';
    if (id) {
        uni.setNavigationBarTitle({title: '编辑声像文件'})
        getInfoApi()
    } else {
        const nodes = node ? JSON.parse(decodeURIComponent(node)) : {};
        const {real_name} = userInfo.value
        formData.value = {
            projectId: projectId.value,
            contractId: contractId.value,
            classifyId: nodes.id,
            type: nodes.fileType,
            wbsId: nodes.treeId,
            uploadTime: dateEnd.value,
            shootingTimeStr: dateEnd.value,
            shootingUser: real_name
        }
        console.log(nodes.type)
        if (nodes.type === 1) {
            getFileTitleNamedata(nodes.treeId)
        }
        uni.setNavigationBarTitle({title: '新增声像文件'})
    }
})

onReady(() => {
    // 设置自定义表单校验规则，必须在节点渲染完毕后执行
    formRef.value?.setRules(formRules)
})

//获取题名
const getFileTitleNamedata = async (wbsId) => {
    const { data } = await mainApi.getFileTitleName({
        pKeyId: wbsId
    })
    formData.value.title = isString(data) ? data: ''
}

//获取详情
const getInfoApi = async () => {
    formData.value = {}
    if (!dataId.value) {
        errorToast('参数异常，请退出重试')
        return false;
    }
    uni.showLoading({title: '获取数据中...', mask: true});
    const { data } = await mainApi.queryById({
        id: dataId.value
    })
    const res = getObjValue(data)
    formData.value = res
    const {imageUrl, pdfUrl} = res
    fileList.value = imageUrl.toString().split(',')
    pdfList.value = pdfUrl.toString().split(',')
    uni.hideLoading();
}

//添加文件
const addFileClick = async () => {
    const tempFiles = await chooseImage(10 - fileList.value.length)
    if (tempFiles.length > 0) {
        uni.showLoading({title: '上传文件中...', mask: true});
    }
    for (let i = 0; i < tempFiles.length; i++) {
        await uploadFile(tempFiles[i].path);
    }
    uni.hideLoading();
}

//选择视频文件
const addVideoFileClick = async () => {
    const {tempFilePath} = await chooseVideo()
    if (tempFilePath) {
        uni.showLoading({title: '上传文件中...', mask: true});
        await uploadFile(tempFilePath);
        uni.hideLoading();
    }
}

//上传文件
const uploadFile = async (file) => {
    const {error, msg, data} = await uploadApi(file)
    if (!error) {
        const { link, pdfUrl } = getObjValue(data)
        fileList.value.push(link)
        if (pdfUrl) {
            pdfList.value.push(pdfUrl)
        }
    } else {
        errorToast(msg)
    }
}

//删除文件
const delFileClick = (index) => {
    fileList.value.splice(index, 1)
    if (pdfList.value.length > 0) {
        pdfList.value.splice(index, 1)
    }
}

//预览图片
const previewImg = (index) => {
    uni.previewImage({
        current: index,
        urls: fileList.value,
    });
}

//表单验证
const formRef = ref(null)
const formData = ref({})
const formRules = {
    title: {
        rules: [{
            required: true,
            errorMessage: '请输入题名'
        }]
    },
    textContent: {
        rules: [{
            required: true,
            errorMessage: '请输入文字说明'
        }]
    },
    shootingTimeStr: {
        rules: [{
            required: true,
            errorMessage: '请选择拍摄时间'
        }]
    },
    uploadTime: {
        rules: [{
            required: true,
            errorMessage: '请选择上传日期'
        }]
    },
    shootingUser: {
        rules: [{
            required: true,
            errorMessage: '请输入拍摄者'
        }]
    },
}

const isFormValidate = async () => {
    if (fileList.value.length <= 0) {
        errorToast('请先上传文件')
        return false
    }
    const isForm = await formValidate(formRef.value)
    if (!isForm) {
        errorToast('请先完善表单')
        return false
    }
    return true
}

//提交保存
const saveClick = async () => {
    const isForm = await isFormValidate()
    if (!isForm) return false;
    //更新数据
    if (dataId.value) {
        await updateImageData()
    } else {
        await addImageData()
    }
}

//更新数据
const updateImageData = async () => {
    uni.showLoading({title: '保存数据中...', mask: true});
    const {error, code, msg} = await mainApi.updateImageclassifyFile({
        ...formData.value,
        imageUrl: fileList.value.join(','),
        pdfUrl: pdfList.value.join(','),
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('保存成功')
    } else {
        errorToast('保存失败: ' + msg)
    }
}

//新增数据
const addImageData = async () => {
    uni.showLoading({title: '新增数据中...', mask: true});
    const {error, code, msg} = await mainApi.addImageclassifyFile({
        ...formData.value,
        imageUrl: fileList.value.join(','),
        pdfUrl: pdfList.value.join(','),
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('新增成功')
        return true
    } else {
        errorToast('新增失败: ' + msg)
        return false
    }
}

//继续新增
const continueAdd = async () => {
    const isForm = await isFormValidate()
    if (!isForm) return false;
    const res = await addImageData()
    if(!res) return false;
    //清空表单
    const {real_name} = userInfo.value
    const { wbsId } = formData.value;
    formData.value.uploadTime = dateEnd.value
    formData.value.shootingTimeStr = dateEnd.value
    formData.value.shootingUser = real_name
    formData.value.title = ''
    formData.value.textContent = ''
    formData.value.photoCode = ''
    formData.value.filmCode = ''
    formData.value.seeAlsoCode = ''
    fileList.value = []
    pdfList.value = []
    getFileTitleNamedata(wbsId).then()
}

//新增保存
const saveAdd = async () => {
    const isForm = await isFormValidate()
    if (!isForm) return false;
    const res = await addImageData()
    if(!res) return false;
    //返回上一页
    setTimeout(() => {
        uni.navigateBack()
    }, 1500)
}
</script>
