<template>
    <hc-new-card title="合同材料">
        <template #header>
            <el-tabs v-model="headerTabsKey" class="hc-header-tabs" @tab-change="headerTabsClick">
                <el-tab-pane label="合同材料基准数据" name="data" />
                <el-tab-pane label="材料实时价格" name="price" />
            </el-tabs>
        </template>
        <template #extra>
            <el-button v-if="headerTabsKey === 'data'" hc-btn type="primary" @click="rowAddClick">
                <hc-icon name="add" />
                <span>新增</span>
            </el-button>
            <el-button v-else :disabled="isTablePrice" hc-btn type="primary" @click="tablePriceClick">
                <hc-icon name="add" />
                <span>新增</span>
            </el-button>
        </template>
        <!-- 合同材料基准数据 -->
        <div v-if="headerTabsKey === 'data'" class="relative h-full flex">
            <div class="flex-1">
                <hc-card-item>
                    <hc-table
                        ref="tableRef1" :column="tableColumn" :datas="tableData" :index-style="{ width: 60 }"
                        :loading="tableLoading" is-current-row is-new @row-click="tableViewRow"
                    >
                        <template #action="{ row }">
                            <el-link type="primary" :disabled="row.isSync === 0" @click="synchronization(row)">同步</el-link>
                            <el-link type="success" :disabled="row.isUpdateOrDelete === 0" @click="rowEditClick(row)">编辑</el-link>
                            <el-link type="danger" :disabled="row.isUpdateOrDelete === 0" @click="delRowClick(row)">删除</el-link>
                        </template>
                    </hc-table>
                    <template #action>
                        <hc-pages :pages="searchForm" @change="pageChange" />
                    </template>
                </hc-card-item>
            </div>
            <div class="ml-3 w-[400px]">
                <hc-card-item scrollbar title="详情信息">
                    <el-form :model="infoData" disabled label-position="left" label-width="auto" size="large">
                        <el-form-item label="材料编号：">
                            <el-input v-model="infoData.materialNumber" />
                        </el-form-item>
                        <el-form-item label="材料名称：">
                            <el-input v-model="infoData.materialName" />
                        </el-form-item>
                        <el-form-item label="规格型号：">
                            <el-input v-model="infoData.specification" />
                        </el-form-item>
                        <el-form-item label="单位：">
                            <el-input v-model="infoData.unit" />
                        </el-form-item>
                        <el-form-item label="(基期)单价：">
                            <el-input v-model="infoData.price" />
                        </el-form-item>
                        <el-form-item label="材料损耗：">
                            <el-input v-model="infoData.wastageRatio" placeholder="材料损耗率" />
                        </el-form-item>
                        <el-form-item label="调差限额：">
                            <el-input v-model="infoData.quotaRatio" placeholder="调差限额百分比" />
                        </el-form-item>
                        <el-form-item label="收益/承担：">
                            <el-input v-model="infoData.ownerRatio" placeholder="业主收益/承担百分比" />
                        </el-form-item>
                        <el-form-item label="综合抵扣：">
                            <el-input v-model="infoData.deductionRatio" placeholder="材料综合抵扣率" />
                        </el-form-item>
                    </el-form>
                </hc-card-item>
            </div>
        </div>
        <!-- 材料实时价格 -->
        <hc-body v-else split padding="0">
            <template #left>
                <hc-card-item scrollbar>
                    <hc-data-tree tree-key="id" :auto-expand-keys="treeExpandKeys" :h-props="treeProps" :datas="treeLoadNode" @node-tap="treeNodeTap" />
                </hc-card-item>
            </template>
            <hc-card-item v-if="isTablePrice">
                <template #header>
                    <div class="text-14px text-red">*价格有效期</div>
                    <div class="ml-3 w-64">
                        <hc-date-picker :dates="betweenTime" @change="betweenTimeUpdate" />
                    </div>
                </template>
                <template #extra>
                    <el-button @click="priceCancelClick">取消</el-button>
                    <el-button type="success" :loading="saveLoaing1" @click="tablePriceSave">提交保存</el-button>
                </template>
                <hc-table :column="tableColumn1" :datas="tableData2" :loading="tableLoading2" :is-index="false">
                    <template #price="{ row }">
                        <hc-table-input v-model="row.price" />
                    </template>
                </hc-table>
            </hc-card-item>
            <hc-card-item v-else>
                <hc-table :column="tableColumn1" :datas="tableData1" :loading="tableLoading1" :is-index="false" />
            </hc-card-item>
        </hc-body>
        <!-- 新增/修改 -->
        <hc-new-dialog v-model="isFormModal" :title="modalTitle" is-footer-center widths="40rem" @close="modalClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" class="p-2" label-position="top" size="large">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="材料编号：">
                            <el-input v-model="formModel.materialNumber" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="材料名称：" prop="materialName">
                            <el-input v-model="formModel.materialName" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规格型号：">
                            <el-input v-model="formModel.specification" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单位：">
                            <el-input v-model="formModel.unit" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="(基期)单价：">
                            <el-input-number v-model="formModel.price" :controls="false" :min="0" class="w-100" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="材料损耗率：">
                            <el-input-number v-model="formModel.wastageRatio" :controls="false" :min="0" class="w-100" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="调差限额百分比：">
                            <el-input-number v-model="formModel.quotaRatio" :controls="false" :min="0" class="w-100" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="业主收益/承担百分比：">
                            <el-input-number v-model="formModel.ownerRatio" :controls="false" :min="0" class="w-100" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="材料综合抵扣率：">
                            <el-input-number v-model="formModel.deductionRatio" :controls="false" :min="0" class="w-100" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="modalClose">取消</el-button>
                <el-button :loading="saveLoaing" hc-btn type="primary" @click="modalSave">提交</el-button>
                <el-button v-if="!formModel.id" :loading="saveLoaing" hc-btn type="primary" @click="modalSaveClose">提交并关闭</el-button>
            </template>
        </hc-new-dialog>
        <!-- 同步材料数据 -->
        <hc-new-dialog v-model="asyncModal" title="同步材料数据" :footer="false" widths="70%" @close="asyncClose">
            <hc-table :column="asyncColumn" :datas="asyncData" :index-style="{ width: 60 }" :loading="asyncLoading">
                <template #action="{ row }">
                    <el-link type="primary" @click="syncRowData(row)">同步到当前合同段</el-link>
                </template>
            </hc-table>
        </hc-new-dialog>
    </hc-new-card>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { HcDelMsg } from 'hc-vue3-ui'
import { getStoreValue, setStoreValue } from '~uti/storage'
import { deepClone, formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/debit-pay/material/contract'
import { useAppStore } from '~src/store'

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

defineOptions({
    name: 'DebitPayMaterialContract',
})

//渲染完成
onActivated(() => {
    getTableData()
})

//标签页
const headerTabsKey = ref('data')
const headerTabsClick = (tab) => {
    console.log(tab)
    if (tab === 'data') {
        searchForm.value.current = 1
        getTableData()
    } else if (tab === 'price') {
        getDateTree()
    }
}

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

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef1 = ref(null)
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'materialNumber', name: '材料编号' },
    { key: 'materialName', name: '材料名称' },
    { key: 'specification', name: '规格型号' },
    { key: 'unit', name: '单位' },
    { key: 'price', name: '(基期)单价' },
    { key: 'wastageRatio', name: '材料损耗率(%)' },
    { key: 'quotaRatio', name: '调差限额百分比(%)' },
    { key: 'ownerRatio', name: '业主收益/承担百分比(%)' },
    { key: 'deductionRatio', name: '材料综合抵扣率(%)' },
    { key: 'action', name: '操作', width: 120, align: 'center' },
])

//获取表格数据
const tableData = ref([])
const infoData = ref({})
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await mainApi.getPage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total']
        if (tableData.value.length > 0) {
            infoData.value = tableData.value[0]
            tableRef1.value?.tableRef?.setCurrentRow(tableData.value[0])
        }
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}
//表格行被点击
const tableViewRow = ({ row }) => {
    infoData.value = row
}

//新增
const modalTitle = ref('')
const isFormModal = ref(false)
const rowAddClick = () => {
    isFormModal.value = true
    formModel.value = {}
    modalTitle.value = '合同材料新增'
}

//表单数据
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    materialName: {
        required: true,
        trigger: 'blur',
        message: '请输入材料名称',
    },
}

//修改
const rowEditClick = (row) => {
    modalTitle.value = '合同材料修改'
    isFormModal.value = true
    const form = deepClone(row)
    //处理类型
    form.price = isNullES(form.price) ? null : Number(form.price)
    form.amount = isNullES(form.amount) ? null : Number(form.amount)
    //赋值给表单
    formModel.value = form
}

//保存
const saveLoaing = ref(false)
const submitData = async () => {
    const res = await formValidate(formRef.value)
    if (!res) return
    saveLoaing.value = true
    const { error, code, msg } = await mainApi.submit({
        ...formModel.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    //判断状态
    saveLoaing.value = false
    if (!error && code === 200) {
        window.$message.success(msg)
        return true
    } else {
        window.$message.error(msg ?? '操作失败')
        return false
    }
}

//提交保存
const isSubmit = ref(false)
const modalSave = async () => {
    const form = formModel.value
    const isValidate = await submitData()
    if (isValidate && isNullES(form.id)) {
        isSubmit.value = true
        formModel.value = {}
    } else if (isValidate && !isNullES(form.id)) {
        getTableData().then()
        modalClose()
    }
}

//提交并关闭
const modalSaveClose = async () => {
    const isValidate = await submitData()
    if (isValidate) {
        getTableData().then()
        modalClose()
    }
}

//删除
const delRowClick = (row) => {
    HcDelMsg(async (resolve) => {
        const { error, code, msg } = await mainApi.remove({ ids: row.id })
        if (!error && code === 200) {
            window?.$message?.success('删除成功')
            getTableData().then()
            formModel.value = {}
            resolve() //关闭弹窗的回调
        } else {
            window.$message.error(msg ?? '操作失败')
        }
    })
}

//关闭弹窗
const modalClose = () => {
    isFormModal.value = false
    if (isSubmit.value) {
        getTableData()
    }
}

//数据格式
const treeStore = 'debit-pay-material-contract-tree-keys'
const treeExpandKeys = ref(getStoreValue(treeStore) || [])
const treeProps = {
    label: 'nodeName',
    children: 'children',
}

//数据
const treeLoadNode = ref([])
const getDateTree = async () => {
    const { data } = await mainApi.dateTree({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    treeLoadNode.value = getArrValue(data)
}

//树节点被点击
const treeInfo = ref({})
const treeNodeTap = ({ data, keys }) => {
    treeInfo.value = getObjValue(data)
    setStoreValue(treeStore, keys)
    treeExpandKeys.value = keys || []
    getTableData1()
}

//材料实时价格
const tableColumn1 = [
    { key: 'materialNumber', name: '材料编码' },
    { key: 'materialName', name: '材料名称' },
    { key: 'unit', name: '材料单位' },
    { key: 'price', name: '单价(元)' },
]
const tableData1 = ref([])

//获取数据
const tableLoading1 = ref(false)
const getTableData1 = async () => {
    const { id } = treeInfo.value
    tableLoading1.value = true
    const { data } = await mainApi.dateTreeTable(id)
    tableData1.value = getArrValue(data)
    tableLoading1.value = false
}

//新增
const isTablePrice = ref(false)
const tablePriceClick = () => {
    isTablePrice.value = true
    getTableData2()
}

//获取数据
const tableData2 = ref([])
const tableLoading2 = ref(false)
const getTableData2 = async () => {
    tableLoading2.value = true
    const { data } = await mainApi.getAllMaterial(contractId.value)
    tableData2.value = getArrValue(data)
    tableLoading2.value = false
}

//日期选择
const betweenTime = ref(null)
const dateFormInfo = ref({ startDate:'', endDate:'' })
const betweenTimeUpdate = ({ arr }) => {
    dateFormInfo.value = { startDate:arr[0], endDate:arr[1] }
}

//保存
const saveLoaing1 = ref(false)
const tablePriceSave = async () => {
    const { startDate, endDate } = dateFormInfo.value
    if (isNullES(startDate) || isNullES(endDate)) {
        window.$message.error('请先选择日期')
        return
    }
    saveLoaing1.value = true
    const { error, code, msg } = await mainApi.addDateTreeTable({
        startDate: startDate,
        endDate: endDate,
        projectId: projectId.value,
        contractId: contractId.value,
        materials: tableData2.value,
    })
    saveLoaing1.value = false
    if (!error && code === 200) {
        window.$message.success('删除成功')
        getDateTree()
        priceCancelClick()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}

//取消
const priceCancelClick = () => {
    isTablePrice.value = false
    tableData2.value = []
    tableLoading2.value = false
}

//同步
const asyncColumn = ref([
    { key: 'contractName', name: '数据来源' },
    { key: 'materialNumber', name: '材料编号' },
    { key: 'materialName', name: '材料名称' },
    { key: 'specification', name: '规格型号' },
    { key: 'unit', name: '单位' },
    { key: 'price', name: '单价' },
    { key: 'wastageRatio', name: '材料损耗率(%)' },
    { key: 'quotaRatio', name: '调差限额百分比(%)' },
    { key: 'ownerRatio', name: '业主收益/承担百分比(%)' },
    { key: 'deductionRatio', name: '材料综合抵扣率(%)' },
    { key: 'action', name: '操作', width: 140, align: 'center' },
])
const asyncData = ref([])
const asyncLoading = ref(false)
const asyncInfo = ref({})

//同步
const asyncModal = ref(false)
const synchronization = async (row) => {
    asyncInfo.value = row
    asyncModal.value = true
    asyncLoading.value = true
    const { data } = await mainApi.getSyncData({
        materialNumber: row.materialNumber,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    asyncData.value = getArrValue(data)
    asyncLoading.value = false
}

//同步到当前合同段
const syncRowData = async (row) => {
    const { error, code, msg } = await mainApi.syncMaterial({
        id: asyncInfo.value.id,
        selectId: row.id,
    })
    if (!error && code === 200) {
        window.$message.success(msg)
        asyncClose()
        getTableData().then()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}

//关闭同步
const asyncClose = () => {
    asyncModal.value = false
    asyncInfo.value = {}
    asyncData.value = []
    asyncLoading.value = false
}
</script>

<style lang="scss">
.el-tabs.hc-header-tabs {
    position: absolute;
    --el-tabs-header-height: 46px;
    .el-tabs__header {
        margin-bottom: 0;
    }
    .el-tabs__nav-wrap {
        margin-bottom: -1px;
    }
    .el-tabs__nav-wrap:after {
        background-color: transparent;
    }
}
</style>
