<template>
    <HcCard>
        <HcTable :column="tableConstructionColumn" :datas="tableConstructionData" :loading="tableConstructionLoading">
            <template #action="{row}">
                <HcTooltip keys="write_construction_edit">
                    <el-button plain size="small" type="primary" @click="tableConstructionEdit(row)">
                        <HcIcon name="edit"/>
                        <span>编辑</span>
                    </el-button>
                </HcTooltip>
            </template>
        </HcTable>
        <template #action>
            <HcPages :pages="searchConstructionForm" @change="pageConstructionChange"/>
        </template>
    </HcCard>

    <!--编辑施工台账-->
    <el-dialog v-model="showConstructionEditModal" class="hc-modal-border" title="编辑施工台账" width="38rem">
        <el-form ref="constructionFormRef" :model="constructionFormModel" :rules="constructionFormRules"
                 label-position="top" label-width="auto" size="large">
            <div class="flex">
                <el-form-item class="flex-1" label="施工起始日期" prop="siteStartTime">
                    <el-date-picker v-model="constructionFormModel.siteStartTime" class="block" format="YYYY-MM-DD"
                                    placeholder="施工起始日期" type="date" value-format="YYYY-MM-DD"/>
                </el-form-item>
                <el-form-item class="mx-4" label=" ">至</el-form-item>
                <el-form-item class="flex-1" label="施工停止日期" prop="siteEndTime">
                    <el-date-picker v-model="constructionFormModel.siteEndTime" class="block" format="YYYY-MM-DD"
                                    placeholder="施工停止日期" type="date" value-format="YYYY-MM-DD"/>
                </el-form-item>
            </div>
            <div class="flex">
                <el-form-item class="flex-1" label="检测起始日期" prop="detectionStartTime">
                    <el-date-picker v-model="constructionFormModel.detectionStartTime" :disabled="!constructionFormModel.siteStartTime || !constructionFormModel.siteEndTime"
                                    class="block"
                                    format="YYYY-MM-DD" placeholder="检测起始日期" type="date"
                                    value-format="YYYY-MM-DD"/>
                </el-form-item>
                <el-form-item class="mx-4" label=" ">至</el-form-item>
                <el-form-item class="flex-1" label="检测停止日期" prop="detectionEndTime">
                    <el-date-picker v-model="constructionFormModel.detectionEndTime" :disabled="!constructionFormModel.siteStartTime || !constructionFormModel.siteEndTime"
                                    class="block"
                                    format="YYYY-MM-DD" placeholder="检测停止日期" type="date"
                                    value-format="YYYY-MM-DD"/>
                </el-form-item>
            </div>
            <el-form-item label="设计方量">
                <el-input v-model="constructionFormModel.designVolume" placeholder="请输入设计方量"/>
            </el-form-item>
            <el-form-item label="实际方量">
                <el-input v-model="constructionFormModel.actualVolume" placeholder="请输入实际方量"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button size="large" @click="showConstructionEditModal = false">
                    <HcIcon name="close"/>
                    <span>取消</span>
                </el-button>
                <el-button :loading="saveConstructionLoading" hc-btn type="primary" @click="saveConstructionClick">
                    <HcIcon name="save"/>
                    <span>提交保存</span>
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script setup>
import {ref, nextTick, watch} from "vue";
import {deepClone, formValidate, getArrValue} from "js-fast-way"
import constructionApi from '~api/ledger/construction';

//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: ''
    },
    contractId: {
        type: [String, Number],
        default: ''
    },
    treeData: {
        type: Object,
        default: () => ({})
    }
})

//变量
const projectId = ref(props.projectId);
const contractId = ref(props.contractId);
const nodeData = ref(props.treeData);

//监听
watch(() => [
    props.treeData
], ([treeData]) => {
    nodeData.value = treeData;
    setQueryData(treeData)
})

//渲染完成
nextTick(() => {
    setQueryData(props.treeData)
})

//获取相关数据
const setQueryData = (data) => {
    const cid = data?.contractIdRelation || ''
    const wbsId = data['contractIdRelation'] ? data['id'] : data['primaryKeyId']
    if (wbsId) {
        searchConstructionForm.value.contractId = cid ? cid : contractId.value;
        searchConstructionForm.value.contractIdRelation = data['contractIdRelation']
        searchConstructionForm.value.wbsIds = [wbsId]
        searchConstructionClick()
    }
}

//搜索表单
const searchConstructionForm = ref({current: 1, size: 20, total: 0})

//搜索
const searchConstructionClick = () => {
    if (searchConstructionForm.value?.wbsIds) {
        searchConstructionForm.value.current = 1;
        getTableConstructionData()
    } else {
        window?.$message?.warning('请先选择一个树节点')
    }
}

//分页被点击
const pageConstructionChange = ({current, size}) => {
    searchConstructionForm.value.current = current
    searchConstructionForm.value.size = size
    getTableConstructionData()
}

//施工台账表头
const tableConstructionColumn = ref([
    {key: 'station', name: '施工桩号'},
    {key: 'site', name: '施工部位'},
    {key: 'siteTimeStr', name: '施工起止日期'},
    {key: 'detectionTimeStr', name: '检测日期'},
    {key: 'designVolume', name: '设计方量'},
    {key: 'actualVolume', name: '实际方量'},
    {key: 'action', name: '操作', width: 100}
])
const tableConstructionData = ref([])

//获取数据
const tableConstructionLoading = ref(false)
const getTableConstructionData = async () => {
    tableConstructionLoading.value = true
    const {error, code, data} = await constructionApi.queryConstructionPage({
        ...searchConstructionForm.value,
        projectId: projectId.value,
    })
    //判断状态
    tableConstructionLoading.value = false
    if (!error && code === 200) {
        tableConstructionData.value = getArrValue(data['records'])
        searchConstructionForm.value.total = data['total'] || 0
    } else {
        tableConstructionData.value = []
        searchConstructionForm.value.total = 0
    }
}

//施工台账编辑
const showConstructionEditModal = ref(false)
const tableConstructionEdit = (row) => {
    constructionFormModel.value = deepClone(row)
    saveConstructionLoading.value = false
    constructionFormRef.value?.resetFields()
    showConstructionEditModal.value = true
}

//施工台账表单
const constructionFormRef = ref(null)
const constructionFormModel = ref({
    siteStartTime: null,
    siteEndTime: null,
    detectionStartTime: null,
    detectionEndTime: null,
    designVolume: '',
    actualVolume: ''
})
const constructionFormRules = ref({
    siteStartTime: {
        required: true,
        validator: (rule, value, callback) => {
            const endTime = constructionFormModel.value?.siteEndTime ?? ''
            if (!value) {
                callback(new Error('请选择施工起始日期'))
            } else {
                callback()
            }
        },
        trigger: "blur",
    },
    siteEndTime: {
        required: true,
        validator: (rule, value, callback) => {
            const startTime = constructionFormModel.value?.siteStartTime ?? ''
            if (!value) {
                callback(new Error('请选择施工停止日期'))
            } else if (value < startTime) {
                callback(new Error('施工停止日期 不能 小于 施工起始日期'))
            } else {
                callback()
            }
        },
        trigger: "blur",
    },
    detectionStartTime: {
        required: true,
        validator: (rule, value, callback) => {
            const endTime = constructionFormModel.value?.siteEndTime ?? ''
            const startTime = constructionFormModel.value?.siteStartTime ?? ''
            if (!value) {
                callback(new Error('请选择检测起始日期'))
            } else if (value < startTime) {
                callback(new Error('检测起始日期 不能 小于 施工起始日期'))
            } else {
                callback()
            }
        },
        trigger: "blur",
    },
    detectionEndTime: {
        required: true,
        validator: (rule, value, callback) => {
            const startTime = constructionFormModel.value?.detectionStartTime ?? ''
            if (!value) {
                callback(new Error('请选择检测停止日期'))
            } else if (value < startTime) {
                callback(new Error('检测停止日期 不能 小于 检测起始日期'))
            } else {
                callback()
            }
        },
        trigger: "blur",
    },
    designVolume: {
        required: true,
        trigger: 'blur',
        message: "请输入设计方量"
    },
    actualVolume: {
        required: true,
        trigger: 'blur',
        message: "请输入实际方量"
    },
})

//提交保存
const saveConstructionClick = async () => {
    const validate = await formValidate(constructionFormRef.value)
    if (validate) {
        const formData = constructionFormModel.value
        const {siteStartTime, siteEndTime, detectionStartTime, detectionEndTime} = formData
        //施工时间
        formData.siteTimeStr = siteStartTime + '~' + siteEndTime
        //检测时间
        formData.detectionTimeStr = detectionStartTime + '~' + detectionEndTime
        //请求保存
        updateConstructionPage(formData)
    }
}
//确认保存
const saveConstructionLoading = ref(false)
const updateConstructionPage = async (formData) => {
    //发起请求
    saveConstructionLoading.value = true
    const {error, code} = await constructionApi.updateConstructionPage({
        ...formData,
        projectId: projectId.value,
        contractId: contractId.value
    }, false)
    //处理数据
    saveConstructionLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        showConstructionEditModal.value = false;
        getTableConstructionData()
    } else {
        window?.$message?.error('保存失败')
    }
}
</script>
