<template>
    <el-dialog :title="title" :visible.sync="visible" width="450px" :before-close="onClose">
        <el-form :model="queryForm" ref="setSecret" :rules="rules">
            <el-form-item label="企微ID" prop="originCorpId">
                <el-input v-model.number="queryForm.originCorpId" placeholder="请输入企微ID" clearable size="small" />
            </el-form-item>
            <el-form-item label="应用类型" prop="applicationType">
                <el-select v-model="queryForm.applicationType" placeholder="请选择应用类型" size="small" filterable clearable style="width: 100%;">
                    <el-option v-for="item in applicationTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="客户密钥" v-if="queryForm.applicationType !== 'PROVIDER'" prop="externalUserSecret">
                <el-input v-model="queryForm.externalUserSecret" placeholder="请输入客户密钥" clearable size="small" />
            </el-form-item>
            <!-- <el-form-item label="书城应用ID" prop="bookAgentId">
                <el-input v-model.number="queryForm.bookAgentId" placeholder="请输入书城应用ID" clearable size="small" />
            </el-form-item> -->
            <el-form-item label="用户分组" prop="sysUserGroupIds">
                <el-select v-model="queryForm.sysUserGroupIds" placeholder="请选择" size="small" multiple filterable clearable style="width: 100%;">
                    <el-option v-for="item in groupsOptions" :key="item.id" :label="item.groupName" :value="item.id" />
                </el-select>
            </el-form-item>
            <div>
                <el-form :model="item" :rules="rulesBookCityType" ref="bookCityType" label-width="80px" label-position="top"
                    v-for="(item, index) in queryPlatformBookCity" :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>
            </div>
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="queryForm.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" @click="onSubmit()">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import { refreshCorp } from "@/api/accounts/corpWeChat";
import { getBookPlatInfoAll } from "@/api/accounts/bookCity";
import { getGroupAll } from "@/api/system/group";
export default {
    name: 'setSecret',
    data() {
        return {
            title: '配置通讯录',
            rules: {
                originCorpId: [
                    { required: true, message: '请输入企微ID', trigger: 'blur' }
                ],
                applicationType: [
                    { required: true, message: '请选择应用类型', trigger: 'blur' }
                ],
                externalUserSecret: [
                    { required: true, message: '请输入客户密钥', trigger: 'blur' }
                ],
            },
            queryForm: {

            },
            queryPlatformBookCity: [],
            rulesBookCityType: {
                bookCityId: [
                    { required: true, message: '请选择书城', trigger: 'change' }
                ],
                bookAgentId: [
                    { required: true, message: '请输入书城应用ID', trigger: 'change' }
                ]
            },
            bookCity: [],
            bookCityCS: [],
            groupsOptions: []
        }
    },
    props: {
        /* 编辑器的内容 */
        value: {
            type: Object,
            default: {},
        },
        visible: {
            type: Boolean,
            default: false
        },
        applicationTypeList: {
            type: Array,
            default: []
        }
    },
    watch: {
        visible: {
            handler(val) {
                console.log('11111-->', val)
            },
            immediate: true,
        },
        value: {
            handler(val) {
                let { bookAgentIdMap, ...data } = val
                this.queryForm = data
                this.queryPlatformBookCity = bookAgentIdMap
            },
            immediate: true,
        },
        queryPlatformBookCity: {
            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.queryPlatformBookCity))
            oldData.push({
                bookCityId: null,
                bookAgentId: null
            })
            this.queryPlatformBookCity = oldData
        },
        /** 删除用户 */
        removeResource(index) {
            this.queryPlatformBookCity.splice(index, 1)
        },
        getAllData() {
            // 获取所有书城
            getBookPlatInfoAll().then(res => {
                this.bookCity = res.data
                this.bookCityCS = res.data
            })
            // 获取用户分组列表
            getGroupAll().then(res => {
                this.groupsOptions = res.data;
            });
        },
        onClose() {
            this.$emit("close");
        },
        stateHandle(ref) {
            return new Promise((resolve) => {
                ref.validate(valid => resolve(valid))
            })
        },
        onSubmit() {
            this.$refs['setSecret'].validate(async (valid) => {
                if (valid) {
                    let isOk = true
                    if (this.$refs['bookCityType']) {
                        let state = this.$refs['bookCityType'].map(async item => {
                            return await this.stateHandle(item)
                        })
                        let okList = await Promise.all(state)
                        if (okList.every(item => item)) {
                            isOk = true
                        } else {
                            isOk = false
                        }
                    }
                    if (isOk) {
                        let bookAgentIdMap = {}
                        this.queryPlatformBookCity.forEach(item => {
                            bookAgentIdMap[item.bookCityId] = item.bookAgentId
                        })
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });
                        refreshCorp({ ...this.queryForm, bookAgentIdMap }).then(res => {
                            const h = this.$createElement;
                            this.$msgbox({
                                customClass: 'boxsss',
                                title: '配置成功',
                                closeOnPressEscape: false,
                                closeOnClickModal: false,
                                closeOnHashChange: false,
                                showClose: false,
                                message: h('div', null, [
                                    h('div', { style: { 'overflow': 'hidden' } }, `URL: ${res.data.externalUserCallbackUrl}`),
                                    h('div', null, `AESKey: ${res.data.aesKey}`),
                                    h('div', null, `Token: ${res.data.token}`),
                                ]),
                                confirmButtonText: '确定'
                            }).then(action => {
                                this.$emit("change");
                                loading.close()
                            });

                        }).catch(() => loading.close())
                    }
                }
            })
        }
    }
}
</script>
<style>
.boxsss {
    width: 600px !important;
}
</style>