<template>
    <!-- 新增修改弹框 -->
    <div>
        <el-dialog
            width="50%"
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            :before-close="handleClose"
            append-to-body
        >
            <el-form
                label-width="120px"
                :model="addOrEditForm"
                :rules="addOrEditFormRef"
                ref="addOrEditFormRef"
                :disabled="formType == 1"
            >
                <TitleTip :titleText="`公司信息`" />
                <el-form-item label="公司名称：" prop="deptName">
                    <el-input v-model="addOrEditForm.deptName" clearable />
                </el-form-item>
                <el-form-item label="公司简称：" prop="deptAbbreviation">
                    <el-input
                        v-model="addOrEditForm.deptAbbreviation"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="公司概述：" prop="remark">
                    <el-input
                        v-model="addOrEditForm.remark"
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 10 }"
                        clearable
                    />
                </el-form-item>
                <el-form-item
                    label="公司状态："
                    prop="status"
                    v-if="formType == 2"
                >
                    <el-radio-group v-model="addOrEditForm.status">
                        <el-radio label="0"> 启用 </el-radio>
                        <el-radio label="1"> 停用 </el-radio>
                        <el-radio label="2"> 注销 </el-radio>
                    </el-radio-group>
                </el-form-item>
                <TitleTip :titleText="`基础设置`" />
                <el-form-item label="默认密码：" prop="initPassword">
                    <el-input v-model="addOrEditForm.initPassword" clearable />
                </el-form-item>
                <el-form-item label="LOGO设置：" prop="logo">
                    <div class="upload-container" v-if="formType != 1">
                        <el-upload
                            :limit="1"
                            :action="uploadFileUrl"
                            list-type="picture-card"
                            :file-list="addOrEditForm.fileList"
                            :headers="headers"
                            :on-remove="handleRemove"
                            :on-preview="handlePreview"
                            :on-success="handleSuccess"
                            :before-upload="handleBeforeUpload"
                            :show-file-list="true"
                            :on-exceed="handleExceed"
                        >
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <div>
                            1、上传图片文件格式仅支持SVG； <br />
                            2、LOGO图片大小不超过3MB,尺寸100px * 100px； <br />
                            3、收集客户的logo请UI设计完成后添加； <br />
                            4、默认公司LOGO。
                            <a @click="onDefaultLogo()"> &gt;&gt; 恢复默认 </a>
                            <br />
                        </div>
                    </div>
                    <div
                        v-else
                        class="view-logo-box"
                        @click="onViewLogoImg(addOrEditForm.logo)"
                    >
                        <img
                            :src="addOrEditForm.logo"
                            style="
                                display: block;
                                max-width: 100%;
                                max-height: 100%;
                                margin: 0 auto;
                            "
                        />
                    </div>
                </el-form-item>
                <TitleTip :titleText="`默认管理员`" />
                <el-form-item label="姓名：" prop="nickName">
                    <el-input v-model="addOrEditForm.nickName" clearable />
                </el-form-item>
                <el-form-item prop="phonenumber" class="user-phone-number">
                    <template slot="label">
                        <div class="custom-label">
                            <span>手机号码：</span>
                            <span>（登录账号）</span>
                        </div>
                    </template>
                    <el-input v-model="addOrEditForm.phonenumber" clearable />
                </el-form-item>
                <el-form-item label="角色：" prop="roles">
                    <el-input disabled v-model="addOrEditForm.roles" />
                </el-form-item>
                <el-form-item class="handle">
                    <el-button
                        @click="
                            () => {
                                $emit('update:formDialogVisible', false)
                            }
                        "
                    >
                        取消
                    </el-button>
                    <el-button type="primary" @click="onSubmitForm">
                        保存
                    </el-button>
                </el-form-item>
            </el-form>

            <el-dialog
                width="30%"
                :visible.sync="dialogInnerVisible"
                append-to-body
                :before-close="
                    () => {
                        dialogInnerVisible = false
                    }
                "
            >
                <img
                    :src="previewUrl"
                    style="display: block; max-width: 100%; margin: 0 auto"
                />
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script>
import {
    addCompanyAPI,
    getDeptDetailsAPI,
    editCompanyAPI,
} from '@/api/company-manage/index.js'
import { validateNewPassword } from '@/utils/validate'
import { getToken } from '@/utils/auth'
export default {
    props: {
        formType: {
            type: Number,
            default: () => 3,
        },
        detailsId: {
            type: [String, Number],
            default: () => '',
        },
        formDialogVisible: {
            type: Boolean,
            default: () => false,
        },
    },

    data() {
        return {
            uploadFileUrl: process.env.VUE_APP_BASE_API + '/file/upload',
            fileType: ['svg'],
            dialogInnerVisible: false,
            previewUrl: '',
            headers: {
                Authorization: 'Bearer ' + getToken(),
            },
            // 新增或修改接口
            addOrEditForm: {
                deptName: '',
                deptAbbreviation: '',
                remark: '',
                initPassword: '',
                logo: '',
                nickName: '',
                phonenumber: '',
                userName: '',
                orderNum: 200,
                fileList: [],
                status: '',
                roles: '公司管理员',
            },
            addOrEditFormRef: {
                deptName: [
                    {
                        required: true,
                        message: '请输入公司名称',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 30,
                        message: '长度在 1 到 30 个字符',
                        trigger: 'blur',
                    },
                ],
                deptAbbreviation: [
                    {
                        required: true,
                        message: '请输入公司简称',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur',
                    },
                ],
                status: [
                    {
                        required: true,
                        message: '请选择公司状态',
                        trigger: 'change',
                    },
                ],
                remark: [
                    {
                        required: true,
                        message: '请输入公司概述',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 150,
                        message: '长度在 1 到 150 个字符',
                        trigger: 'blur',
                    },
                ],
                initPassword: [
                    {
                        required: true,
                        message: '请输入默认密码',
                        trigger: 'blur',
                    },
                    { validator: validateNewPassword, trigger: 'blur' },
                ],
                logo: [
                    {
                        required: true,
                        message: '请上传logo',
                        trigger: 'blur',
                    },
                ],
                nickName: [
                    {
                        required: true,
                        message: '请输入管理员姓名',
                        trigger: 'blur',
                    },
                    {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur',
                    },
                ],
                phonenumber: [
                    {
                        required: true,
                        message: '请输入手机号码',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur',
                    },
                ],
                roles: [
                    {
                        required: true,
                        message: '请输入角色',
                        trigger: 'blur',
                    },
                ],
            },
        }
    },

    computed: {
        dialogVisible: {
            get() {
                return this.formDialogVisible
            },
        },
        dialogTitle: {
            get() {
                if (this.formType === 1) return '公司详情'
                if (this.formType === 2) return '公司编辑'
                if (this.formType === 3) return '公司注册'
            },
        },
    },
    methods: {
        handleClose() {
            this.$refs.addOrEditFormRef.resetFields()
            this.$emit('update:formDialogVisible', false)
        },
        onSubmitForm() {
            this.$refs.addOrEditFormRef.validate(async (valid) => {
                if (valid) {
                    const {
                        deptName,
                        deptAbbreviation,
                        remark,
                        initPassword,
                        logo,
                        nickName,
                        phonenumber,
                        deptId,
                        parentId,
                        userId,
                        status,
                    } = this.addOrEditForm
                    const params = {
                        deptName,
                        deptAbbreviation,
                        remark,
                        logo,
                        initPassword,
                        orderNum: 200,
                        sysUser: {
                            nickName,
                            phonenumber,
                            userName: phonenumber,
                        },
                    }

                    if (this.formType == 2) {
                        params.deptId = deptId
                        params.status = status
                        params.parentId = parentId
                        params.sysUser.userId = userId
                    }
                    const SEND_FUN =
                        this.formType == 2 ? editCompanyAPI : addCompanyAPI
                    const res = await SEND_FUN(params)
                    if (res.code === 200) {
                        this.$modal.msgSuccess(
                            this.formType === 2 ? '修改成功' : '新增成功',
                        )
                    }
                    this.$emit('update:formDialogVisible', false)
                    this.$emit('updateTableList')
                }
            })
        },

        // 上传之前
        handleBeforeUpload(file) {
            const isSvg = this.fileType.some((e) => file.type.includes(e))
            if (!isSvg) {
                this.$modal.msgError(
                    `文件格式不正确, 请上传${this.fileType.join(
                        '、',
                    )}格式的文件!`,
                )
                return false
            }
            const isLt = file.size / 1024 / 1024 < 3
            if (!isLt) {
                this.$modal.msgError(`LOGO大小不能超过 3 MB`)
                return false
            }
            this.$modal.loading('图片正在上传，请稍候...')
        },
        handleRemove(file) {
            this.addOrEditForm.fileList = this.addOrEditForm.fileList.filter(
                (item) => item.uid !== file.uid,
            )
            this.addOrEditForm.logo = ''
        },
        handlePreview(file) {
            this.dialogInnerVisible = true
            this.previewUrl = file.url
        },

        handleSuccess(res) {
            if (res.code === 200) {
                this.addOrEditForm.logo = res.data.url
            } else {
                this.addOrEditForm.fileList = []
                this.addOrEditForm.logo = ''
            }
            this.$modal.closeLoading()
        },
        onViewLogoImg(url) {
            this.dialogInnerVisible = true
            this.previewUrl = url
        },

        onDefaultLogo() {
            this.addOrEditForm.fileList = [
                {
                    url: 'http://36.33.26.201:17788/statics/2025/01/03/logo_20250103151123A002.svg',
                },
            ]
            this.addOrEditForm.logo =
                'http://36.33.26.201:17788/statics/2025/01/03/logo_20250103151123A002.svg'
        },
        // 文件个数超出
        handleExceed() {
            this.$modal.msgError(`上传的LOGO数量不能超过 1 个`)
        },
    },
    async mounted() {
        if (this.formType === 1 || this.formType === 2) {
            // console.log(this.detailsId, 'detailsId')
            const { data: res } = await getDeptDetailsAPI(this.detailsId)
            const {
                deptName,
                deptAbbreviation,
                remark,
                deptId,
                logo,
                initPassword,
                parentId,
                sysUser,
                status,
            } = res

            const { userName, nickName, userId } = sysUser
            Object.assign(this.addOrEditForm, {
                deptName,
                deptAbbreviation,
                remark,
                deptId,
                userId,
                logo,
                initPassword,
                parentId,
                phonenumber: userName,
                userName,
                nickName,
                status,
                fileList: [{ url: logo }],
            })
        }
        if (this.formType === 3) {
            this.getConfigKey('sys.user.initPassword').then((res) => {
                this.addOrEditForm.initPassword = res.msg
            })
        }
    },
    watch: {
        formDialogVisible: {
            handler(newValue) {
                if (!newValue) {
                    this.$refs.addOrEditFormRef.resetFields()
                }
            },
            deep: true,
        },
    },
}
</script>

<style lang="scss" scoped>
::v-deep .handle .el-form-item__content {
    text-align: right;
}

::v-deep .el-dialog {
    display: flex !important;
    flex-direction: column !important;
    margin: 0 !important;
    position: absolute !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    max-height: 100vh !important;
    .el-dialog__body {
        flex: 1;
        overflow-y: scroll !important;
        .el-table__header-wrapper .el-checkbox {
            display: none !important;
        }
    }
    .dialog-content {
        padding: 20px;
    }
}

.upload-container {
    display: flex;
    align-items: center;

    & div:last-child {
        font-size: 13px;
        padding-left: 20px;
        line-height: 2.2;

        a {
            color: #1890ff;
        }
    }
}

.view-logo-box {
    width: 120px;
    height: 120px;
    cursor: pointer;
}
::v-deep .el-upload {
    width: 120px;
    height: 120px;
}

::v-deep .el-upload--picture-card {
    line-height: 120px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 120px;
    height: 120px;
}
.custom-label {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}

::v-deep .user-phone-number .el-form-item__label {
    display: flex;
    justify-content: flex-end;
}
</style>
