<template>
    <div v-loading="isLoading" class="hc-task-form white relative">
        <!-- 基础表单 -->
        <hc-card-item>
            <hc-info-table>
                <tr>
                    <hc-info-table-td center is-title>合同材料：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.contractMaterialName }}</hc-info-table-td>
                    <hc-info-table-td center is-title>材料到场编号：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.materialArriveNumber }}</hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>计量期：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.periodName }}</hc-info-table-td>
                    <hc-info-table-td center is-title>业务日期：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.businessDate }}</hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>单价：</hc-info-table-td>
                    <hc-info-table-td v-loading="priceLoading" width="120px">
                        <el-input v-model="baseForm.price" :disabled="!isEdits || tableInfo.status === 2" @blur="priceInputBlur" />
                    </hc-info-table-td>
                    <hc-info-table-td center is-title>计量数量：</hc-info-table-td>
                    <hc-info-table-td v-loading="meterLoading" width="120px">
                        <el-input v-model="baseForm.meterAmount" :disabled="!isEdits || tableInfo.status === 2" @blur="meterAmountInputBlur" />
                    </hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>计量金额：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.meterMoney }}</hc-info-table-td>
                    <hc-info-table-td center is-title>备料堆放地点：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.storagePlace }}</hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>存储情况：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.storageStatus }}</hc-info-table-td>
                    <hc-info-table-td center is-title>材料来源：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.materialSource }}</hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>材料是否符合要求：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.materialConformName }}</hc-info-table-td>
                    <hc-info-table-td center is-title>存储方法是否符合要求：</hc-info-table-td>
                    <hc-info-table-td width="120px">{{ baseForm?.storageConformName }}</hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>合格证号：</hc-info-table-td>
                    <hc-info-table-td width="auto" colspan="3">{{ baseForm?.certificate }}</hc-info-table-td>
                </tr>
                <tr>
                    <hc-info-table-td center is-title>备注：</hc-info-table-td>
                    <hc-info-table-td width="auto" colspan="3">{{ baseForm?.remark }}</hc-info-table-td>
                </tr>
            </hc-info-table>
        </hc-card-item>
        <!-- 附件列表 -->
        <hc-card-item class="mt-3" title="附件列表">
            <template #extra>
                <span class="text-[13px] text-orange font-400">可上传 图片(png、jpg、jpeg)、Excel(xls、xlsx)、PDF、Word(doc、docx)文件</span>
            </template>
            <el-form :model="baseForm" label-position="left" label-width="auto">
                <el-form-item label="上传附件">
                    <hc-form-upload type="list" :src="baseForm.fileList" :h-props="uploadFormProps" is-del @upload="attachmentUpload" @change="attachmentUploadChange" @del="attachmentUploadDel" />
                </el-form-item>
            </el-form>
        </hc-card-item>
        <!-- 文件上传组件 -->
        <hc-upload-file ref="uploadFileRef" :options="uploadFileOptions" @success="uploadFileSuccess" />
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { getArrValue, getObjVal, getObjValue, isNullES } from 'js-fast-way'
import { delMessage, isNumberReg } from '~uti/tools'
import { getHeader } from 'hc-vue3-ui'
import mainApi from '~api/tasks/hc-data'

const props = defineProps({
    isEdit: {
        type: Boolean,
        default: true,
    },
    info: {
        type: Object,
        default: () => ({}),
    },
    table: {
        type: Object,
        default: () => ({}),
    },
})

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')

//监听可否编辑
const isEdits = ref(props.isEdit)
watch(() => props.isEdit, (val) => {
    isEdits.value = val
}, { immediate: true, deep: true })

//监听数据
watch(() => [
    props.table,
    props.info,
], ([table, row]) => {
    setTaskInfo(table, row)
}, { deep: true })

//渲染完成
onMounted(() => {
    setTaskInfo(props.table, props.info)
})

//设置任务信息
const taskInfo = ref({})
const tableInfo = ref({})
const setTaskInfo = (table, row) => {
    tableInfo.value = table
    taskInfo.value = row
    if (getObjVal(table) && getObjVal(row)) {
        getDataDetail()
    }
}

//基础表单
const baseForm = ref({ fileList: [] })

//获取任务数据信息详情
const isLoading = ref(false)
const getDataDetail = async () => {
    const id = taskInfo.value.id
    const dataId = tableInfo.value.id
    const { data } = await mainApi.getDataDetail({ id, dataId })
    //转换数据
    const { attachmentFormTask, basicsInfo } = getObjValue(data)
    baseForm.value = getObjValue(basicsInfo) //表单信息
    baseForm.value.fileList = getArrValue(attachmentFormTask) //附件列表
}

//单价输入框失去焦点
const priceLoading = ref(false)
const priceInputBlur = async () => {
    let { id, price } = baseForm.value
    const isMeter = isNumberReg(price)
    let priceValue = price
    if (isNullES(price) || !isMeter) {
        priceValue = 0
    }
    await nextTick(() => {
        baseForm.value.price = priceValue
    })
    //发起请求
    priceLoading.value = true
    const { error, code, msg } = await mainApi.taskMaterialUpdate({
        projectId: projectId.value,
        contractId: contractId.value,
        taskId: taskInfo.value.id,
        price: priceValue,
        id,
    })
    priceLoading.value = false
    if (!error && code === 200) {
        window.$message.success('修改成功')
    } else {
        window.$message.error(msg ?? '修改失败')
    }
}

//单价输入框失去焦点
const meterLoading = ref(false)
const meterAmountInputBlur = async () => {
    let { id, meterAmount } = baseForm.value
    const isMeter = isNumberReg(meterAmount)
    let meterAmountValue = meterAmount
    if (isNullES(meterAmount) || !isMeter) {
        meterAmountValue = 0
    }
    await nextTick(() => {
        baseForm.value.meterAmount = meterAmountValue
    })
    //发起请求
    meterLoading.value = true
    const { error, code, msg } = await mainApi.taskMaterialUpdate({
        projectId: projectId.value,
        contractId: contractId.value,
        meterAmount: meterAmountValue,
        taskId: taskInfo.value.id,
        id,
    })
    meterLoading.value = false
    if (!error && code === 200) {
        window.$message.success('修改成功')
    } else {
        window.$message.error(msg ?? '修改失败')
    }
}

//文件上传
const uploadFileRef = ref(null)
const uploadFileOptions = ref({
    headers: getHeader(),
    multiple: false,
})
const uploadFormProps = {
    url: 'filePdfUrl',
    name: 'fileName',
}

const attachmentUpload = () => {
    if (isEdits.value || tableInfo.value.status !== 2) {
        uploadFileRef.value?.selectFile()
    } else {
        window.$message.error('当前状态不可上传')
    }
}
const attachmentUploadChange = (a, b, fileList) => {
    baseForm.value.fileList = getArrValue(fileList)
}

// 文件上传成功的回调
const uploadFileSuccess = async ({ resData }) => {
    const { pdfUrl } = resData
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        uploadFileRef.value?.setModalShow(false)
        return
    }
    baseForm.value.fileList.push({
        contractId: contractId.value,
        fileName: resData.originalName ?? '',
        filePdfUrl: resData.pdfUrl ?? '',
        fileUrl: resData.link ?? '',
        taskId: taskInfo.value.id,
    })
    uploadFileRef.value?.setModalShow(false)
    //发起请求
    const dataId = tableInfo.value.id
    const { error, code, msg } = await mainApi.taskUploadFile({
        projectId: projectId.value,
        contractId: contractId.value,
        fileList: baseForm.value.fileList,
        taskId: taskInfo.value.id,
        dataId,
    })
    if (!error && code === 200) {
        window.$message.success('上传成功')
    } else {
        window.$message.error(msg ?? '上传失败')
    }
}

//删除文件
const attachmentUploadDel = ({ file }, resolve) => {
    if (!isEdits.value) {
        window.$message.error('当前状态不可删除')
        return
    }
    delMessage(async () => {
        const { error, code, msg } = await mainApi.removeFile({
            id: file.id,
            taskId: taskInfo.value.id,
        })
        if (!error && code === 200) {
            resolve(true)
        } else {
            window.$message.error(msg ?? '删除失败')
            resolve(false)
        }
    })
}
</script>

<style lang="scss">
.hc-task-form.white .hc-card-item-box {
    background: white !important;
}
</style>
