<template>
    <!-- 资源审核弹窗 -->
    <a-modal :visible="true" :width="width" :maskClosable="false" :destroyOnClose="true" :title="title" centered
        wrapClassName="modal-wrap" @cancel="onClose">
        <div class="action-content">
            <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" :class="{'disabled':disable}">
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="名称" name="name">
                            <a-input allowClear v-model:value="form.name" style="width: 100%" @change="createKey" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" :offset="0">
                        <a-form-item label="编码" name="key">
                            <a-input allowClear v-model:value="form.key" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="密匙范围" name="scope">
                            <a-select v-model:value="form.scope" style="width: 100%" :options="scopeOpts">
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" :offset="0">
                        <a-form-item label="授权方式" name="grantTypes">
                            <a-select v-model:value="form.grantTypes" mode="multiple"
                                :dropdown-style="{ maxHeight: '150px', overflow: 'auto' }" :maxTagCount="2"
                                style="width: 100%" :options="grantTypesOpts">
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="自动授权" name="autoapproveType">
                            <a-select v-model:value="form.autoapproveType" style="width: 100%" :options="autoapproveOpts">
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" :offset="0">
                        <a-form-item label="系统用户" name="userIds">
                            <a-input v-model:value="form.userIds" style="width: 100%" disabled />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="24">
                        <a-form-item label="描述" name="note" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                            <a-textarea allowClear v-model:value="form.note" placeholder="" :rows="3" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <template #footer>
            <div class="btns" style="display: flex;justify-content: flex-end;">
                <a-button class="btn" @click="onClose"
                    style="width: 64px;height: 34px;margin-right: 25px;color: #333333;">取消</a-button>
                <a-button class="btn" @click="handleSubmit"
                    style="width: 64px;height: 34px;background: #0671DD;color: #ffffff;">确定</a-button>
            </div>
        </template>
    </a-modal>
</template>
<script>
import { defineComponent, reactive, ref, onMounted, watch, toRefs, createVNode, toRaw } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { session } from '/@/utils/Memory';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import moment from 'moment';
import { generateCodeByName } from '/@/api/sys/tag';
import { save } from '/@/api/authorize/authorize';

const props = {
    appInfo: {
        type: Object,
        default: ()=>{}
    },
    title: {
        type: String,
        default: "新增应用"
    }
}
export default defineComponent({
    name: 'modal',
    components: { ExclamationCircleOutlined },
    props,
    setup(props, { emit }) {
        const data = reactive({
            width: '800px',
            title: props.title,
            timer: null,
            disable: props.title==='查看应用'
        })
        const formRef = ref(null)
        const form = reactive({
            name: "",
            key: "",
            id: "",
            note: "",
            grantTypes: [],
            scope: "",
            autoapproveType: 1,
            autoapprove: true,
            userIds: "",
            userIdsArr: []
        })
        const checkTypes = (rule, value, callback) => {
            if (value === undefined || !value.length) {
                return Promise.reject("请选择授权方式")
            } else {
                return Promise.resolve()
            }
        };
        const checkAutoApprove = (rule, value, callback) => {
            if (value === undefined || value === null) {
                return Promise.reject("请选择自动授权")
            } else {
                return Promise.resolve()
            }
        };
        const rules = {
            name: [{
                required: true,
                message: '请输入名称',
                trigger: 'blur'
            }],
            key: [{
                required: true,
                message: '请输入编码',
                trigger: 'change'
            }],
            scope: [{
                required: true,
                message: '请输入密匙范围',
                trigger: 'change'
            }],
            autoapproveType: [
                { required: true, validator: checkAutoApprove, trigger: "change" },
            ],
            grantTypes: [
                { required: true, validator: checkTypes, trigger: "change" },
            ]
        };
        const scopeOpts = [
            {
                label: "系统内部",
                value: "app"
            },
            {
                label: "平台",
                value: "all"
            }
        ]
        const grantTypesOpts = [
            {
                label: "授权码",
                value: "authorization_code"
            },
            {
                label: "密码",
                value: "password"
            },
            {
                label: "客户端凭证",
                value: "client_credentials"
            },
            {
                label: "token刷新口令",
                value: "refresh_token"
            }
        ]
        const autoapproveOpts = [
            {
                label: "是",
                value: 1
            },
            {
                label: "否",
                value: 0
            },
        ]
        const createKey = (e) => {
            if (data.timer) {
                clearTimeout(data.timer);
            }
            data.timer = setTimeout(() => {
                //名称生成code
                let param = {
                    1: session.getItem('tokenV2'),
                    2: form.name
                }
                generateCodeByName(param).then(res => {
                    form.key = res.result
                })
            }, 500);
        }
        //初始化请求所需数据
        onMounted(() => {
            for(let key in props.appInfo){
                form[key] = props.appInfo[key]
            }
        })
        // 关闭请求弹窗
        const onClose = (e) => {
            emit('closeModal')
        }
        //提交方法
        function handleSubmit() {
            formRef.value.validate().then(() => {
                let params = JSON.parse(JSON.stringify(form))
                params.autoapprove = Boolean(params.autoapproveType)
                params.clientSecretStr = params.key
                params.system = {
                    id:params.id,
                    key:params.key,
                    name:params.name,
                    note:params.note
                }
                delete params.autoapproveType
                delete params.userIdsArr
                if(!data.disable){
                    save(params).then(res=>{
                        message.success('保存成功')
                        emit('onSubmit')
                    })
                }else{
                    onClose()
                }
            }).catch((error) => {
                console.log('error', error);
            });
        }
        // 重置表单
        const resetForm = () => {
            formRef.value.resetFields();
        };

        return {
            formRef,
            form,
            ...toRefs(data),
            rules,
            scopeOpts,
            grantTypesOpts,
            autoapproveOpts,
            createKey,
            onClose,
            handleSubmit,
        };
    },
});
</script>
<style lang="less" scoped>
.modal-wrap {
    .action-content {
        padding: 20px;
        .disabled{
            pointer-events: none;
        }
    }
}
</style>