<template>
    <div>
        <el-dialog :title="modalTitle" :visible.sync="visible" width="600px" :before-close="onClose">
            <el-form :model="queryParams" :rules="rules" ref="queryParamsCorpModify" label-position="top">
                <el-form-item label="企业ID" prop="originCorpId">
                    <el-input v-model="queryParams.originCorpId" :disabled="!!queryParams.corpId" placeholder="请输入企业ID" clearable size="small" />
                </el-form-item>
                <el-form-item label="企业简称" prop="corpName">
                    <el-input v-model="queryParams.corpName" placeholder="请输入企业简称" clearable size="small" />
                </el-form-item>
                <el-form-item label="企业全称" prop="corpFullName">
                    <el-input v-model="queryParams.corpFullName" placeholder="请输入企业全称" clearable size="small" />
                </el-form-item>
                <template v-if="queryParams.corpId">
                    <!-- 修改 -->
                    <el-form-item label="当前在投的书城企微应用ID" prop="bookAgentId">
                        <el-input v-model="queryParams.bookAgentId" placeholder="请输入当前在投的书城企微应用ID" clearable size="small" oninput="value=value.replace(/[^\d]/g,'')" />
                    </el-form-item>
                    <el-form-item label="书城企微应用ID">
                        <el-form :model="item" :rules="rulesBookCityType" ref="bookCityType" label-width="80px" label-position="top"
                            v-for="(item, index) in queryParams.bookAgentIdMap" :key="index">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="书城" prop="bookCityId">
                                        <el-select v-model="item.bookCityId" size="small" placeholder="选择书城" filterable clearable>
                                            <el-option v-for="item in bookCity" :disabled="item.disabled" :key="item.id"
                                                :label="item.platformName" :value="item.platformKey" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="书城应用ID" prop="bookAgentId">
                                        <el-input v-model.number="item.bookAgentId" placeholder="请输入书城应用ID" clearable
                                            size="small" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="2">
                                    <div style="margin-top: 42px">
                                        <el-button @click.prevent="removeResource(index)" type="text" icon="el-icon-delete"
                                            style="color: red; margin-left: 10px"></el-button>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-form>
                        <el-button type="text" icon="el-icon-plus" @click="addResource">新增书城</el-button>
                    </el-form-item>
                    <el-form-item label="会话存档密钥" prop="msgAuditSecret">
                        <el-input v-model="queryParams.msgAuditSecret" placeholder="请输入会话存档密钥" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="会话存档Seq" prop="msgAuditSeq">
                        <el-input v-model="queryParams.msgAuditSeq" placeholder="请输入会话存档Seq" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="开放平台绑定的小程序/公众号名字" prop="openAppName">
                        <el-input v-model="queryParams.openAppName" placeholder="请输入开放平台绑定的小程序/公众号的AppId" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="开放平台绑定的小程序/公众号的AppId" prop="openAppId">
                        <el-input v-model="queryParams.openAppId" placeholder="请输入开放平台绑定的小程序/公众号的AppId" clearable size="small" />
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item label="应用类型" prop="authType">
                        <el-radio-group v-model="queryParams.authType">
                            <el-radio label="SELF_BUILT">自建应用</el-radio>
                            <el-radio label="INTERNAL">内部应用</el-radio>
                            <el-radio label="AUTH_PROVIDER">服务商代开发应用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="应用ID" prop="agentId">
                        <el-input v-model="queryParams.agentId" placeholder="请输入应用ID" clearable size="small" oninput="value=value.replace(/[^\d]/g,'')" />
                    </el-form-item>
                    <el-form-item label="应用密钥" prop="agentSecret">
                        <el-input v-model="queryParams.agentSecret" placeholder="请输入应用密钥" clearable size="small" />
                    </el-form-item>
                    <template v-if="queryParams.authType === 'SELF_BUILT'">
                        <el-form-item label="企微请求代理地址" prop="proxyUrl">
                            <el-input v-model="queryParams.proxyUrl" placeholder="请输入企微请求代理地址" clearable size="small" />
                        </el-form-item>
                        <el-form-item label="备案的域名" prop="domain">
                            <el-input v-model="queryParams.domain" placeholder="请输入备案的域名" clearable size="small" />
                        </el-form-item>
                        <el-form-item label="域名备案查询截图" prop="domainBeianImgUrl">
                            <el-upload
                                class="avatar-uploader"
                                action=""
                                :show-file-list="false"
                                :http-request="handleUpload"
                                :before-upload="beforeUpload"
                                accept="image/jpeg,image/png,image/jpg"
                            >
                                <img v-if="queryParams.domainBeianImgUrl" :src="queryParams.domainBeianImgUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </template>
                </template>
                
                <el-form-item label="企业备注" prop="remark">
                    <el-input v-model="queryParams.remark" placeholder="请输入企业备注" clearable size="small" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="onClose()">取 消</el-button>
                <el-button type="primary" :loading="loading" @click="submit('queryParamsCorpModify')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { addCorpApi, editCorpApi, uploadImageApi } from "@/api/accounts/corpWeChat";
import axios from 'axios';
import { getBookPlatInfoAll } from "@/api/accounts/bookCity";
export default {
    data() {
        return {
            queryParams: {
                corpFullName: null,
                corpName: null,
                originCorpId: null,
                authType: 'SELF_BUILT',
                agentId: null,
                agentSecret: null,
                proxyUrl: null,
                domain: null,
                domainBeianImgUrl: null,
                remark: null
            },
            rulesBookCityType: {
                bookCityId: [
                    { required: true, message: '请选择书城', trigger: 'change' }
                ],
                bookAgentId: [
                    { required: true, message: '请输入书城应用ID', trigger: 'change' }
                ]
            },
            rules: {
                corpFullName: [
                    { required: true, message: '请输入企业全称', trigger: 'blur' }
                ],
                originCorpId: [
                    { required: true, message: '请输入企业ID', trigger: 'blur' }
                ],
                corpName: [
                    { required: true, message: '请输入企业简称', trigger: 'blur' }
                ],
                authType: [
                    { required: true, message: '请选择应用类型', trigger: 'blur' }
                ],
                agentId: [
                    { required: true, message: '请输入应用ID', trigger: 'blur' }
                ],
                agentSecret: [
                    { required: true, message: '请输入应用密钥', trigger: 'blur' }
                ]
            },
            loading: false,
            bookCity: [],
            bookCityCS: [],
        }
    },
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        modifyData: {
            type: Object,
            default: null
        },
        modalTitle: {
            type: String,
            default: '新增企业'
        }
    },
    watch: {
        modifyData: {
            handler(val) {
                if (val && Object.keys(val).length > 0) {
                    this.queryParams = val
                    this.queryParams.bookAgentIdMap = val.bookAgentIdMap || []
                } else {
                    this.queryParams = {
                        corpFullName: null,
                        corpName: null,
                        originCorpId: null,
                        authType: 'SELF_BUILT',
                        agentId: null,
                        agentSecret: null,
                        proxyUrl: null,
                        domain: null,
                        domainBeianImgUrl: null,
                        remark: null
                    }
                }
            },
            immediate: true,
        },
        'queryParams.bookAgentIdMap': {
            handler(val) {
                if (val && val.length > 0) {
                    let data = this.bookCityCS.map(item => {
                        if (val.some(i => i.bookCityId === item.platformKey)) {
                            return { ...item, disabled: true }
                        }
                        return { ...item, disabled: false }
                    })
                    this.bookCity = data
                } else {
                    this.bookCity = this.bookCityCS
                }
            },
            deep: true,
            immediate: false,
        }
    },
    created() {
        this.getAllData()
    },
    methods: {
        /** 新增用户 */
        addResource() {
            let oldData = JSON.parse(JSON.stringify(this.queryParams.bookAgentIdMap))
            oldData.push({
                bookCityId: null,
                bookAgentId: null
            })
            this.queryParams.bookAgentIdMap = oldData
        },
         /** 删除用户 */
        removeResource(index) {
            this.queryParams.bookAgentIdMap.splice(index, 1)
        },
        getAllData() {
            // 获取所有书城
            getBookPlatInfoAll().then(res => {
                this.bookCity = res.data
                this.bookCityCS = res.data
            })
        },
        onClose() {
            this.$emit("onClose");
        },
        submit(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.loading = true
                    let data = null
                    if (this.modifyData && this.modifyData.corpId) {
                        let params = JSON.parse(JSON.stringify(this.queryParams))
                        // 新增应用时，bookAgentIdMap 为空
                        if (params.bookAgentIdMap && params.bookAgentIdMap.length > 0) {
                            
                            let bookAgentIdMap = {}
                            params.bookAgentIdMap.forEach(item => {
                                bookAgentIdMap[item.bookCityId] = item.bookAgentId
                            })
                            params.bookAgentIdMap = bookAgentIdMap
                        }
                        data = await editCorpApi({ ...params, corpId: this.modifyData.corpId }).catch(err => {
                            this.loading = false
                        })
                    } else {
                        data = await addCorpApi(this.queryParams).catch(err => {
                            this.loading = false
                        })
                    }

                    this.loading = false
                    if (data.data) {
                        this.$message({
                            message: (this.modifyData && this.modifyData.corpId) ? '修改成功' : '新增成功',
                            type: 'success'
                        });
                        this.resetForm(formName);
                        this.$emit("onChange");
                    }
                }
            })
        },
        async handleUpload(option) {
            const file = option.file;
            const suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
            try {
                const res = await uploadImageApi({ filePrefix: 'corp_info/corp_icp/', suffix: 'image/' + suffix });
                if (res.code === 200 && res.data) {
                    const data = res.data;
                    const formData = new FormData();
                    
                    for (let key in data) {
                        if (key !== 'host' && key !== 'ossUrl' && key !== 'domain') {
                            formData.append(key, data[key]);
                        }
                    }
                    formData.append('file', file);
                    
                    const uploadUrl = data.ossUrl;
                    
                    const uploadRes = await axios.post(uploadUrl, formData, {
                        headers: { 'Content-Type': 'multipart/form-data' }
                    });
                    // Depending on what is returned by the OSS or common upload
                    if (uploadRes.data.data) {
                        this.queryParams.domainBeianImgUrl = uploadRes.data.data;
                        this.$message.success('上传成功');
                    } else {
                        this.$message.error('上传失败');
                    }
                } else {
                    this.$message.error(res.msg || '获取上传凭证失败');
                }
            } catch (error) {
                console.error(error);
                this.$message.error('上传失败');
            }
        },
        beforeUpload(file) {
            const isImage = file.type.indexOf("image/") !== -1;
            if (!isImage) {
                this.$message.error("文件格式错误，请上传图片类型，如：JPG，PNG后缀的文件。");
            }
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过 10MB!");
            }
            return isImage && isLt10M;
        }

    }
}
</script>

<style scoped>
.avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}
.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>