<template>
    <HcPageLayout>
        <template #left>
            <div class="hc-layout-tree-box">
                <el-scrollbar>
                    <HcTreeData @nodeTap="treeNodeTap" />
                </el-scrollbar>
            </div>
        </template>
        <HcCard>
            <template #header>
                <div class="w-36">
                    <el-select v-model="searchForm.landNature" block clearable placeholder="请选择土地性质" size="large">
                        <el-option v-for="item in natureType" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                    </el-select>
                </div>
                <div class="w-52 ml-2">
                    <el-input v-model="searchForm.name" 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">
                    <HcIcon name="add" />
                    <span>新增</span>
                </el-button>
                <el-button size="large" type="danger" hc-btn :disabled="tableCheckedKeys.length < 1" @click="batchClick">
                    <HcIcon name="delete-bin" />
                    <span>删除</span>
                </el-button>
            </template>
            <HcTable ref="tableListRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check @selection-change="tableSelectionChange">
                <template #action="{ row, index }">
                    <el-button size="small" type="primary" @click="editRowClick(row)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="delClickRow(row)">
                        删除
                    </el-button>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </HcCard>
        <!-- 新增/编辑 -->
        <HcDialog is-to-body bg-color="white" :show="rowModal" :title="formModel.id ? '编辑' : '新增'" widths="30rem" :loading="submitLoading" @save="rowModalSave" @close="rowModalClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" size="large">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="formModel.name" />
                </el-form-item>
                <el-form-item label="土地性质：">
                    <el-select v-model="formModel.landNature" block>
                        <el-option v-for="item in natureType" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                    </el-select>
                </el-form-item>
                <el-form-item label="政府补偿标准：" prop="governmentStand">
                    <el-input v-model="formModel.governmentStand" />
                </el-form-item>
                <el-form-item label="两方协议补偿标准：" prop="agreementStand">
                    <el-input v-model="formModel.agreementStand" />
                </el-form-item>
            </el-form>
        </HcDialog>
    </HcPageLayout>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import landApi from '~api/base/land.js'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import { getDictInfo } from '~api/other'
import { delMessageV2 } from '~com/message/index.js'


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

onMounted(()=>{
    getTableData()
    getNatureType()
})
//获取土地性质
const natureType = ref([])
const getNatureType = async ()=>{
    const { error, code, data } = await getDictInfo('land_nature')
    if (!error && code === 200) {
        natureType.value = getArrValue(data)
        natureType.value.forEach((ele)=>{
            ele.dictKey = parseInt(ele.dictKey)
        })
       
    } else {
        natureType.value = []
    }
}

//树节点被点击
const treeNodeTap = ({ node, data }) => {
    searchForm.value.areaId = data.id
    getTableData()
}

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

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//获取数据
const tableLoading = ref(false)
const tableColumn = [
    { key: 'name', name: '名称' },
    { key: 'governmentStand', name: '政府补偿标准' },
    { key: 'agreementStand', name: '两方协议补偿标准' },
    { key: 'action', name: '操作', width: '130', align: 'center' },
]
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await landApi.getPage({
        ...searchForm.value,
        projectId: projectId.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total'] || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//弹窗
const rowModal = ref(false)
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}

//新增
const addRowClick = () => {
    formModel.value = {}
    rowModal.value = true
}

//编辑
const editRowClick = (row) => {
    formModel.value = row
    rowModal.value = true
}
const submitLoading = ref(false)
//保存
const rowModalSave = async () => {
    console.log( formModel.value, ' formModel.value')
    const res = await formValidate(formRef.value)
    if (res) {
        submitLoading.value = true
        const form = formModel.value
        form.projectId = projectId.value
        form.areaId = searchForm.value.areaId
        const { error, code, msg } = await landApi.addOrUpdate(form)
        //判断状态
        submitLoading.value = false
        if (!error && code === 200) {
            window.$message?.success(msg)
            rowModal.value = false
            getTableData()
            
        } 
    }

}
//删除
const delClickRow = (row)=>{
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow([row.id])
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
const removeRow = async (id)=>{
    const { error, code } = await landApi.remove( id, false)
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message?.error('删除失败')
    }
}
const batchClick = ()=>{
    const rows = tableCheckedKeys.value
    const ids = arrToId(rows).split(',')
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow(ids)
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
//关闭弹窗
const rowModalClose = () => {
    rowModal.value = false
    formModel.value = {}
}
</script>

<style lang="scss" scoped>
.hc-layout-tree-box {
    position: relative;
    height: 100%;
    padding: 18px;
}
</style>
