<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-48">
                    <el-select v-model="searchForm.compensationType" block clearable placeholder="请选择补偿性质" size="large">
                        <el-option v-for="item in compensationType" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                    </el-select>
                </div>
                <div class="w-64 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="warning" @click="viewRowClick(row)">
                        查看
                    </el-button>
                    <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" is-table widths="80%" :padding="false"
            :title="formModel.id ? '编辑' : '新增'" :loading="submitLoading" @save="rowModalSave" @close="rowModalClose" 
        >
            <HcCard>
                <template #header>
                    <el-form ref="formRef" inline :model="formModel" :rules="formRules" 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.compensationType" block>
                                <el-option v-for="item in compensationType" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </template>
                <template #extra>
                    <el-button size="large" type="success" hc-btn @click="addChildRowClick">
                        <HcIcon name="add" />
                        <span>新增</span>
                    </el-button>
                </template>
                <HcTable :column="tableColumn1" :datas="tableData1">
                    <template #specificationName="{ row, index }">
                        <el-input v-model="row.specificationName" />
                    </template>
                    <template #unitName="{ row, index }">
                        <el-input v-model="row.unitName" />
                    </template>
                    <template #governmentStand="{ row, index }">
                        <el-input v-model="row.governmentStand" />
                    </template>
                    <template #agreementStand="{ row, index }">
                        <el-input v-model="row.agreementStand" />
                    </template>
                    <template #action="{ row, index }">
                        <el-button size="small" type="danger" @click="delChild(index)">
                            <HcIcon name="delete-bin" />
                            <span>删除</span>
                        </el-button>
                    </template>
                </HcTable>
            </HcCard>
        </HcDialog>

        <!-- 查看 -->
        <HcDialog is-to-body bg-color="white" :footer="false" :show="rowViewModal" is-table widths="80%" :padding="false" title="查看" @close="rowViewModalClose">
            <HcCard>
                <template #header>
                    <el-form inline :model="formModel" size="large" disabled>
                        <el-form-item label="名称：" prop="name">
                            <el-input v-model="formModel.name" />
                        </el-form-item>
                        <el-form-item label="补偿性质：">
                            <el-select v-model="formModel.compensationType" block>
                                <el-option v-for="item in compensationType" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </template>
                <HcTable :column="tableColumn2" :datas="tableData1" />
            </HcCard>
        </HcDialog>
    </HcPageLayout>
</template>

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


onMounted(()=>{
    getTableData()
    getCompensationTypeType()
})

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


//获取补偿性质
const compensationType = ref([])
const getCompensationTypeType = async ()=>{
    const { error, code, data } = await getDictInfo('compensation_type')
    if (!error && code === 200) {
        compensationType.value = getArrValue(data)
        compensationType.value.forEach((ele)=>{
            ele.dictKey = parseInt(ele.dictKey)
        })
       
    } else {
        compensationType.value = []
    }
}
//树节点被点击
const treeNodeTap = ({ node, data }) => {
    searchForm.value.areaId = data.id
    getTableData()
}

//搜索表单
const searchForm = ref({
    compensationType: 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: 'compensationTypeName', name: '补偿类型' },
    { key: 'name', name: '名称' },
    { key: 'action', name: '操作', width: '190', align: 'center' },
]
const tableData = ref([
    { id: 1, key1: 'xxxx', key2: 'xxxx', key3: '65632' },
    { id: 2, key1: 'xxxx', key2: 'xxxx', key3: '65632' },
    { id: 3, key1: 'xxxx', key2: 'xxxx', key3: '65632' },
    { id: 4, key1: 'xxxx', key2: 'xxxx', key3: '65632' },
])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await cropsApi.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 tableColumn1 = [
    { key: 'specificationName', name: '规格名称' },
    { key: 'unitName', name: '单位名称' },
    { key: 'governmentStand', name: '政府补偿标准' },
    { key: 'agreementStand', name: '两方协议补偿标准' },
    { key: 'action', name: '操作', width: '100', align: 'center' },
]
//表格表单数据
const tableColumn2 = [
    { key: 'specificationName', name: '规格名称' },
    { key: 'unitName', name: '单位名称' },
    { key: 'governmentStand', name: '政府补偿标准' },
    { key: 'agreementStand', name: '两方协议补偿标准' },
   
]
const tableData1 = ref([
])

//新增
const addRowClick = () => {
    formModel.value = {}
    tableData1.value = []
    rowModal.value = true
}
//删除
const delChild = (index)=>{
    tableData1.value.splice(index, 1)
}
//编辑
const editRowClick = (row) => {
    getDetail(row.id)
    rowModal.value = true
}
//获取详情
const getDetail = async (id)=>{
    const { error, code, data } = await cropsApi.getDetail({
        id,
    })
    if (!error && code === 200) {
        formModel.value = getObjValue(data)
        tableData1.value = formModel.value.childrenList || []
    
    } else {
        formModel.value = {}
        tableData1.value = []
    }
 }
const submitLoading = ref(false)
//保存
const rowModalSave = async () => {
    const res = await formValidate(formRef.value)
    if (res) {
        submitLoading.value = true
        const form = formModel.value
        form.projectId = projectId.value
        form.areaId = searchForm.value.areaId
        form.childrenList = tableData1.value
        const { error, code, msg } = await cropsApi.addOrUpdate(form)
        //判断状态
        submitLoading.value = false
        if (!error && code === 200) {
            window.$message?.success(msg)
            rowModal.value = false
            getTableData()
            
        } 
    }
}

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

//查看
const rowViewModal = ref(false)
const viewRowClick = (row) => {
    rowViewModal.value = true
    getDetail(row.id)
}
const rowViewModalClose = () => {
    rowViewModal.value = false
}
//新增子
const addChildRowClick = ()=>{
    tableData1.value.push({})
}
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 removeRow = async (id)=>{
    const { error, code } = await cropsApi.remove( id, false)
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    } else {
        window.$message?.error('删除失败')
    }
}
//删除
const delClickRow = (row)=>{
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeRow([row.id])
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
</script>

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