<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
            <el-form-item label="" prop="corpName">
                <el-input v-model="queryParams.corpName" placeholder="企微名称" clearable size="small" style="width: 140px"
                    @keyup.enter.native="getList" />
            </el-form-item>
            <el-form-item label="" prop="originCorpId">
                <el-input v-model="queryParams.originCorpId" placeholder="企微ID" clearable size="small" style="width: 140px"
                    @keyup.enter.native="getList" />
            </el-form-item>
            <el-form-item label="" prop="applicationType">
                <el-select v-model="queryParams.applicationType" placeholder="请选择应用类型" size="small" filterable clearable style="width: 140px;">
                    <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="" prop="authStatus">
                <el-select v-model="queryParams.authStatus" placeholder="授权状态" clearable filterable style="width: 140px"
                    size="small" @keyup.enter.native="handleQuery">
                    <el-option label="成功授权" :value="1" />
                    <el-option label="取消授权" :value="-1" />
                </el-select>
            </el-form-item>
            <el-form-item label="" prop="configStatus">
                <el-select v-model="queryParams.configStatus" placeholder="配置状态" clearable filterable style="width: 140px"
                    size="small" @keyup.enter.native="handleQuery">
                    <el-option label="未配置" value="ING" />
                    <el-option label="配置成功" value="SUCCESS" />
                    <el-option label="配置失败" value="ERROR" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" align="middle">
            <el-col :span="1.5">
                <div class="grid-content">
                    <el-button type="primary" size="mini" @click="warrantHandle">企微授权</el-button>
                </div>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table :data="corpList" v-loading="loading" size="mini">
            <el-table-column label="企微名称" prop="corpName" width="150" align="center" fixed="left"
                :show-overflow-tooltip="true" />
            <el-table-column label="企微头像" prop="corpSquareLogoUrl" align="center" width="150">
                <template slot-scope="scope">
                    <el-image style="height: 23px" :src="scope.row.corpSquareLogoUrl" fit="fit" />
                </template>
            </el-table-column>
            <el-table-column label="企微ID" prop="originCorpId" align="center" width="150" />
            <el-table-column label="应用类型" prop="applicationType" align="center" width="150">
                <template slot-scope="scope">{{ scope.row.applicationType | filterApplicationType }}</template>
            </el-table-column>
            <el-table-column label="用户规模" prop="corpUserMax" align="center" width="100" />
            <el-table-column label="授权方企业类型" prop="corpType" align="center" width="150">
                <template slot-scope="scope">{{ scope.row.corpType | filterCorpType }}</template>
            </el-table-column>
            <el-table-column label="认证到期时间" prop="verifiedEndTime" align="center" width="120" />
            <el-table-column label="授权状态" prop="authStatus" align="center" width="120">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.authStatus === 1">成功授权</el-tag>
                    <el-tag type="danger" v-else>取消授权</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="配置状态" prop="configStatus" align="center" width="120">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.configStatus === 'SUCCESS'">配置成功</el-tag>
                    <el-tag type="warning" v-else-if="scope.row.configStatus === 'ING'">未配置</el-tag>
                    <el-tag type="danger" v-else>配置失败</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="回调地址" prop="externalUserCallbackUrl" width="200" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <a style="color: #1890ff;" @click="copy(scope.row.externalUserCallbackUrl)">{{
                        scope.row.externalUserCallbackUrl }}</a>
                </template>
            </el-table-column>
            <el-table-column label="Token" prop="externalUserToken" width="150" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <a style="color: #1890ff;" @click="copy(scope.row.externalUserToken)">{{ scope.row.externalUserToken
                    }}</a>
                </template>
            </el-table-column>
            <el-table-column label="AESKey" prop="externalUserAesKey" width="150" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <a style="color: #1890ff;" @click="copy(scope.row.externalUserAesKey)">{{ scope.row.externalUserAesKey
                    }}</a>
                </template>
            </el-table-column>
            <el-table-column label="授权时间" prop="createTime" width="130" :show-overflow-tooltip="true" />
            <el-table-column label="用户分组" prop="sysUserGroupList" width="150" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <div v-if="scope.row.sysUserGroupList"><span v-for="(item, index) in scope.row.sysUserGroupList"
                            :key="item.id"><i v-if="index > 0">,</i>{{ item.groupName }}</span></div>
                    <div v-else>--</div>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" width="250" :show-overflow-tooltip="true" />
            <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <template v-if="scope.row.authStatus === 1">
                        <el-button size="mini" type="text" icon="el-icon-refresh"
                            @click="handleRefresh(scope.row)">刷新</el-button>
                        <el-button size="mini" type="text" icon="el-icon-refresh"
                            @click="setSecretHandle(scope.row)">配置密钥</el-button>
                        <template v-if="scope.row.configStatus === 'SUCCESS'">
                            <el-dropdown style="margin-left: 7px;">
                                <el-button class="el-dropdown-link" size="mini" type="text">更多<i
                                        class="el-icon-arrow-down el-icon--right"></i></el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item><el-button size="mini" type="text" icon="el-icon-refresh"
                                            @click="handleSync(scope.row)">同步所有</el-button></el-dropdown-item>
                                    <el-dropdown-item><el-button size="mini" type="text" icon="el-icon-tickets"
                                            @click="handleMailList(scope.row)">企微通讯录</el-button></el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <setSecret :value="secretData" :applicationTypeList="applicationTypeList" :visible="setShow" @close="setShow = false; secretData = { bookAgentIdMap: [] }"
            @change="closeSetSecret(); getList()" />
        <mailList :corpId="corpId" :visible="mailShow" @close="mailShow = false; corpId = null" />
    </div>
</template>

<script>
import { getCorpToAuth, getCorpList, putRefreshCorp, putSyncAllCorpUser } from "@/api/accounts/corpWeChat";
import setSecret from './setSecret.vue'
import mailList from './mailList.vue'
export default {
    name: 'corp',
    components: { setSecret, mailList },
    data() {
        return {
            showSearch: true,
            loading: false,
            queryParams: {
                pageSize: 20,
                pageNum: 1,
                corpName: '',
                originCorpId: '',
                authStatus: 1
            },
            corpList: [],
            total: 0,
            setShow: false,
            secretData: {
                bookAgentIdMap: []
            },
            mailShow: false,
            corpId: null,
            applicationTypeList: [{label: '内部应用', value: 'INTERNAL'}, {label: '自建应用', value: 'SELF_BUILT'}, {label: '服务商代开发应用', value: 'PROVIDER'}]
        }
    },
    mounted() {
        this.$nextTick(() => {
            window.addEventListener('storage', this.listener)
        })
    },
    beforeDestroy() { // 在组件生命周期结束的时候销毁。
        window.removeEventListener('storage', this.listener, false)
    },
    created() {
        this.getList()
    },
    filters: {
        filterCorpType(val) {
            if (val) {
                return { verified: '认证号', unverified: '注册号' }[val]
            }
            return '-1'
        },
        filterApplicationType(val) {
            if (val) {
                return {INTERNAL: '内部应用', SELF_BUILT: '自建应用', PROVIDER: '服务商代开发应用'}[val] || '-1';
            }
            return '-1'
        }
    },
    methods: {
        copy(str) {
            let element = document.createElement("textarea");
            element.id = 'myTextarea'
            element.textContent = str
            document.body.append(element);
            (document.getElementById('myTextarea')).select();
            document.execCommand("Copy")
            document.body.removeChild(element);
            this.msgSuccess(`复制成功：${str}`);
        },
        handleSync(row) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            putSyncAllCorpUser(row.corpId).then(res => {
                loading.close()
                this.getList()
            }).catch(() => loading.close())
        },
        handleMailList(row) {
            this.mailShow = true
            this.corpId = row.corpId
        },
        listener(e) {
            if (e.key === 'corpAdMp') {
                if (e.newValue === 'ok') {
                    this.getList()
                    this.msgSuccess("授权成功");
                    localStorage.removeItem('corpAdMp')
                } else {
                    this.$message.error('授权失败');
                    localStorage.removeItem('corpAdMp')
                }
            }
        },
        getList() {
            this.loading = true
            getCorpList(this.queryParams).then(res => {
                this.corpList = res.data.records
                this.total = res.data.total
                this.loading = false
            }).catch(() => this.loading = false)
        },
        /** 重置搜索条件 */
        resetQuery() {
            this.resetForm("queryForm");
            this.getList();
        },
        /** 企微授权 */
        warrantHandle() {
            getCorpToAuth({ redirectUri: encodeURIComponent(process.env.VUE_APP_CORP_URL) }).then(res => {
                if (res.data) {
                    window.open(res.data)
                }
            })
        },
        /** 刷新企微信息 */
        handleRefresh(row) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            putRefreshCorp(row.corpId).then(res => {
                loading.close()
                this.getList()
            }).catch(() => loading.close())
        },
        /** 配置密钥 */
        setSecretHandle(row) {
            this.setShow = true
            this.secretData = {
                corpId: row.corpId,
                originCorpId: row.originCorpId,
                externalUserSecret: row.externalUserSecret,
                bookAgentIdMap: [],
                applicationType: row.applicationType,
                remark: row.remark,
                sysUserGroupIds: row.sysUserGroupIds
            }
            if (row.bookAgentIdMap && Object.keys(row.bookAgentIdMap).length > 0) {
                this.secretData.bookAgentIdMap = Object.keys(row.bookAgentIdMap).map(key => {
                    return {
                        bookCityId: key,
                        bookAgentId: row.bookAgentIdMap[key]
                    }
                })
            }
        },
        /** 关闭配置 */
        closeSetSecret() {
            this.setShow = false
            this.secretData = {}
        }
    }
}
</script>