<template>
    <!-- 申请库弹窗 -->
    <a-modal :visible="true" :width="width" :maskClosable="false" :destroyOnClose="true" centered :title="title"
        :footer="null" wrapClassName="modal-wrap" @cancel="onClose">
        <div class="action-content">
            <div class="top-search">
                <div class="left-search-input">
                    <div class="input">
                        <span>关键字</span>
                        <a-input allowClear v-model:value="searchValue" style="width: 200px;"
                            placeholder="请输入资源名称"></a-input>
                    </div>
                    <div class="input">
                        <span>审核状态</span>
                        <a-select allowClear v-model:value="selectValue" style="width: 200px" :options="statusOptions">
                        </a-select>
                    </div>
                    <div class="input">
                        <span>申请时间</span>
                        <!-- <a-date-picker v-model:value="searchTime" placeholder="申请时间" style="width: 200px" /> -->
                        <a-range-picker placeholder="申请时间" v-model:value="searchTime" />
                    </div>
                </div>
                <div class="right-btns">
                    <a-button style="margin-right: 15px;" @click="handleReset">重置</a-button>
                    <a-button type="primary" @click="handleSearch">查询</a-button>
                </div>
            </div>
            <div class="bottom-table">
                <BasicTable @register="registerTable" class="basic-table">
                    <!-- <template #OPT="{ record }">
                    <span>{{ record.OPT==='login' ? '登录' : '退出' }}</span>
                </template> -->
                    <template #toolbar>
                        <a-button style="background-color: #fc8b01;color: #fff;" @click="handleAdd"
                            :disabled="hasSelected">提交申请</a-button>
                    </template>
                    <template #action="{ record }">
                        <TableAction :actions="[
                            {
                                label: '移出',
                                tooltip: '移出',
                                onClick: handleDelete.bind(null, record),
                                disabled: record.shzt != '未提交' && record.shzt != '审核不通过'
                            },
                            {
                                label: '提交申请',
                                disabled: record.shzt != '未提交' && record.shzt != '审核不通过',
                                onClick: handleAdd.bind(null, record),
                            },
                        ]" />
                    </template>
                </BasicTable>
            </div>
        </div>
    </a-modal>
    <a-modal v-model:visible="showSelectAppModal" centered title="选择应用" width="400px" :maskClosable="false"
        @cancel="closeSelectAppModal">
        <div class="content" style="padding: 20px 10px 10px;font-size: 16px;">
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-item label="选择应用" name="selectAppKey">
                    <a-select allowClear v-model:value="selectAppKey" :options="appOptions">
                    </a-select>
                </a-form-item>
            </a-form>
        </div>
        <template #footer>
            <a-button @click="closeSelectAppModal">取消</a-button>
            <a-button type="primary" @click="handleSubmit">确定</a-button>
        </template>
    </a-modal>
    <!-- 申请弹出框 -->
    <ApplyModal @register="registerModal" @success="applyHandleSuccess" />
</template>
<script>
import { defineComponent, reactive, ref, onMounted, watch, toRefs, computed, createVNode } from 'vue';
// 导入表格组件，表格事件
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { session } from '/@/utils/Memory';
import moment from 'moment';
//操作申请库资源
import { getResInCar, clearResInCar, deleteResInCar } from '/@/api/resource/plat';
//提交授权申请
import { queryFlowInfoPage, submitExamine } from '/@/api/resource/examine';
//获取应用数据
import { list } from '/@/api/authorize/authorize';
import ApplyModal from './applyModal/ApplyModal.vue';
import { useModal } from '/@/components/Modal';

const props = {
    // resId: {
    //     type: String,
    //     default: ''
    // }
}
export default defineComponent({
    name: 'modal',
    components: { BasicTable, TableAction, ExclamationCircleOutlined, ApplyModal },
    props,
    emits: ['closeModal'],
    setup(props, { emit }) {
        const data = reactive({
            width: '1440px',
            title: '申请库',
        })
        const searchValue = ref('')
        const selectValue = ref('')
        const searchTime = ref([])
        const statusOptions = [
            {
                label: "未提交",
                value: "未提交"
            },
            {
                label: "审核中",
                value: "审核中"
            },
            {
                label: "审核通过",
                value: "审核通过"
            },
            {
                label: "审核不通过",
                value: "审核不通过"
            },
        ]
        const selectAppKey = ref('')
        const showSelectAppModal = ref(false)
        const appOptions = []
        const [registerModal, { openModal }] = useModal();
        // 请求所有申请库中的资源
        const getAllData = () => {
            return new Promise((resolve) => {
                getResInCar({
                    keyword: searchValue.value,
                    shzt: selectValue.value,
                    sqsj: searchTime.value.length == 2 ? moment(searchTime.value[0]).format('YYYY-MM-DD') : '',
                    endSqsj: searchTime.value.length == 2 ? moment(searchTime.value[1]).format('YYYY-MM-DD') : '',
                    userId: session.getItem('userId'),
                }).then((res) => {
                    if (res.datas?.length) {
                        let resData = []
                        res.datas.forEach(item => {
                            //筛掉接口服务
                            if (item.applyCarInfo.workflowType === 'INTERFACE') {
                                resData.push({
                                    resInCarId: item.applyCarInfo.id,
                                    serviceid: item.applyCarInfo.resId,
                                    zylx: '接口服务',
                                    // zymc: item.resInfo.SERVICENAME,
                                    zymc: item.applyCarInfo.resName,
                                    yyxt: "",
                                    // sqdz: "",
                                    sqsj: "",
                                    sqr: "",
                                    shzt: item.shzt,
                                    shr: "",
                                    shyj: ""
                                })
                            }
                        })
                        resolve(resData)
                    } else {
                        resolve([])
                    }
                }).catch((err) => {
                    resolve([])
                })
            })
        }
        //表格列
        const columns = [
            {
                title: '资源类型',
                align: 'center',
                dataIndex: 'zylx',
                key: 'zylx'
            },
            {
                title: '资源名称',
                align: 'center',
                dataIndex: 'zymc',
                key: 'zymc'
            },
            {
                title: '应用系统',
                align: 'center',
                dataIndex: 'yyxt',
                key: 'yyxt'
            },
            {
                title: '申请时间',
                align: 'center',
                dataIndex: 'sqsj',
                key: 'sqsj'
            },
            {
                title: '申请人',
                align: 'center',
                dataIndex: 'sqr',
                key: 'sqr'
            },
            {
                title: '审核状态',
                align: 'center',
                dataIndex: 'shzt',
                key: 'shzt'
            },
            {
                title: '审核人',
                align: 'center',
                dataIndex: 'shr',
                key: 'shr'
            },
            {
                title: '审核意见',
                align: 'center',
                dataIndex: 'shyj',
                key: 'shyj'
            }
        ]
        //注册表格
        const [registerTable, { reload, getRowSelection, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
            title: '资源列表',
            api: getAllData,
            columns: columns,        //表头配置
            bordered: false,
            striped: false,
            useSearchForm: false,     //开启搜索区域
            actionColumn: {
                width: 100,
                title: '操作',
                dataIndex: 'action',
                slots: { customRender: 'action' },
            },
            rowSelection: {
                type: 'checkbox',
                getCheckboxProps: (record) => {
                    if (record.shzt != '未提交' && record.shzt != '审核不通过') {
                        return { disabled: true }
                    } else {
                        return null
                    }
                }
            },
            pagination: {
                // pageSize: 10,
                hideOnSinglePage: false
            },
            rowKey: (record) => record.serviceid,
            canResize: true,
            showTableSetting: true,  // 显示表格设置
            tableSetting: {
                redo: true,
                size: true,
                setting: false,
                fullScreen: false
            },
            showIndexColumn: true,
            indexColumnProps: { fixed: 'left' },
        });
        //判断是否选中数据
        const hasSelected = computed(() => {
            const rowSelection = getRowSelection();
            return !(rowSelection.selectedRowKeys?.length === 1);
        });
        //重置查询
        const handleReset = () => {
            searchValue.value = ''
            selectValue.value = ''
            searchTime.value = ""
            reload();
        }
        //条件查询
        const handleSearch = () => {
            reload();
        }
        //移除资源
        const handleDelete = (record) => {
            Modal.confirm({
                title: '移出提示',
                icon: createVNode(ExclamationCircleOutlined),
                content: '确定移出该资源？',
                centered: true,
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk: (() => {
                    let params = {
                        idList: [record.resInCarId]
                    }
                    deleteResInCar(params, record).then(res => {
                        reload();
                        eventBus.emit('interfaceCenter')
                        eventBus.emit('addResToCarEventBusInterface')
                    })
                })
            });
        }
        //添加申请
        const handleAdd = (record) => {
            // showSelectAppModal.value = true;
            // selectAppKey.value = ''
            var list = record && record.resInCarId ? [record.resInCarId] : getSelectRowKeys();
            if (list.length) {
                openModal(true, {
                    isUpdate: false,
                    sqzys: list
                });
            }
        }
        const handleSubmit = () => {
            queryFlowInfoPage({
                page: 1,
                rows: 1000000
            }).then(flowRes => {
                const rowKeys = getSelectRowKeys();
                let ids = rowKeys.toString();
                let flag = 0
                flowRes.forEach(item => {
                    if (item.FLOWNAME === '接口授权') {
                        flag = 1
                        let params = {
                            bussInfo: {
                                bussname: '接口授权',//业务名称
                                flowid: item.id,//流程id
                                serverids: ids,//资源id
                                systemkey: selectAppKey.value,
                            }
                        }
                        submitExamine(params).then(res => {
                            if (res.resp_code === 0 && res.resp_msg === '提交成功') {
                                message.success('申请成功')
                                reload();
                            } else {
                                message.error('申请失败')
                            }
                        })
                    }
                })
                clearSelectedRowKeys();
                !flag && message.info('没有对应流程，请联系管理员');
            })
            showSelectAppModal.value = false;
        }
        const closeSelectAppModal = () => {
            showSelectAppModal.value = false;
            selectAppKey.value = ''
        }
        // 关闭请求弹窗
        const onClose = (e) => {
            emit('closeModal')
        }
        /**
         * 申请成功
         */
        function applyHandleSuccess() {
            reload();
        }
        //初始化请求所需数据
        onMounted(() => {
            list().then(res => {
                res.forEach(item => {
                    appOptions.push({
                        label: item.NAME,
                        value: item.KEY
                    })
                })
            })
        })
        return {
            // formRef,
            searchValue,
            selectValue,
            searchTime,
            statusOptions,
            selectAppKey,
            showSelectAppModal,
            appOptions,
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
            hasSelected,
            ...toRefs(data),
            registerModal,
            registerTable,
            handleReset,
            handleSearch,
            handleDelete,
            handleAdd,
            onClose,
            closeSelectAppModal,
            handleSubmit,
            applyHandleSuccess
        };
    },
});
</script>
<style lang="less" scoped>
.modal-wrap {
    .action-content {
        padding: 20px;
        max-height: 800px;
        overflow: auto;
        background-color: #eff0f5;

        .top-search {
            // padding-left: 20px;
            width: 100%;
            height: 74px;
            border-radius: 6px;
            background: #FFFFFF;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .left-search-input {
                margin-left: 20px;
                display: flex;

                .input {
                    margin-right: 30px;

                    span {
                        margin-right: 10px;
                    }
                }
            }

            .right-btns {
                margin-right: 20px;
            }
        }

        .bottom-table {
            // height: 825px;
            margin-top: 20px;

            .basic-table {
                height: 100%;

                ::v-deep .ant-table-title {
                    padding: 0 !important;

                    .vben-basic-title {
                        font-family: '阿里巴巴普惠体 2.0';
                        font-size: 16px;
                        font-weight: bold;
                        color: #333333;
                    }

                }
            }
        }
    }
}
</style>