<template>
    <div class="relative h-full flex">
        <div :id="`hc_table_card_${uuid}`">
            <hc-new-card>
                <template #header>
                    <el-button hc-btn type="primary" @click="systemPaymentClick">引用项目支付项</el-button>
                    <el-button hc-btn type="primary" @click="sortClick">
                        <HcIcon name="arrow-up-down" />
                        <span>排序</span>
                    </el-button>
                </template>
                <hc-table
                    :column="tableColumn" :datas="tableData" :loading="tableLoading" is-new
                    :index-style="{ width: 60 }" is-current-row @row-click="viewRowClick"
                >
                    <template #isDeduct="{ row }">
                        <span>{{ row?.isDeduct === 1 ? '是' : '否' }}</span>
                    </template>
                    <template #isTotalTerms="{ row }">
                        <span>{{ row?.isTotalTerms === 1 ? '是' : '否' }}</span>
                    </template>
                    <template #action="{ row }">
                        <el-link type="success" @click="editRowClick(row)">修改</el-link>
                        <el-link type="danger" @click="delRowClick(row)">删除</el-link>
                    </template>
                </hc-table>
                <template #action>
                    <hc-pages :pages="searchForm" @change="pageChange" />
                </template>
            </hc-new-card>
        </div>
        <div :id="`hc_info_card_${uuid}`" class="flex-1">
            <hc-new-card scrollbar>
                <infoTable :ids="rowViewId" />
                <hc-title title="汇总项">
                    <template #extra>
                        <el-link type="primary" @click="addColloect">添加汇总项</el-link>
                    </template>
                </hc-title>
                <hc-table :column="tableColumn1" :datas="tableData1" is-new :index-style="{ width: 60 }">
                    <template #isDeduct="{ row }">
                        <span>{{ row?.isDeduct === 1 ? '是' : '否' }}</span>
                    </template>
                    <template #action="{ row }">
                        <el-link type="danger" @click="delCollectRow(row)">删除</el-link>
                    </template>
                </hc-table>
            </hc-new-card>
        </div>

        <!-- 引用系统支付项 -->
        <systemPay v-model="systemPayShow" @finish="finishSystemPay" />

        <!-- 修改项目支付项 -->
        <rowDataInfo v-model="isEditRowShow" :ids="rowDataId" @finish="finishEditRow" />

        <!-- 添加汇总项 -->
        <hc-new-dialog v-model="isCollectShow" is-table widths="1200px" title="添加汇总项" @save="collectModalSave">
            <div class="hc-flex-column">
                <div class="hc-flex-shrink hc-alert-primary">
                    <span class="mr-1">当前表格已选择</span>
                    <span class="text-4">{{ selectArr.length }}</span>
                    <span class="ml-1">项</span>
                </div>
                <div class="hc-flex-content">
                    <hc-body padding="0px">
                        <hc-table
                            :column="tableCollectColumn" :datas="tableCollectData" :loading="tableCollectLoading"
                            is-new :check-style="{ width: 29 }" :index-style="{ width: 60 }"
                            is-check @selection-change="tableCollectCheckChange"
                        >
                            <template #isDeduct="{ row }">
                                <span>{{ row?.isDeduct === 1 ? '是' : '否' }}</span>
                            </template>
                            <template #isTotalTerms="{ row }">
                                <span>{{ row?.isTotalTerms === 1 ? '是' : '否' }}</span>
                            </template>
                        </hc-table>
                    </hc-body>
                </div>
            </div>
        </hc-new-dialog>
        <!-- 排序弹框 -->
        <hc-new-dialog v-model="sortModal" title="排序" widths="80rem">
            <hc-table
                ref="tableRef"
                ui="hc-test-drop-table"
                :column="sorttableColumn" :datas="sorttableData" :loading="tableLoading" :index-style="{ width: 80 }"
                is-new
                is-row-drop quick-sort
                @row-drop="rowDropTap" @row-sort="rowSortTap"
            >
                <template #isDeduct="{ row }">
                    <span>{{ row?.isDeduct === 1 ? '是' : '否' }}</span>
                </template>
                <template #isTotalTerms="{ row }">
                    <span>{{ row?.isTotalTerms === 1 ? '是' : '否' }}</span>
                </template>
                <template #action="{ index }">
                    <span class="text-link text-xl" @click="upSortClick(index)">
                        <HcIcon name="arrow-up" fill />
                    </span>
                    <span class="text-link ml-2 text-xl" @click="downSortClick(index)">
                        <HcIcon name="arrow-down" fill />
                    </span>
                </template>
            </hc-table>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="sortModal = false">取消</el-button>
                    <el-button :loading="sortLoding" hc-btn type="primary" @click="saveSortClick">保存</el-button>
                </div>
            </template>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { nextTick, onActivated, onMounted, ref } from 'vue'
import { getRandom } from 'js-fast-way'
import infoTable from './components/pay/info-table.vue'
import systemPay from './components/pay/system-pay.vue'
import rowDataInfo from './components/pay/row-data.vue'
import payApi from '~api/project/debit/contract/pay.js'
import { arrToId, getArrValue, getObjValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import { HcDelMsg } from 'hc-vue3-ui'

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
defineOptions({
    name: 'ProjectDebitProjectPay',
})

const uuid = getRandom(4)

//渲染完成
onMounted(() => {
    setSplitRef()
})

onActivated(() => {
    getTableData()
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    nextTick(() => {
        window.$split(['#hc_table_card_' + uuid, '#hc_info_card_' + uuid], {
            sizes: [70, 30],
            snapOffset: 0,
            minSize: [50, 300],
        })
    })
}

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

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

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'payNumber', name: '支付项编号', width: 140 },
    { key: 'payName', name: '支付项名称' },
    { key: 'payTypeName', name: '支付项类型', width: 160 },
    { key: 'isDeduct', name: '是否为扣款项', width: 100 },
    { key: 'isTotalTerms', name: '是否合计项', width: 100 },
    { key: 'payApplicableTypeName', name: '适用类型', width: 100 },
    { key: 'action', name: '操作', width: 100 },
])
const sorttableColumn = ref([
    { key: 'payNumber', name: '支付项编号', width: 140 },
    { key: 'payName', name: '支付项名称' },
    { key: 'payTypeName', name: '支付项类型', width: 160 },
    { key: 'isDeduct', name: '是否为扣款项', width: 100 },
    { key: 'isTotalTerms', name: '是否合计项', width: 100 },
    { key: 'payApplicableTypeName', name: '适用类型', width: 100 },
    { key: 'action', name: '排序', width: 90 },

])
const tableData = ref([])
const sorttableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await payApi.getProListPage({
        ...searchForm.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) {
            getDetail(tableData.value[0].id)
            rowViewId.value = tableData.value[0].id

        }


    } else {
        tableData.value = []
        searchForm.value.total = 0

    }
}

//向下
const downSortClick = (index) => {
    const indexs = index + 1
    const data = sorttableData.value
    if (indexs !== data.length) {
        const tmp = data.splice(indexs, 1)
        sorttableData.value.splice(index, 0, tmp[0])
    } else {
        window?.$message?.warning('已经处于置底，无法下移')
    }
}

//向上
const upSortClick = (index) => {
    const data = sorttableData.value || []
    if (index !== 0) {
        const tmp = data.splice(index - 1, 1)
        sorttableData.value.splice(index, 0, tmp[0])
    } else {
        window?.$message?.warning('已经处于置顶，无法上移')
    }
}
//引用系统支付项
const systemPayShow = ref(false)
const systemPaymentClick = () => {
    systemPayShow.value = true
}

const finishSystemPay = () => {
    getTableData()
    systemPayShow.value = false

}
//汇总项
const tableColumn1 = ref([
    { key: 'payNumber', name: '支付项编号' },
    { key: 'payName', name: '支付项名称' },
    { key: 'payTypeName', name: '支付项类型' },
    { key: 'contractFormulaIds', name: '合同计算公式' },
    { key: 'updateFormulaIds', name: '变更计算公式' },
    { key: 'currentFormulaIds', name: '本期计算公式' },
    { key: 'isDeduct', name: '是否为扣款项' },
    { key: 'action', name: '操作', width: 50 },
])
const tableData1 = ref([])

//修改
const rowDataId = ref('')
const rowViewId = ref('')
const isEditRowShow = ref(false)
const editRowClick = (row) => {
    isEditRowShow.value = true
    rowDataId.value = row.id

}
//获取节点详情
const getDetail = async (id) => {
    const { error, code, data } = await payApi.getProDetail({
        id,
    })
    if (!error && code === 200) {
        tableData1.value = getObjValue(data)['summaryItemList']

    } else {
        tableData1.value = []
    }
}
const viewRowClick = ({ row }) => {
    rowViewId.value = row.id
    getDetail(row.id)
}
const finishEditRow = () => {
    isEditRowShow.value = false
    getTableData()
}
const delRowClick = (row) => {
    HcDelMsg( async ( resolve) => {
            await removeProPay(row.id)
            resolve() //关闭弹窗的回调
        })
}
const removeProPay = async (id) => {
    const { error, code } = await payApi.removeProList({
        id: id,
    })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getTableData()
        rowViewId.value = ''
    }
}
//添加汇总项
const isCollectShow = ref(false)
const collectSaveLoading = ref(false)
const collectModalSave = async () => {

    collectSaveLoading.value = true
    const { error, code, msg } = await payApi.addCollect({
        bindIds: selectTableCollectIds.value,
        id: rowViewId.value,

    })
    //判断状态
    collectSaveLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
    } else {
            window.$message.error(msg)
     }
    getDetail(rowViewId.value)
    isCollectShow.value = false
}
const addColloect = () => {
    isCollectShow.value = true
    getTableCollectData()
    selectArr.value = []
}
//删除汇总项
const delCollectRow = async (row) => {
    HcDelMsg( async ( resolve) => {
            await removeCollectPay(row.id)
            resolve() //关闭弹窗的回调
        })
}
const removeCollectPay = async (id) => {
    const { error, code, msg } = await payApi.removeCollect({
        id: rowViewId.value,
        bindId: id,
    })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getDetail(rowViewId.value)
    } else {
         window.$message.error(msg)
     }
}
//添加汇总项
const tableCollectColumn = ref([
    { key: 'payNumber', name: '支付项编号' },
    { key: 'payName', name: '支付项名称' },
    { key: 'payTypeName', name: '支付项类型' },
    { key: 'isDeduct', name: '是否为扣款项' },
    { key: 'isTotalTerms', name: '是否合计项' },
    { key: 'payApplicableTypeName', name: '支付项适用类型' },
])
const tableCollectData = ref([])
const tableCollectLoading = ref(false)
const getTableCollectData = async () => {
    tableCollectLoading.value = true
    const { error, code, data } = await payApi.getProListPage({
        type: '1',
        contractId: contractId.value,
        recordId: rowViewId.value,
        current: 1, size: 100000,
    })
    tableCollectLoading.value = false
    if (!error && code === 200) {
        tableCollectData.value = getArrValue(data['records'])

    } else {
        tableCollectData.value = []

    }
}
const selectTableCollectIds = ref('')
const selectArr = ref([])
const tableCollectCheckChange = (list) => {
    selectArr.value = list
    selectTableCollectIds.value = arrToId(list)
}


const sortModal = ref(false)
const sortClick = ()=>{
    sortModal.value = true
    sorttableData.value = Array.from(tableData.value)
}
const tableRef = ref(null)
// 行拖拽
const rowDropTap = (rows) => {
    sorttableData.value = [] // 先清空，否则排序会异常
    nextTick(() => {
        tableRef.value?.setData(rows)
        sorttableData.value = rows
    })
}

// 点击排序
const rowSortTap = (rows) => {
    sorttableData.value = [] // 先清空，否则排序会异常
    nextTick(() => {
        sorttableData.value = rows
    })
}
const sortLoding = ref(false)
const saveSortClick = async ()=>{
    console.log(sorttableData.value, 'sorttableData.value')
    const ids = arrToId(sorttableData.value)
    //发起请求
    sortLoding.value = true
    const { error, code, msg } = await payApi.getSort({ ids })
    sortLoding.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        sortModal.value = false
        getTableData()
    } else {
         window.$message.error(msg)
     }
}
</script>
