<template>
    <HcCard>
        <template #header>
            <div class="w-64">
                <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>
        <div class="base-region-box">
            <div id="region-01" class="base-region-table">
                <HcTable ref="tableListRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check @selection-change="tableSelectionChange" @row-click="rowView">
                    <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>
            </div>
            <div id="region-02" class="base-region-info">
                <el-scrollbar>
                    <div class="base-region-card">
                        <div class="title">
                            已关联用户信息
                        </div>
                        <div class="content">
                            <el-tag v-for="item in allUserNameArr" :key="item.id">
                                {{ item }}
                            </el-tag>
                        </div>
                    </div>
                    <div class="base-region-card">
                        <div class="title">
                            已分配区域权限
                        </div>
                        <div class="content" style="padding-top: 12px">
                            <HcTreeData v-if="isShowTree" :is-menu="false" show-checkbox :default-checked-keys="defaultCheckedKeys" @change="treecheck" />
                        </div>
                    </div>
                </el-scrollbar>
            </div>
        </div>
        <template #action>
            <HcPages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 新增/编辑 -->
        <HcDialog is-to-body bg-color="white" :show="rowModal" is-table widths="62rem" :title="formModel.id ? '编辑' : '新增'" :loading="submitLoading" @save="rowModalSave" @close="rowModalClose">
            <div class="base-region-dialog">
                <div class="dialog-form">
                    <el-scrollbar>
                        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" size="large">
                            <el-form-item label="编号：" prop="number">
                                <el-input v-model="formModel.number" />
                            </el-form-item>
                            <el-form-item label="名称：" prop="name">
                                <el-input v-model="formModel.name" />
                            </el-form-item>
                            <el-form-item label="备注：" prop="remark">
                                <el-input v-model="formModel.remark" />
                            </el-form-item>
                            <el-form-item label="关联用户" prop="allUser">
                                <HcTasksUser :contract-id="ownerId" :project-id="projectId" ui="w-full" :users="allUserName" @change="tasksUserChange" />
                            </el-form-item>
                        </el-form>
                    </el-scrollbar>
                </div>
                <div class="dialog-action">
                    <div class="title">
                        区域权限授权
                    </div>
                    <div class="data-tree-box">
                        <el-scrollbar>
                            <HcTreeData ref="retreeRef" :is-menu="false" show-checkbox :default-checked-keys="defaultCheckedKeys" @change="treecheck" />
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </HcDialog>
    </HcCard>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import split from 'split.js'
import regionApi from '~api/base/region.js'
import { arrToId, arrToKey, formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import { delMessageV2 } from '~com/message/index.js'

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
//渲染完成
onMounted(()=> {
    setSplitDom()
    getTableData()
    getOwnerIds()
})

// 初始化设置拖动分割线
const splitvar = ref(null)
const setSplitDom = () => {
    try {
        //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
        splitvar.value = split([
            '#region-01',
            '#region-02',
        ], {
            sizes: [50, 50],
        })
    } catch (e) {
        setTimeout(() => {
            setSplitDom()
        }, 500)
    }
}

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

//搜索表单
const searchForm = ref({
    name: null, queryValue: 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: 'number', name: '编号' },
    { key: 'allUser', name: '角色名称' },
    { key: 'remark', name: '备注' },
    { key: 'action', name: '操作', width: '130', align: 'center' },
]
const tableData = ref([
 
])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await regionApi.getPage({
        ...searchForm.value,
        projectId: projectId.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total'] || 0
        if (tableData.value.length > 0) {
            getDetail(tableData.value[0].id)
        } else {
            allUserNameArr.value = []
            defaultCheckedKeys.value = []
            isShowTree.value = false
            setTimeout(() => {
                isShowTree.value = true
            }, 1000)
           

        }
        
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}
//getOwnerId查询当前项目业主方合同段id
const ownerId = ref('')
const getOwnerIds = async ()=>{
    const { error, code, data } = await regionApi.getOwnerId({
        projectId: projectId.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        ownerId.value = data
    } else {
        ownerId.value = ''
    }
}

//多选事件
//多选
const tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}
const rowView = ({ row })=>{
   getDetail(row.id)
}
//弹窗
const rowModal = ref(false)
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}
const allUserName = ref('')
const tasksUserChange = (user) => {
    formModel.value.allUser = arrToKey(user, 'userId', '-')

}

//新增
const addRowClick = () => {
    formModel.value = {}
    rowModal.value = true
    defaultCheckedKeys.value = []
    allUserName.value = ''
}

//编辑
const editRowClick = (row) => {
    // formModel.value = row
    rowModal.value = true
    getDetail(row.id)

}
const allUserNameArr = ref([])
//获取详情
const getDetail = async (id)=>{
    const { error, code, data } = await regionApi.getDetail({
        id,
    })
    if (!error && code === 200) {
        formModel.value = getObjValue(data)
        defaultCheckedKeys.value = data['allAreaId'].split(',') || []
        allUserName.value = arrToKey(data['allUserList'], 'name', '-') || ''
        allUserNameArr.value = allUserName.value .split(',') || []
     
    } else {
        formModel.value = { }
      
    }
 }
//保存
const submitLoading = ref(false)
const rowModalSave = async () => {
    console.log(formModel.value, 'value')
    const res = await formValidate(formRef.value)
    if (res) {
        submitLoading.value = true
        //发起请求
        const form = formModel.value
        form.projectId = projectId.value
        const { error, code, msg } = await regionApi.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 defaultCheckedKeys = ref([])
const retreeRef = ref(null)
const isShowTree = ref(true)
const treecheck = (data)=>{
    const checkedKeys = data.node.checkedKeys
    formModel.value.allAreaId = checkedKeys.join(',')

}
//删除
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 regionApi.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()
        }
 })
}
</script>

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

<style lang="scss">

</style>
