<template>
    <HcPageLayout id="hc-settle-node-target">
        <template #left>
            <div class="hc-layout-tree-box">
                <el-scrollbar>
                    <HcTreeData @nodeTap="treeNodeTap" />
                </el-scrollbar>
            </div>
        </template>
        <HcCard>
            <template #header>
                <div class="w-32">
                    <el-select v-model="searchForm.type" block clearable placeholder="补偿类型" size="large" @change="changType">
                        <el-option label="征地补偿" value="1" />
                        <el-option label="坟地补偿" value="2" />
                        <el-option label="专项补偿" value="3" />
                    </el-select>
                </div>
                <div class="w-32 ml-2">
                    <el-select v-model="searchForm.stageId" block clearable placeholder="计量期" size="large">
                        <el-option v-for="item in numberOptions" :key="item.id" :label="item.number" :value="item.id" />
                    </el-select>
                </div>
                <div class="w-52 ml-2">
                    <el-input v-model="searchForm.queryValue" clearable placeholder="请输入名称进行查询" size="large" />
                </div>
                <div class="ml-4">
                    <el-button type="primary" size="large" @click="searchClick">
                        <HcIcon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extra>
                <el-button size="large" type="primary" hc-btn @click="addRowClick">
                    新增结算
                </el-button>
                <el-button size="large" type="success" hc-btn @click="editingClick">
                    编辑结算周期
                </el-button>
                <el-button size="large" type="warning" hc-btn @click="cycleClick">
                    查看报表
                </el-button>
                <el-button size="large" type="danger" hc-btn :disabled="tableCheckedKeys.length < 1" @click="batchDel">
                    批量删除
                </el-button>
            </template>
            <HcTable :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check @selection-change="tableSelectionChange">
                <template #name="{ row, index }">
                    <span class="text-blue text-hover" @click="previewPdf(row)">{{ row.name }}</span>
                </template>
                <template #action="{ row, index }">
                    <el-button size="small" type="primary" @click="editRowClick(row)">
                        修改
                    </el-button>
                    <el-button size="small" type="danger" @click="delRowClick(row)">
                        删除
                    </el-button>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </HcCard>

        <!-- 抽屉 -->
        <HcDrawer :show="isDrawer" uis="hc-settle-drawer" to-id="hc-main-box" @close="drawerClose">
            <div class="hc-settle-drawer-box">
                <div class="settle-left-box">
                    <div class="settle-pdf">
                        <HcPdf src="http://bladex-chongqing-info.oss-cn-hangzhou.aliyuncs.com//upload/20230504/911982ba85e66cfa58fb02d5a738bb2b.pdf" />
                    </div>
                </div>
                <div class="settle-right-box">
                    <div class="settle-right">
                        <div class="hc-settle-cycle">
                            <div class="title">
                                结算周期
                            </div>
                            <div class="cycle-box">
                                <el-scrollbar>
                                    <div class="item">
                                        第一期
                                    </div>
                                    <div class="item">
                                        第一期
                                    </div>
                                    <div class="item">
                                        第一期
                                    </div>
                                    <div class="item">
                                        第一期
                                    </div>
                                </el-scrollbar>
                            </div>
                        </div>
                        <div class="hc-settle-cycle of">
                            <div class="title">
                                结算报表名称
                            </div>
                            <div class="cycle-box">
                                <el-scrollbar>
                                    <div class="item">
                                        封面
                                    </div>
                                    <div class="item">
                                        补偿结算表
                                    </div>
                                    <div class="item">
                                        补偿明细表
                                    </div>
                                    <div class="item">
                                        面积统计明细表
                                    </div>
                                </el-scrollbar>
                            </div>
                        </div>
                        <div class="hc-settle-btn">
                            <el-button type="primary" hc-btn size="large" @click="drawerClose">
                                取 消 查 阅
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </HcDrawer>

        <!-- 新增结算单 -->
        <HcDialog is-to-body bg-color="white" is-table widths="80%" :title="addTitle" :padding="false" :show="rowModal" :loading="addLoaing" @save="rowModalSave" @close="rowModalClose">
            <div class="hc-settle-dialog-box">
                <div id="settle-dialog-tree" class="hc-settle-dialog-tree">
                    <el-scrollbar>
                        <HcTreeData :is-menu="false" @nodeTap="treeNodeTap1" />
                    </el-scrollbar>
                </div>
                <div id="settle-dialog-table" class="hc-settle-dialog-table">
                    <div class="dialog-table-header">
                        <i class="ri-asterisk" style="color:red;line-height: 40px;padding-right: 5px;" />
                        <div class="w-44">
                            <el-select v-model="jqnumber" block clearable placeholder="请选择结算期数" size="large">
                                <el-option v-for="item in numberOptions" :key="item.id" :label="item.number" :value="item.number" />
                            </el-select>
                        </div>
                        <div class="w-32 ml-8" style="position: absolute; right: 320px;">
                            <el-select v-model="searchForm1.type" block clearable placeholder="补偿类型" size="large" @change="changType">
                                <el-option label="征地补偿" value="1" />
                                <el-option label="坟地补偿" value="2" />
                                <el-option label="专项补偿" value="3" />
                            </el-select>
                        </div>
                        <div class="w-52 ml-2" style="position: absolute; right: 100px;">
                            <el-input v-model="searchForm1.number" clearable placeholder="请输入协议编号进行查询" size="large" />
                        </div>
                        <div class="ml-4" style="position: absolute; right: 0;">
                            <el-button type="primary" size="large" @click="searchClick1">
                                <HcIcon name="search-2" />
                                <span>搜索</span>
                            </el-button>
                        </div>
                    </div>
                    <div class="dialog-table-body">
                        <HcTable ref="addTableRef" :column="tableColumn1" :datas="tableData1" is-check @selection-change="tableSelectionChange" />
                    </div>
                </div>
            </div>
        </HcDialog>

        <!-- 结算周期编辑 -->
        <HcDialog is-to-body bg-color="white" is-table widths="80%" title="编辑结算周期" :show="editingModal" @save="editingModalSave" @close="editingModalClose">
            <div class="hc-settle-editing-dialog-box">
                <div class="editing-dialog-tip">
                    <div class="name">
                        提示：
                    </div>
                    <div class="content">
                        <div class="item truncate">
                            1.日期不能为空
                        </div>
                        <div class="item truncate">
                            2.同一期的结束日期不能小于开始日期
                        </div>
                        <div class="item truncate">
                            3.连续的两期，上一期结束日期和下一期的开始日期必须连续，如：期号1的结束日期为2018-1-25，则期号2的开始日期必须是2018-1-26 ！
                        </div>
                        <div class="item truncate text-orange">
                            4.已经存在数据的结算周期不能进行删除以及修改结算类型！
                        </div>
                    </div>
                    <div class="btn">
                        <el-button type="primary" size="large" @click="addInRow">
                            <HcIcon name="add" />
                            <span>添加</span>
                        </el-button>
                    </div>
                </div>
                <div class="editing-dialog-table">
                    <HcTable :is-index="false" :column="tableColumn2" :datas="tableData2">
                        <template #number="{ row, index }">
                            <el-input v-model="row.number" />
                        </template>
                        <template #startDate="{ row, index }">
                            <el-date-picker v-model="row.startDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" @change="checkTime(row)" />
                        </template>
                        <template #endDate="{ row, index }">
                            <el-date-picker v-model="row.endDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" @change="checkTime(row)" />
                        </template>
                        <template #printDate="{ row, index }">
                            <el-date-picker v-model="row.printDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
                        </template>
                        <template #remark="{ row, index }">
                            <el-input v-model="row.remark" />
                        </template>
                        <template #action="{ row, index }">
                            <el-button size="small" type="danger" :loading="delInLoad" @click="delInRow(row, index)">
                                删除
                            </el-button>
                        </template>
                    </HcTable>
                </div>
            </div>
        </HcDialog>
    </HcPageLayout>
</template>

<script setup>
import { nextTick, onUnmounted, ref } from 'vue'
import split from 'split.js'
import settleApi from '~api/settle/index.js'
import { arrToId, getArrValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import { delMessageV2 } from '~com/message/index.js'
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
//树节点被点击
const treeNodeTap = ({ node, data }) => {
    searchForm.value.areaId = data.id
    getTableData()
}

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

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}
const searchClick1 = () => {
    searchForm1.value.current = 1
    getTableData1()
}
//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//获取数据
const tableLoading = ref(false)
const tableColumn = [
    { key: 'stage', name: '计量期' },
    { key: 'name', name: '结算协议书名称' },
    { key: 'typeValue', name: '协议书类型' },
    { key: 'agreementMoney', name: '协议书金额' },
    { key: 'action', name: '操作', width: '130', align: 'center' },
]
const tableData = ref([
])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await settleApi.getOutPage({
        projectId: projectId.value,
        ...searchForm.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
      
    } else {
        tableData.value = []
     
    }
}

//多选事件
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows
}


//结算周期
const isDrawer = ref(false)
const cycleClick = () => {
    isDrawer.value = true
}
const drawerClose = () => {
    isDrawer.value = false
}


//弹窗
const rowModal = ref(false)
const formModel = ref({})
const addTitle = ref('新增结算单')

// 初始化设置拖动分割线
const splitvar = ref(null)
const setSplitDom = () => {
    try {
        //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
        splitvar.value = split([
            '#settle-dialog-tree',
            '#settle-dialog-table',
        ], {
            sizes: [20, 80],
            minSize: [200, 900],
        })
    } catch (e) {
        setTimeout(() => {
            setSplitDom()
        }, 500)
    }
}

const tableColumn1 = [
    { key: 'number', name: '协议书编号' },
    { key: 'name', name: '结算协议书名称' },
    { key: 'allMoney', name: '协议书补偿金额(元)' },
]
const tableData1 = ref([])
const addTableRef = ref(null)
const searchForm1 = ref({ type:'1' })
const tableLoading1 = ref(false)
const getTableData1 = async () => {
    tableLoading1.value = true
    const { error, code, data } = await settleApi.getAgreementList({
        projectId: projectId.value,
        ...searchForm1.value,
        agreementIds:rowagreementIds.value,
    })
    tableLoading1.value = false
    if (!error && code === 200) {
        tableData1.value = getArrValue(data)
        let item = tableData1.value.filter(item=>item.isQuote === 1)
        await nextTick()
        item.forEach((ele)=>{
            addTableRef.value.toggleRowSelection(ele, true)
        })
      
    } else {
        tableData1.value = []
     
    }
}
const treeNodeTap1 = ({ node, data }) => {
    searchForm1.value.areaId = data.id
    getTableData1()
}
//新增
const addRowClick = () => {
    formModel.value = {}
    rowModal.value = true
    addTitle.value = '新增结算单'
    searchForm1.value.type = '1'
    rowagreementIds.value = ''
    searchForm1.value.number = ''
    tableCheckedKeys.value = []
    addTableRef.value?.clearSelection()
    changType('1')
    getTableData1()
    nextTick(() => {
        setSplitDom()
    })
}
//查看附件

const previewPdf = (row) => {
  const { mergePdfUrl } = row
  if (mergePdfUrl) {
    window.open(mergePdfUrl, '_blank')
  } else {
    window.$message.warning('文件不存在')
  }
 
}
//编辑
const rowagreementIds = ref('')
const editId = ref('')
const editRowClick = (row) => {
    rowagreementIds.value = row.agreementIds
    searchForm1.value.type = row.type.toString()
    changType( searchForm1.value.type)
    jqnumber.value = row.stage
    editId.value = row.id
    addTitle.value = '修改结算单'
    formModel.value = {}
    rowModal.value = true
    nextTick(() => {
        setSplitDom()
    })
}
//删除协议
const delRowClick = (row)=>{
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow(row.id)
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
//批量删除
const batchDel = ()=>{
    const ids = arrToId(tableCheckedKeys.value)
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow(ids)
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
const removeRow = async (id)=>{
    const { error, code } = await settleApi.remove( { ids:id })
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message?.error('删除失败')
    }
}

//保存
const addLoaing = ref(false)
const rowModalSave = async () => {
    const agreementIds = arrToId(tableCheckedKeys.value)
    const stage = jqnumber.value
    let stageId = ''
    numberOptions.value.forEach((ele)=>{
        if ( ele.number === stage) {
            stageId = ele.id
        }
    })
    if (!stage) {
        window.$message.warning('请选择结算期数')
    } else if (!agreementIds) {
        window.$message.warning('请选择协议书')
    } else {
        addLoaing.value = true
        const { error, code, msg } = await settleApi.addOrUpdateAgree({
            projectId: projectId.value,
            type:searchForm1.value.type,
            areaId:searchForm1.value.areaId,
            stage:stage,
            stageId:stageId,
            agreementIds:agreementIds,
            id:editId.value,
        })
        addLoaing.value = false
        if (!error && code === 200) {
            window.$message.success(msg)
            getTableData()
            rowModal.value = false
        
        } 
    }
 
}

//关闭弹窗
const rowModalClose = () => {
    rowModal.value = false
    formModel.value = {}
}


const editingModal = ref(false)
const tableColumn2 = [
    { key: 'number', name: '期号' },
    { key: 'startDate', name: '开始日期' },
    { key: 'endDate', name: '结束日期' },
    { key: 'printDate', name: '报表打印日期' },
    { key: 'remark', name: '备注' },
    { key: 'action', name: '操作', width: '90', align: 'center' },
]
const tableData2 = ref([

])
const getTableData2 = async () => {
    tableLoading.value = true
    const { error, code, data } = await settleApi.getPage({
        projectId: projectId.value,
        type:searchForm.value.type,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData2.value = getArrValue(data)
      
    } else {
        tableData2.value = []
     
    }
}
//获取期数
const numberOptions = ref([])
const jqnumber = ref('')//计量期
const changType = async (val)=>{
    jqnumber.value = ''
    const { error, code, data } = await settleApi.getPage({
        projectId: projectId.value,
        type:val,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        numberOptions.value = getArrValue(data)
      
    } else {
        numberOptions.value = []
     
    }
    getTableData1()
}
//编辑结算周期
const editingClick = () => {
    if (searchForm.value.type) {
        editingModal.value = true
        getTableData2()
    } else {
        window.$message.warning('请选择补偿类型')
    }
 
}
//添加
const addInRow = ()=>{
    tableData2.value.push({})
}

const editingModalSave = async () => {
    tableData2.value.forEach((ele)=>{
        ele.type = searchForm.value.type
        ele.projectId = projectId.value
    })
    if (tableData2.value.length > 0) {
        const { error, code, data, msg } = await settleApi.addOrUpdate({
            list: tableData2.value,
        })
        if (!error && code === 200) {
            window.$message.success(msg)
            editingModal.value = false
        } 
    } else {
        window.$message.warning('请先填数据')
    }
  
      

}
//时间限制
const checkTime = (row) =>{
      if (row.startDate && row.endDate) {
        const startTime = new Date( row.startDate)
        const endTime = new Date( row.endDate)
        if (endTime < startTime) {
          window.$message.error('结束时间不能早于开始时间')
          // 清空结束时间
          row.endDate = ''
        }
      }
    }
  
//删除结算周期
const delInLoad = ref(false)
const delInRow = async (row, index)=>{
    if (!row?.id) {
        tableData2.value.splice(index, 1)
    } else {
        delInLoad.value = true 
        const { error, code, data, msg } = await settleApi.delete({
            id: row.id,
        })
        delInLoad.value = false
        if (!error && code === 200) {
        window.$message.success(msg)
            tableData2.value.splice(index, 1)
        } 
    }
    
}
const editingModalClose = () => {
    editingModal.value = false
}


//销毁
onUnmounted(() => {
    if (splitvar.value) {
        splitvar.value.destroy()
    }
})
</script>

<style lang="scss" scoped>
@import "~src/styles/settle/index.scoped.scss";
</style>

<style lang="scss">
@import "~src/styles/settle/index.scss";
</style>
