<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>
            <el-col :span="1.5">
                <div style="padding-top: 9px;font-size: 12px;margin-left: 5px">服务商（点击授权）:</div>
            </el-col>
            <el-col :span="1.5" v-for="item in providerList" :key="item.id">
                <el-button size="mini" @click="getCode(item.id)">{{ item.providerName }}</el-button>
            </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="200" fixed="left"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <div>{{scope.row.corpName}}</div>
                    <div>{{scope.row.originCorpId}}</div>
                </template>
            </el-table-column>
            <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="135" />
            <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="300" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <div class="table-row">回调地址：<a style="color: #1890ff;" v-if="scope.row.agentCallbackUrl" @click="copy(scope.row.externalUserCallbackUrl)">{{scope.row.agentCallbackUrl}}</a><span v-else>--</span></div>
                    <div class="table-row">Token：<a style="color: #1890ff;" v-if="scope.row.token" @click="copy(scope.row.externalUserToken)">{{scope.row.token}}</a><span v-else>--</span></div>
                    <div class="table-row">AESKey：<a style="color: #1890ff;" v-if="scope.row.encodingAesKey" @click="copy(scope.row.encodingAesKey)">{{scope.row.encodingAesKey}}</a><span v-else>--</span></div>
                </template>
            </el-table-column>
            <el-table-column label="授权时间" prop="createTime" width="135" :show-overflow-tooltip="true" />
            <el-table-column label="备注" prop="remark" width="250" :show-overflow-tooltip="true" />
            <el-table-column label="操作" width="200" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <div v-if="scope.row.authStatus === 1" class="czCell">
                        <el-button size="mini" type="text" icon="el-icon-edit"
                            @click="handleRefresh(scope.row)">修改</el-button>
                        <!-- <el-button size="mini" type="text" icon="el-icon-setting"
                            @click="setSecretHandle(scope.row)">配置密钥</el-button>
                        <el-button size="mini" v-if="scope.row.corpId" type="text" icon="el-icon-setting"
                            @click="setSessionHandle(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>
                    </div>
                </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" />
        <set-session v-if="sessionVisible" :visible="sessionVisible" :msgAuditSecret="msgAuditSecret" :corpId="corpId"
            @close="msgAuditSecret = {}; corpId = null; sessionVisible = false" @change="sessionChange()" />

        <modal-corp :visible="corpVisible" :modifyData="corpData" :modalTitle="corpTitle" @onClose="corpVisible = false"
            @onChange="corpVisible = false; getList()" />

        <el-dialog title="扫码授权" :visible.sync="codeVisible" width="240px" :before-close="handleCodeClose">
            <canvas ref="qrcodeCanvas"></canvas>
        </el-dialog>
    </div>
</template>

<script>
import { getProviderAuth, getCorpList, getProviderList, putSyncAllCorpUser } from "@/api/accounts/corpWeChat";
import setSecret from './setSecret.vue'
import mailList from './mailList.vue'
import setSession from './setSession.vue'
import ModalCorp from './modalCorp.vue'
import QRCode from 'qrcode';
export default {
    name: 'corp',
    components: { setSecret, mailList, setSession, ModalCorp },
    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' }],
            msgAuditSecret: null,
            sessionVisible: false,

            corpVisible: false,
            corpData: null,
            corpTitle: '新增企业',
            providerList: [],
            codeVisible: false,
        }
    },
    mounted() {
        this.$nextTick(() => {
            window.addEventListener('storage', this.listener)
        })
    },
    beforeDestroy() { // 在组件生命周期结束的时候销毁。
        window.removeEventListener('storage', this.listener, false)
    },
    created() {
        getProviderList().then(res => {
            this.providerList = res.data
        })
        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: {
        getCode(id) {
            getProviderAuth({ providerId: id }).then(res => {
                this.codeVisible = true
                this.$nextTick(() => {
                    const canvas = this.$refs.qrcodeCanvas;
                    QRCode.toCanvas(canvas, res.data, { width: 200 }, function (error) {
                        if (error) console.error('------->', error);
                        console.log('QR code generated successfully!');
                    });
                })
            })
        },
        handleCodeClose() {
            this.codeVisible = false
        },
        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)
            //     }
            // })
            this.corpVisible = true
            this.corpData = null
            this.corpTitle = '新增企业'
        },
        /** 刷新企微信息 */
        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())
            const { originCorpId, corpId, corpFullName, corpName, bookAgentIdMap, bookAgentId, msgAuditSecret, msgAuditSeq, openAppId, openAppName, remark } = row
            this.corpVisible = true
            
            this.corpData = { 
                originCorpId, 
                corpId, 
                corpFullName, 
                corpName,
                bookAgentIdMap: [],
                bookAgentId,
                msgAuditSecret,
                msgAuditSeq,
                openAppId,
                openAppName,
                remark
            }
            if (bookAgentIdMap && Object.keys(bookAgentIdMap).length > 0) {
                this.corpData.bookAgentIdMap = Object.keys(bookAgentIdMap).map(key => {
                    return {
                        bookCityId: key,
                        bookAgentId: bookAgentIdMap[key]
                    }
                })
            }
            this.corpTitle = '修改企业'
        },
        /** 配置密钥 */
        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 = {}
        },
        /** 配置会话存档 */
        setSessionHandle(row) {
            this.corpId = row.corpId
            this.msgAuditSecret = row.msgAuditSecret
            this.sessionVisible = true
        },
        sessionChange() {
            this.msgAuditSecret = {};
            this.corpId = null;
            this.sessionVisible = false;
            this.getList()
        }
    }
}
</script>

<style scoped lang="scss">
.czCell {
    display: flex;
    gap: 0px 5px;
    flex-wrap: wrap;

    >button {
        padding: 0;
        margin-left: 0;
    }
}
.table-row {
    display: flex;
    
    a {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: inline-block;
        flex: 1;
    }
}
</style>