<template>
    <div class="default-main">
        <div>
            <TableHeader :showTimeAll="false" showExport ref="TableHeaderRef">
                <template #select>
                    <el-form-item label="用户类型">
                        <el-select
                            v-model.trim="tableStore.table.params.userType"
                            clearable
                            placeholder="请选择用户类型"
                        >
                            <el-option v-for="item in uesrList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </template>
                <template #operation>
                    <el-button icon="el-icon-Plus" type="primary" @click="add">新增</el-button>
                </template>
            </TableHeader>
            <Table ref="tableRef" />
            <el-dialog draggable v-model="dialogVisible" :title="title" width="600" :before-close="handleClose">
                <el-form ref="ruleFormRef" :model="form" label-width="170px" :disabled="disabled" :rules="rules">
                    <el-form-item label="用户类型：" prop="userType">
                        <el-select v-model="form.userType" clearable placeholder="请选择用户类型" @change="useChange">
                            <el-option v-for="item in uesrList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用户名称：" prop="userName">
                        <el-input
                            v-model.trim="form.userName"
                            clearable
                            placeholder="请输入用户名称"
                            maxlength="32"
                            show-word-limit
                        />
                    </el-form-item>

                    <el-form-item label="电压等级：" prop="voltage">
                        <el-select v-model="form.voltage" clearable collapse-tags placeholder="请选择电压等级">
                            <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>

                    <el-form-item
                        :label="userShow == 'Power_Station_Users' ? '拟接入容量(MVA)：' : '用户协议容量(MVA)：'"
                        prop="protocolCapacity"
                    >
                        <!-- <el-input v-model="form.protocolCapacity" clearable placeholder="请输入用户协议容量" /> -->
                        <el-input-number
                            style="width: 100%"
                            v-model="form.protocolCapacity"
                            :min="0"
                            :max="10000000"
                            placeholder="请输入用容量"
                        />
                    </el-form-item>

                    <el-form-item label="区域" prop="regionList">
                        <!-- <el-cascader v-model="form.regionList" style="width: 100%" :props="props" :options="areaList" /> -->
                        <el-cascader v-model="form.regionList" :props="props" :options="areaList"  style="width: 100%"  placeholder="请选择区域" />
                    </el-form-item>
                 
                    <el-form-item label="详细地址：" prop="area">
                        <el-input
                            clearable
                            v-model="form.area"
                            :autosize="{ minRows: 2, maxRows: 4 }"
                            maxlength="300"
                            show-word-limit
                            type="textarea"
                            placeholder="请输入详细地址"
                        />
                    </el-form-item>
                </el-form>

                <template #footer v-if="!disabled">
                    <div class="dialog-footer">
                        <el-button @click="handleClose">取消</el-button>
                        <el-button type="primary" @click="onSubmit">确定</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <!-- 设备 -->
        <equipment ref="equipmentRef" />
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mainHeight } from '@/utils/layout'
import { useDictData } from '@/stores/dictData'
import equipment from './equipment.vue'
import { addUse, updateUse, removeUse } from '@/api/advance-boot/bearingCapacity'
import { getAreaDept } from '@/api/harmonic-boot/area'

defineOptions({
    name: 'estimate/photovoltaic'
})
const dictData = useDictData()
const levelList = dictData.getBasicData('Dev_Voltage_Stand')
const uesrList = dictData.getBasicData('CARRY_CAPCITY_USER_TYPE')
const dialogVisible = ref(false)
const disabled = ref(false)
const TableHeaderRef = ref()
const equipmentRef = ref()
const title = ref('')
//const areaList: any = dictData.areaSelect()
const areaList = ref([])
const userShow: any = ref('Power_Station_Users')

const form = ref({
    area: '',
    city: '',
    province: '',
    protocolCapacity: 0,
    region: '',
    userName: '',
    userType: '',
    voltage: '',
    regionList: []
})
const rules = {
    userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
    userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
    voltage: [{ required: true, message: '请选择电压等级', trigger: 'change' }],
    protocolCapacity: [{ required: true, message: '请输入容量', trigger: 'change' }],
    regionList: [{ required: true, message: '请选择区域', trigger: 'change' }],
    mav2: [{ required: true, message: '请输入拟接入容量', trigger: 'blur' }],
    area: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}
const props = { label: 'name', value: 'id' }
const ruleFormRef = ref()
const tableStore: any = new TableStore({
    url: '/advance-boot/carrycapacityuser/queyDetailUser',
    // url: '/hzj/carrycapacityuser/queyDetailUser',
    method: 'POST',
    column: [
        // { width: '60', type: 'checkbox' },

        {
            title: '序号',
            width: '80',
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { field: 'userName', title: '用户名称' },
        {
            field: 'userType',
            title: '用户类型',
            formatter: (row: any) => {
                return uesrList.filter(item => item.id == row.cellValue)[0].name
            }
        },

        // { field: 'area', title: '所属区域' },
        {
            field: 'voltage',
            title: '电压等级(V)',
            formatter: (row: any) => {
                return levelList.filter(item => item.id == row.cellValue)[0].name
            }
        },
        {
            field: 'protocolCapacity',
            title: '用户协议容量(MVA)',
            formatter: (row: any) => {
                return uesrList.filter(item => item.id == row.row.userType)[0].code != 'Power_Station_Users'
                    ? row.cellValue
                    : '/'
            }
        },
        {
            field: 'protocolCapacity',
            title: '拟接入容量(MVA)',
            formatter: (row: any) => {
                return uesrList.filter(item => item.id == row.row.userType)[0].code == 'Power_Station_Users'
                    ? row.cellValue
                    : '/'
            }
        },
        { field: 'area', title: '详细地址' },
        { field: 'createBy', title: '创建者' },
        { field: 'createTime', title: '创建日期' },
        {
            title: '操作',
            width: '180',
            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    title: '设备 ',
                    type: 'primary',
                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    click: row => {
                        equipmentRef.value.open(row)
                    }
                },
                {
                    name: 'edit',
                    title: '查看',
                    type: 'primary',

                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    click: row => {
                        disabled.value = true
                        dialogVisible.value = true
                        dialogVisible.value = true
                        title.value = '查看承载能力待评估用户'
                        form.value = JSON.parse(JSON.stringify(row))
                        form.value.regionList = [form.value.province, form.value.city, form.value.region]
                        userShow.value = uesrList.filter(item => item.id == row.userType)[0].code
                    }
                },
                {
                    name: 'edit',
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    click: async row => {
                        disabled.value = false
                        dialogVisible.value = true
                        await nextTick
                        title.value = '编辑承载能力待评估用户'

                        form.value = JSON.parse(JSON.stringify(row))
                        form.value.regionList = [form.value.province, form.value.city, form.value.region]
                        userShow.value = uesrList.filter(item => item.id == row.userType)[0].code
                    }
                },
                {
                    name: 'del',
                    text: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除？'
                    },
                    click: row => {
                        removeUse({ userIds: row.userId }).then(res => {
                            ElMessage.success('删除成功')
                            tableStore.index()
                        })
                    }
                }
            ]
        }
    ],

    loadCallback: () => {
        console.log(tableStore.table.data)
    }
})

tableStore.table.params.userType = ''

provide('tableStore', tableStore)
onMounted(() => {
    tableStore.index()


})
const useChange = (e: string) => {
    userShow.value = uesrList.filter(item => item.id == e)[0].code
}
// 新增
const add = async () => {
    disabled.value = false
    title.value = '新增承载能力待评估用户'

    await getAreaDept().then(res => {
        areaList.value = JSON.parse(JSON.stringify(res.data))
    })
    dialogVisible.value = true
}
// 保存
const onSubmit = () => {
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            form.value.province = form.value.regionList[0] || ''
            form.value.city = form.value.regionList[1] || ''
            form.value.region = form.value.regionList[2] || ''
            if (title.value == '新增承载能力待评估用户') {
                addUse(form.value).then(res => {
                    ElMessage.success('新增成功!')
                    dialogVisible.value = false
                    tableStore.index()
                    handleClose()
                })
            } else if (title.value == '编辑承载能力待评估用户') {
                updateUse(form.value).then(res => {
                    ElMessage.success('修改成功!')
                    dialogVisible.value = false
                    tableStore.index()
                    handleClose()
                })
            }
        }
    })
}

// 取消
const handleClose = () => {
    form.value = {
        area: '',
        city: '',
        province: '',
        protocolCapacity: 0,
        region: '',
        userName: '',
        userType: '',
        voltage: '',
        regionList: []
    }
    ruleFormRef.value?.resetFields()
    dialogVisible.value = false
}
</script>
