<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" :title="title" style="max-width: 750px">
        <el-scrollbar>
            <el-form :inline="false" :model="form" label-width="120px" :rules="rules" ref="formRef">
                <el-tabs tab-position="left" style="height: 100%" :before-leave="checkUserId" v-model="tab">
                    <el-tab-pane label="基本信息" name="user">
                        <el-form-item label="用户名" prop="userName" >
                            <el-input v-model="form.userName" placeholder="请输入用户名" clearable />
                        </el-form-item>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="重点用户">
                                    <el-select v-model="form.keyUser">
                                        <el-option label="重要" value="1" />
                                        <el-option label="不重要" value="0" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属行业" prop="industry">
                                    <el-input v-model="form.industry" placeholder="请输入所属行业" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="所在地区" prop="addr">
                            <area-cascard v-model="form.addr" @change="reValueAddr" ref="areaRef" placeholder="请选择所在地区"   clearable/>
                        </el-form-item>
                        <el-form-item label="详细地址">
                            <el-input v-model="form.addrDetail" placeholder="请输入详细地址" clearable/>
                        </el-form-item>
                        <el-form-item label="联系方式">
                            <el-input v-model="form.concact" placeholder="请输入联系方式" clearable/>
                        </el-form-item>
                        <el-form-item label="用户描述">
                            <el-input v-model="form.remark" :rows="2" type="textarea" placeholder="请输入描述" clearable/>
                        </el-form-item>
                        <el-form-item label="企业照片">
                            <div>
                                <el-image
                                    style="width: 200px; height: 200px"
                                    :src="userLogo.url"
                                    :preview-src-list="[userLogo.url]"
                                    v-if="userLogo.url"
                                ></el-image>
                                <el-upload
                                    action=""
                                    :show-file-list="false"
                                    :auto-upload="false"
                                    accept=".png,.jpg"
                                    :on-change="chooseImage"
                                >
                                    <el-button type="primary">上传图片</el-button>
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-tab-pane>

                    <el-tab-pane label="进线" name="incomingLine">
                        <IncomingTable ref="incomingTable"></IncomingTable>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import TableStore from '@/utils/tableStore' // 若不是列表页面弹框可删除
import AreaCascard from '@/components/form/areaCascard/index.vue'
import { uploadFile, deleteFile } from '@/api/system-boot/file'
import { addSgUser, updateSgUser } from '@/api/advance-boot/sgGroven/sgUser'
import IncomingTable from './IncomingTable.vue'
import { getFileUrl } from '@/api/system-boot/file'

const dialogVisible = ref(false)
const title = ref('')
const tableStore = inject('tableStore') as TableStore
const areaRef = ref()
const formRef = ref()
const tab = ref('user')

//进线表格子组件
const incomingTable = ref()

const userLogo = reactive({
    url: '',
    name: ''
})

const dialogVisibleLogo = ref(false)
// 注意不要和表单ref的命名冲突
const form = reactive<anyObj>({
    id: '',
    userName: '',
    keyUser: '1',
    industry: '',
    addr: [],
    addrStrOption: '',
    addrDetail: '',
    concact: '',
    remark: '',
    userLogo: ''
})

//form表单校验规则
const rules = {
    userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    industry: [{ required: true, message: '所属行业不能为空', trigger: 'blur' }],
    addr: [{ required: true, message: '所在地区不能为空', trigger: 'change' }]
}
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const open = (text: string, data?: anyObj) => {
    tab.value = 'user'
    title.value = text
    //默认选中第一个tab
    dialogVisible.value = true
    if (data) {
        // 表单赋值
        for (let key in form) {
            form[key] = data[key]
        }
        form.addr = data.addr.split('/')
        form.keyUser = String(data.keyUser)
        if (form.userLogo) {
            getFileUrl({filePath:form.userLogo}).then(res=>{
                 userLogo.url=res.data
            })
            // 图片的name我不知道
        }
        //待子组件渲染完毕
        nextTick(() => {
            incomingTable.value.getTableData(form.id)
        })
    } else {
        resetForm()
        // 在此处恢复默认表单
        for (let key in form) {
            form[key] = ''
        }
        userLogo.url = ''
        form.keyUser = '1'
    }
}

/**
 * 将联级选择的区域数组转为字符串
 */
const reValueAddr = () => {
    form.addrStrOption = form.addr.join('/')
}

/**
 * 选择图片上传
 * @param e
 */
const chooseImage = (e: any) => {
    uploadFile(e.raw, 'sgGovern/').then(res => {
        userLogo.name = res.data.name
        userLogo.url = res.data.url
        form.userLogo = res.data.name
        ElMessage.success('新增成功')
    })
}

/**
 * 删除文件操作,此操作应在提交表单的时候操作，删除的图片可能有多张
 */
const handleRemove = (e: any, userLogo: any) => {
    form.userLogo = ''
    userLogo.value = []
    deleteFile(e.name).then(res => {
        ElMessage.success('删除成功')
    })
}

/**
 * 预览图片
 */
const handlePictureCardPreview = () => {
    dialogVisibleLogo.value = true
}

/**
 * 提交用户表单数据
 */
const submit = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            if (form.id) {
                form.addrStrOption = form.addr.join('/')
                await updateSgUser(form)
                ElMessage.success('更新成功')
                tableStore.index()
                //切到进线处
                dialogVisible.value = false
            } else {
                await addSgUser(form).then(res => {
                    form.id = res.data
                    //查询进线数据，避免一直处于loading状态
                    incomingTable.value.getTableData(form.id)
                    ElMessage.success('保存成功')
                    tableStore.index()
                    //切到进线处
                    tab.value='incomingLine'
                    dialogVisible.value = true
                })
            }

        }
    })
}

/************针对tab切换*************/
const checkUserId = (tab: any, event: any) => {
    if (tab == 'user') {
        return true
    }
    if (form.id) {
        return true
    } else {
        ElMessage.error('请先创建用户基础信息！')
        return false
    }
}

defineExpose({ open })
</script>

<style scoped>
.el-upload-list__item {
    transition: none !important;
}

.el-select {
    min-width: 180px;
}
</style>
