<template>
    <div class="open-mgmt">
        <Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading" />
        <!-- 列表 -->
        <div class="open-mgmt-left">
            <div class="open-header">
                <span>{{ $t("settings.openList") }}</span>
                <div class="open-action">
                    <!-- <Icon type="md-add" size="18" style="margin-right: 10px" color="rgb(115 115 115)" @click="editOpen(true, true)" /> -->
                    <Icon type="md-add" title="新增" size="18" style="margin-right: 10px" @click="editOpen(true, true)" />
                    <Icon type="md-trash" title="删除" size="18" @click="delOpen" />
                </div>
            </div>
            <div>
                <EmptyData v-if="!openList.length" :top="270"></EmptyData>
                <vuescroll>
                    <div class="open-left-list">
                        <div :class="['open-list', index == nowIndex ? 'list-select' : '']"
                            v-for="(item, index) in openList"
                            :key="index"
                            @click="list(index)"
                        >
                            <span>{{ item.name }}</span>
                        </div>
                    </div>
                </vuescroll>
            </div>
        </div>
        <!-- 信息 -->
        <div class="open-mgmt-right">
            <div class="open-header">
                <span>{{ $t("settings.openInfo") }}</span>
                <div class="open-action" @click="editOpen(true, false)" v-show="!isEdit && Object.keys(this.openMgInfo).length > 0">
                    <div>
                        <Icon type="ios-create" size="18" />
                        <span>{{ $t("settings.edit") }}</span>
                    </div>
                </div>
                <div class="open-action" v-show="isEdit">
                    <div @click="keepMgmt(true)">
                        <Icon type="md-checkmark-circle" size="18" />
                        <span>{{ $t("settings.openKeep") }}</span>
                    </div>
                    <div @click="keepMgmt(false)">
                        <Icon type="md-close-circle" size="18" />
                        <span>{{ $t("settings.unedit") }}</span>
                    </div>
                </div>
            </div>
            <EmptyData v-if="!Object.keys(openMgInfo).length" :top="-100"></EmptyData>
            <div class="open-right-info" v-else>
                <div class="open-info">
                    <vuescroll>
                        <div class="light-iview-form">
                            <!-- <div class="open-mgmt-info"> -->
                            <Form :model="openMgInfo" label-position="top">
                                <div class="open-mgmt-info">
                                    <FormItem :label="$t('settings.openName')">
                                        <Input v-model="openMgInfo.name"
                                            :class="isEdit ? '' : 'open-info-disabled'"
                                            :readonly="isEdit ? false : true"
                                        ></Input>
                                    </FormItem>
                                    <FormItem :label="$t('settings.token')" class="api-token" v-show="!isEdit">
                                        <div class="api-icon">
                                            <!-- 隐藏 -->
                                            <Icon :type="isTokenShow ? 'md-eye' : 'md-eye-off'"
                                                :title="isTokenShow ? '隐藏' : '显示'"
                                                size="18"
                                                style="margin-right: 10px"
                                                color="#40A8F0"
                                                @click="isTokenShow = !isTokenShow"
                                            />
                                            <!-- 刷新 -->
                                            <Icon type="md-refresh"
                                                title="刷新"
                                                v-show="isTokenShow"
                                                size="18"
                                                style="margin-right: 10px"
                                                color="#40A8F0"
                                                @click="refresh"
                                            />
                                            <!-- 复制 -->
                                            <Icon type="ios-copy"
                                                title="复制"
                                                v-show="isTokenShow"
                                                size="18"
                                                color="#40A8F0"
                                                @click="copyToken"
                                            />
                                        </div>
                                        <Input v-model="openMgInfo.token"
                                            type="textarea"
                                            :autosize="{ minRows: 10 }"
                                            class="open-info-disabled"
                                            readonly
                                            v-show="isTokenShow"
                                        ></Input>
                                    </FormItem>
                                    <FormItem :label="$t('settings.des')">
                                        <Input v-model="openMgInfo.descr"
                                            type="textarea"
                                            :autosize="{ minRows: 2 }"
                                            :class="isEdit ? '' : 'open-info-disabled'"
                                            :readonly="isEdit ? false : true"
                                        ></Input>
                                    </FormItem>
                                    <FormItem :label="$t('settings.openStatus')">
                                        <RadioGroup v-model="openMgInfo.status">
                                            <Radio :label="1" :disabled="isEdit ? false : true">
                                                {{ $t("settings.enable") }}
                                            </Radio>
                                            <Radio :label="0" :disabled="isEdit ? false : true">
                                                {{ $t("settings.disable") }}
                                            </Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </div>
                                <p>{{ $t("settings.webhook") }}</p>
                                <div class="open-mgmt-info">
                                    <FormItem :label="$t('settings.domainName')">
                                        <Input v-model="openMgInfo.domain"
                                            :class="isEdit ? '' : 'open-info-disabled'"
                                            :readonly="isEdit ? false : true"
                                        ></Input>
                                    </FormItem>
                                    <FormItem :label="$t('settings.authorization')">
                                        <Input v-model="openMgInfo.webhookToken"
                                            type="textarea"
                                            :autosize="{ minRows: 2 }"
                                            :class="isEdit ? '' : 'open-info-disabled'"
                                            :readonly="isEdit ? false : true"
                                        ></Input>
                                    </FormItem>
                                </div>
                            </Form>
                        </div>
                        <!-- </div> -->
                    </vuescroll>
                </div>
                <div class="open-api">
                    <!-- <div class="open-api"> -->
                    <Tabs value="1">
                        <TabPane :label="$t('settings.apiType1')" name="1">
                            <div class="open-api-table">
                                <Table ref="selection"
                                       :loading="isLoadList"
                                       :columns="apiListCol"
                                       :data="isEdit ? apiListW : apiListSelW"
                                       @on-selection-change="selectionChange1"
                                >
                                    <template slot-scope="{ row }" slot="name">
                                        <span>{{ row.name }}</span>
                                        <Poptip trigger="hover" :content="row.descr" placement="right">
                                            <!-- <Icon type="ios-alert" /> -->
                                            <Icon type="ios-alert-outline" />
                                        </Poptip>
                                    </template>
                                </Table>
                            </div>
                        </TabPane>
                        <TabPane :label="$t('settings.apiType2')" name="2">
                            <div class="open-api-table">
                                <Table ref="selection"
                                       :loading="isLoadList"
                                       :columns="apiListCol"
                                       :data="isEdit ? apiListR : apiListSelR"
                                       @on-selection-change="selectionChange2"
                                >
                                    <template slot-scope="{ row }" slot="name">
                                        <span>{{ row.name }}</span>
                                        <Poptip trigger="hover" :content="row.descr" placement="right">
                                            <Icon type="ios-alert-outline" />
                                        </Poptip>
                                    </template>
                                </Table>
                            </div>
                        </TabPane>
                        <TabPane :label="$t('settings.subNews')" name="3">
                            <div class="open-api-table">
                                <Table ref="selection"
                                       :loading="isLoadList"
                                       :columns="apiListCol"
                                       :data="isEdit ? newsListSel : newsListNow"
                                       @on-selection-change="selectionChange3"
                                >
                                    <template slot-scope="{ row }" slot="name">
                                        <span>{{ row.name }}</span>
                                        <Poptip trigger="hover" :content="row.descr" placement="right">
                                            <Icon type="ios-alert-outline" />
                                        </Poptip>
                                    </template>
                                </Table>
                            </div>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: "OpenMgmt",
    data() {
        return {
            isLoading: false,
            isLoadList: false,
            isTokenShow: false,
            schoolCode: this.$store.state.userInfo.schoolCode,
            openList: [], //开放平台列表
            openMgInfo: {}, //平台信息
            apiType: 1,
            apiListCol: [ //api表头
                /* {
                    type: 'selection',
                    width: 80,
                    align: 'center',
                }, */
                {
                    title: this.$t("settings.apiName"),
                    key: "name",
                    slot: "name",
                },
                {
                    title: this.$t("settings.apiAddress"),
                    key: "url",
                },
                {
                    title: this.$t("settings.apiMethod"),
                    key: "method",
                },
                /* {
                    title: this.$t("settings.des"),
                    key: "descr",
                }, */
            ],
            apiList: [], //api原有列表
            apiListSelR: [], //已有的读取接口
            apiListSelW: [], //已有的写入接口
            newsList: [], //原始通知列表
            newsListNow: [], //已有的通知
            pageTotal: 0,
            pageSizeOpts: [5, 10, 20, 30, 40],
            nowIndex: 0, //当前下标
            isEdit: false, //编辑状态
            isAdd: false, // 编辑/新增
        }
    },
    mounted() {
        this.getOpenList()
    },
    computed: {
        // 读取接口
        apiListR() {
            if (this.apiList && this.openMgInfo && this.openMgInfo.auths) {
                return this.apiList.filter((item) => {
                    item._checked = this.openMgInfo.auths.includes(item.auth)
                    return item.type == "r"
                })
            } else {
                return []
            }
        },
        // 写入接口
        apiListW() {
            if (this.apiList && this.openMgInfo && this.openMgInfo.auths) {
                return this.apiList.filter((item) => {
                    item._checked = this.openMgInfo.auths.includes(item.auth)
                    return item.type == "w"
                })
            } else {
                return []
            }
        },
        // 通知
        newsListSel() {
            if (this.newsList && this.openMgInfo && this.openMgInfo.webhooks) {
                return this.newsList.filter((item) => {
                    item._checked = this.openMgInfo.webhooks.includes(item.auth)
                    return item
                })
            } else {
                return []
            }
        },
    },
    methods: {
        // 获取应用列表
        getOpenList() {
            this.isLoading = true
            let list = []
            let req = { code: this.schoolCode }
            this.$api.openMgmt.getOpenList(req).then(
                (res) => {
                    if (res.apps.length != 0) {
                        list = [...res.apps]
                        // 没有创建时间，暂时倒序
                        list.reverse()
                        this.openList = list
                        this.openMgInfo = this._.cloneDeep(this.openList[this.nowIndex])
                        // this.isLoading = false
                    }
                    this.getApiList()
                    this.getWebhook()
                },
                (err) => {
                    this.$Message.warning(this.$t("settings.openModal1"))
                    /* setTimeout(() => {
                        this.isLoading = false
                    }, 1000) */
                }
            ).finally(() => {
                this.isLoading = false
            })
        },
        // 获取api 列表
        getApiList() {
            this.apiList = []
            let reqs = {}
            this.$api.openMgmt.getApiList(reqs).then(
                (res) => {
                    if (res) {
                        let list = [...res.apis]
                        if (list.length > 0) {
                            // 根据auth 的大小进行排序
                            list.sort((a, b) => {
                                return a.auth - b.auth
                            })
                        }
                        this.apiList = list
                        this.selectApi()
                    }
                },
                (err) => {
                    this.$Message.warning(this.$t("settings.openModal2"))
                    /* setTimeout(() => {
                        this.isLoadList = false
                    }, 1000) */
                }
            )
        },
        // 获取订阅通知
        getWebhook() {
            let reqs = {}
            this.$api.openMgmt.getWebhook(reqs).then((res) => {
                if (res) {
                    let list = res.webhooks
                    list.sort(function (a, b) {
                        return a.auth - b.auth
                    })
                    this.newsList = this._.cloneDeep(list)
                    this.selectNews()
                }
            })
        },
        // 筛选出该应用已有的api
        selectApi() {
            if(Object.keys(this.openMgInfo).length > 0) {
                let schoolApi = this.apiList.filter((item) => {
                    return this.openMgInfo.auths.includes(item.auth)
                })
                this.apiListSelR = schoolApi.filter((item) => {
                    return item.type == "r"
                })
                this.apiListSelW = schoolApi.filter((item) => {
                    return item.type == "w"
                })
            }
            
        },
        // 筛选已有的通知
        selectNews() {
            if(Object.keys(this.openMgInfo).length > 0) {
                this.newsListNow = this.newsList.filter((item) => {
                    return this.openMgInfo.webhooks.includes(item.auth)
                })
            }
        },
        // 编辑、新增
        editOpen(isEdit, isAdd) {
            this.isTokenShow = false
            if (!this.isEdit) {
                this.apiListCol.unshift({
                    type: "selection",
                    width: 40,
                    align: "center",
                })
                this.isEdit = isEdit
                this.isAdd = isAdd
                // 新增
                if (isAdd) {
                    var defaultInfo = {
                        auths: [],
                        // code: this.schoolCode,
                        descr: null,
                        name: this.$t("settings.opName"),
                        // school: this.schoolCode,
                        status: 0,
                        webhooks: [],
                    }
                    this.openList.unshift(defaultInfo)
                    this.openMgInfo = defaultInfo
                    this.nowIndex = 0
                }
            }
        },
        // 删除应用
        delOpen() {
            if (!this.isEdit) {
                var titWord = this.$t("settings.delModal1") + this.openMgInfo.name + this.$t("settings.delModal2")
                this.$Modal.confirm({
                    title: `${titWord}`,
                    onOk: () => {
                        this.isLoading = true
                        let req = {
                            id: this.openMgInfo.id,
                            code: this.schoolCode,
                        }
                        this.$api.openMgmt.delOpen(req).then(
                            (res) => {
                                this.openList.splice(this.nowIndex, 1)
                                if (this.openList.length == this.nowIndex) {
                                    this.nowIndex = 0
                                }
                                if(this.openList.length > 0) {
                                    this.openMgInfo = this._.cloneDeep(this.openList[this.nowIndex])
                                    this.selectApi()
                                    this.selectNews()
                                } else {
                                    this.openMgInfo = {}
                                }
                                this.isTokenShow = false
                                this.$Message.success(this.$t("settings.delModal3"))
                            },
                            (err) => {
                                this.$Message.error(this.$t("settings.delModal4"))
                            }
                        ).finally(()=>{
                            this.isLoading = false
                        })
                    },
                    onCancel: () => {
                        this.$Message.info(this.$t("settings.delModal5"))
                    },
                })
            }
        },
        list(index) {
            if (index != this.nowIndex) {
                this.isTokenShow = false
                if (this.isEdit) {
                    if (this.isAdd) {
                        this.openList.splice(0, 1)
                        index = index - 1
                    }
                    this.isEdit = !this.isEdit
                    this.apiListCol.splice(0, 1)
                }
                this.nowIndex = index
                this.openMgInfo = this._.cloneDeep(this.openList[index])
                this.selectApi()
                this.selectNews()
            }
        },
        // 保存平台信息
        keepMgmt(type) {
            // this.isEdit = type
            if (type) {
                if(!this.openMgInfo.name) {
                    this.$Message.warning("请输入应用名称")
                    return
                }
                this.isLoading = true
                let auths = []
                let arr = this.apiListSelR.concat(this.apiListSelW)
                if (arr.length > 0) {
                    arr.map((item) => {
                        auths.push(item.auth)
                    })
                }
                let webhooks = []
                if (this.newsListNow.length > 0) {
                    this.newsListNow.map((item) => {
                        webhooks.push(item.auth)
                    })
                }
                let req = {
                    code: this.schoolCode,
                    school: this.schoolCode,
                    auths,
                    webhooks
                }
                req = Object.assign(this.openMgInfo, req)
                this.$api.openMgmt.editOpenInfo(req).then(
                    (res) => {
                        if (res) {
                            console.log(res.app)
                            this.openMgInfo = res.app
                            this.refreshToken()
                            this.openList.splice(this.nowIndex, 1, this.openMgInfo)
                            // this.getOpenList()
                            this.selectApi()
                            this.selectNews()
                            this.$Message.success(this.$t("settings.keepModal1"))
                        }
                    },
                    (err) => {
                        this.$Message.warning(this.$t("settings.keepModal2"))
                        // setTimeout(() => {
                        //     this.isLoading = false
                        // }, 1000)
                    }
                ).finally(() => {
                    this.isLoading = false
                })
            } else {
                if(this.openList.length > 1 || !this.isAdd) {
                    this.openList = this.openList.filter((i) => i.id)
                    this.openMgInfo = this._.cloneDeep(this.openList[this.nowIndex])
                    this.selectApi()
                    this.selectNews()
                }
                // 只有现在添加的一个应用
                else {
                    this.openList.splice(0, 1)
                    this.openMgInfo = {}
                    this.apiListSelR = []
                    this.apiListSelW = []
                    this.newsListNow = []
                }
            }
            this.apiListCol.splice(0, 1)
            this.isEdit = false
        },
        // 刷新token
        refresh() {
            if (this.isTokenShow) {
                this.$Modal.confirm({
                    title: this.$t("settings.refreshModal3"),
                    onOk: () => {
                        this.refreshToken()
                    },
                    onCancel: () => {
                        this.$Message.info(this.$t("settings.refreshModal4"))
                    },
                })
            }
        },
        refreshToken() {
            let req = {
                id: this.openMgInfo.id,
                code: this.openMgInfo.school,
            }
            this.$api.openMgmt.getToken(req).then(
                (res) => {
                    if (res) {
                        this.openList[this.nowIndex].token = res.auth_token
                        this.openMgInfo.token = res.auth_token
                        if (!this.isAdd) {
                            this.$Message.success(
                                this.$t("settings.refreshModal1")
                            )
                        }
                    }
                },
                (err) => {
                    this.$Message.warning(this.$t("settings.refreshModal2"))
                    /* setTimeout(() => {
                        this.isLoading = false
                    }, 1000) */
                }
            )
        },
        copyToken() {
            if (this.isTokenShow) {
                var that = this
                this.$copyText(this.openMgInfo.token).then(
                    function (e) {
                        that.$Message.success(that.$t("settings.copyModal1"))
                    },
                    function (e) {
                        that.$Message.error(that.$t("settings.copyModal2"))
                    }
                )
            }
        },
        // 写入接口
        selectionChange1(selection) {
            this.apiListSelW = selection
        },
        // 读取接口
        selectionChange2(selection) {
            this.apiListSelR = selection
        },
        // 通知接口
        selectionChange3(selection) {
            this.newsListNow = selection
        },
    },
}
</script>

<style lang="less">
@import "./OpenMgmt2.less";
</style>

<style lang="less">
.open-mgmt {
    .ivu-form-item:not(:first-child) {
        margin-top: 30px;
    }
    .ivu-form-item:last-child {
        margin-bottom: 70px;
    }
    .ivu-radio-inner,
    .ivu-checkbox-inner {
        width: 18px;
        height: 18px;
        border-radius: 4px;
        /* background-color: #0f0f0f;
        border-color: #4d4d4d; */
        border-width: 1px;
        margin-right: 5px;
    }

    .ivu-checkbox-checked .ivu-checkbox-inner{
        background: #ffffff;
    }
    .ivu-radio-inner::after,
    .ivu-checkbox-checked .ivu-checkbox-inner::after {
        content: "";
        display: block;
        width: 10px;
        height: 16px;
        border-right: #ffffff solid 3px;
        border-bottom: #ffffff solid 3px;
        transform: rotate(35deg);
        position: absolute;
        top: -4px;
        left: 4px;
        border-radius: 0;
        background-color: transparent;
        border-color: #0094ff;
    }

    .ivu-checkbox-disabled .ivu-checkbox-inner {
        background-color: #0f0f0f;
        border-color: #4d4d4d;
    }

    .ivu-radio-wrapper,
    .ivu-checkbox-wrapper {
        color: #a5a5a5;
    }

    .ivu-checkbox {
        margin-right: 0;
    }

    .ivu-checkbox-wrapper {
        margin-left: 0;
        margin-right: 30px;
    }

    .open-info-disabled {
        .ivu-input {
            background: transparent;
            border: none;
            box-shadow: none;
            font-size: 16px;
            // color: #1e1f21;
            font-weight: 500;
        }
    }

    .ivu-tabs-nav {
        color: #a5a5a5;

        .ivu-tabs-tab {
            height: 40px;
            color: var(--second-text-color);
        }

        .ivu-tabs-ink-bar {
            border-bottom: 2px solid var(--tabs-bottom-color);
        }

        .ivu-tabs-tab-active {
            font-size: 14px;
            color: var(--primary-text-color);
            font-weight: bold;
        }

        .ivu-tabs-tab:hover {
            // color: #fff;
        }
    }

    .ivu-tabs-bar {
        margin-left: 20px;
    }
}
</style>