<template>
    <div class="hc-uni-app-table-form" :class="[editType]">
        <hc-table-form ref="tableFormRef" :form="tableFormInfo" :html="excelHtml" :scroll="false" :pkey="appItem.excelId" @render="tableFormRender" />
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import queryApi from '~api/ledger/query'
import { getArrValue, getObjVal, getObjValue, isString } from 'js-fast-way'

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

//初始变量
const useAppState = useAppStore()

//基础变量
const appItem = ref(props.option)
const tableFormRef = ref(null)
const editType = ref('form')

//深度监听
watch(() => [
    props.option,
], ([option]) => {
    appItem.value = getObjValue(option)
    getDataApi()
}, { deep: true })

//渲染完成
onMounted(() => {
    //设置主题
    useAppState.setTheme('light')
    useAppState.setThemeVal('light')
    if (getObjVal(appItem.value)) {
        getDataApi()
    }
    editTypeClick('form')
    //接受app传递过来的消息
    window.addEventListener('message', (event) => {
        if (event.data.source === 'app') {
            setMessage(event.data)
        }
    })
})

//设置消息
const setMessage = ({ data, type }) => {
    if (type === 'editTypeClick') {
        editTypeClick(data)
    } else if (type === 'formSave') {
        toSaveClick()
    } else if (type === 'pageTap') {
        console.log('pageTap', data)
        getBussDataInfo(Number(data))
    } else if (type === 'addForm') {
        addTableFormClick()
    } else if (type === 'delForm') {
        delTableFormClick()
    } else if (type === 'linkIds') {
        let ids = data ? JSON.parse(data) : []
        linkTableFormClick(ids)
    } else if (type === 'copyFormData') {
        copyTableFormClick()
    } else if (type === 'getPdfUrl') {
        getBussPdfInfo()
    }
}

const getDataApi = async () => {
    const { excelId } = appItem.value
    if (excelId) {
        await getTableFormInfo()
        await getExcelHtml()
    }
}

//获取表单初始数据
const getFormDataInit = (data = {}) => {
    const { projectId, contractId, excelId, date } = appItem.value
    return {
        linkTabIds: [],
        ...data,
        projectId: projectId,
        contractId: contractId,
        recordTime: date,
        pkeyId: excelId,
        isTheLog: '1',
        theLogId: '',
        classify: 1,
    }
}

//获取已填写的数据
const formLogDataList = ref([])
const getTableFormInfo = async () => {
    const { contractId, excelId, pkeyId, date } = appItem.value
    const { data } = await queryApi.getTheLogBusinessData({
        contractId: contractId,
        pkeyId: excelId,
        nodePrimaryKeyId: pkeyId,
        recordTime: date,
        theLogId: '',
    }, false)
    let res = getArrValue(data), formArrData = []
    if (res.length > 0) {
        for (let i = 0; i < res.length; i++) {
            formArrData.push(getFormDataInit(res[i]))
        }
    } else {
        formArrData.push(getFormDataInit())
    }
    formLogDataList.value = formArrData
    setFormLength()
    getBussDataInfo()
}

//获取表单初始数据
const formLogIndex = ref(0)
const tableFormInfo = ref({})
const getBussDataInfo = (index = 0) => {
    const formLog = formLogDataList.value
    const info = getObjValue(formLog[index])
    formLogIndex.value = index
    if (getObjVal(info)) {
        tableFormInfo.value = info
    } else {
        tableFormInfo.value = {}
    }
    postMessage({
        type: 'formIndex',
        data: {
            id: info?.id ?? '',
            page: Number(index) + 1,
        },
    })
}

//获取模板标签数据
const excelHtml = ref('')
const isTableForm = ref(false)
const getExcelHtml = async () => {
    const { contractId, excelId } = appItem.value
    if (excelId) {
        //获取数据
        const { error, code, data } = await queryApi.getExcelHtml({
            contractId: contractId,
            pkeyId: excelId,
        }, false)
        //处理数据
        const resData = isString(data) ? data || '' : ''
        if (!error && code === 200 && resData) {
            excelHtml.value = resData
            isTableForm.value = true
        } else {
            excelHtml.value = ''
            isTableForm.value = false
            postMsg('暂无表单', 'error')
        }
    } else {
        isTableForm.value = false
        postMsg('参数异常', 'error')
    }
}

//渲染完成
const tableFormRender = (form) => {
    tableFormInfo.value = form
    postMessage({ type: 'formRender' })
}

//新增表格
const addTableFormClick = () => {
    const defaultData = getFormDataInit()
    formLogDataList.value.push(defaultData)
    const index = formLogDataList.value.length - 1
    setFormLength()
    getBussDataInfo(index)
    postMsg('新增成功', 'success')
}

//删除当前页
const delTableFormClick = () => {
    const index = formLogIndex.value
    formLogDataList.value.splice(index, 1)
    const logIndex = index <= 0 ? 0 : index - 1
    formLogIndex.value = logIndex
    setFormLength()
    getBussDataInfo(logIndex)
    postMsg('删除成功', 'success')
}

//复制当前表格及内容
const copyTableFormClick = () => {
    const index = formLogIndex.value
    const formLog = formLogDataList.value
    const info = getObjValue(formLog[index])
    const defaultData = getFormDataInit(info)
    formLogDataList.value.push({
        ...defaultData,
        id: '',
    })
    setFormLength()
    getBussDataInfo(formLogDataList.value.length - 1)
    postMsg('复制成功', 'success')
}

//更新表单数量
const setFormLength = () => {
    postMessage({
        type: 'formLength',
        data: formLogDataList.value.length,
    })
}

//更新关联工序
const linkTableFormClick = (data) => {
    const index = formLogIndex.value
    const formLog = formLogDataList.value
    const info = getObjValue(formLog[index])
    info.linkTabIds = data
    formLogDataList.value[index] = info
    tableFormInfo.value.linkTabIds = data
}

//预览PDF
const getBussPdfInfo = async () => {
    const { contractId, excelId, pkeyId, date } = appItem.value
    const { data } = await queryApi.getBussPdfInfo({
        contractId: contractId,
        pkeyId: excelId,
        nodePrimaryKeyId: pkeyId,
        recordTime: date,
        theLogId: '',
    }, false)
    //处理数据
    const resData = isString(data) ? data ?? '' : ''
    postMessage({
        type: 'formPdfUrl',
        data: resData,
    })
}

//切换显示模式
const tableWidth = ref(0)
const editTypeClick = (type) => {
    let metaEle = document.getElementsByName('viewport')[0]
    if (type === 'form') {
        metaEle.setAttribute('content', 'width=device-width,user-scalable=no,initial-scale=1.0')
        tableWidth.value = 0
    } else if (type === 'table') {
        metaEle.setAttribute('content', 'width=1080, initial-scale=0.5,user-scalable=yes')
        tableWidth.value = document.body.offsetWidth
    }
    editType.value = type
}

//保存表单
const toSaveClick = async () => {
    const formLog = formLogDataList.value
    let isLink = await isLinkTabIds(formLog)
    if (!isLink) {
        postMessage({
            type: 'saveRes',
            data: false,
        })
        return
    }
    //发起请求
    const { error, code } = await queryApi.saveExcelBussData({
        dataInfo: { orderList: formLog },
    }, false)
    if (!error && code === 200) {
        postMessage({
            type: 'saveRes',
            data: true,
        })
        postMsg('保存成功', 'success')
        getBussPdfInfo().then()
    } else {
        postMessage({
            type: 'saveRes',
            data: false,
        })
        postMsg('保存失败', 'error')
    }
}

//判断工序节点
const isLinkTabIds = async (data) => {
    const { nodeType } = appItem.value
    if (nodeType === 7 || nodeType === 11) {
        const isLink = data.some(({ linkTabIds }) => {
            const linkIds = getArrValue(linkTabIds)
            return linkIds.length > 0
        })
        if (isLink) {
            return true
        } else {
            postMsg('请先关联工序', 'error')
            return false
        }
    } else {
        return true
    }
}

//发送消息
const postMessage = ({ type, data = {} }) => {
    window?.postMessage({
        type: type,
        source: 'web',
        data: data,
    })
}

//弹出提示
const postMsg = (title, icon) => {
    window?.postMessage({
        type: 'msg',
        source: 'web',
        data: {
            title: title,
            icon: icon,
        },
    })
}
</script>

<style lang="scss">
@import "~src/styles/uni-app/table-form.scss";
</style>
