<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 #toolbar>
                        <a-button :disabled="hasSelected" style="background-color: #fc8b01;color: #fff;"
                            @click="handleCreate">提交申请</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: applyHandleEdit.bind(null, record),
                            },
                        ]" />
                    </template>
                </BasicTable>
            </div>
        </div>
    </a-modal>
    <!-- 申请弹出框 -->
    <ApplyModal @register="registerModal" @success="applyHandleSuccess" :type="props.type" />
</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 ApplyModal from './applyModal/ApplyModal.vue';
import { useModal } from '/@/components/Modal';
import { columns } from "./ResCarModal.data"


export default defineComponent({
    name: 'modal',
    components: { BasicTable, TableAction, ApplyModal, ExclamationCircleOutlined },
    props: {
        type: {
            type: String,
            default: '',
        }
    },
    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 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 => {
                            //筛掉接口服务
                            var type = item.applyCarInfo.workflowType;
                            if (type == props.type) {
                                if (item?.resInfo?.SERVICEID) {
                                    resData.push({
                                        resInCarId: item.applyCarInfo.id,
                                        serviceid: item?.resInfo?.SERVICEID,
                                        zylx: type === 'MAP' ? '地图资源' : type === 'SCENE' ? '场景资源' : '文件资源',
                                        // zymc: item.resInfo.SERVICENAME,
                                        zymc: item.applyCarInfo.resName,
                                        yyxt: item.systemkey,
                                        // sqdz: "",
                                        sqsj: item.applyCarInfo.createtime,
                                        sqr: item.sqrname,
                                        shzt: item.shzt,
                                        shr: "",
                                        shyj: ""
                                    })
                                }
                            }
                        })
                        console.log("资源中心申请库列表:", resData)
                        resolve(resData)
                    } else {
                        resolve([])
                    }
                }).catch((err) => {
                    resolve([])
                })
            })
        }

        //注册表格
        const [registerTable, { reload, getRowSelection, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
            title: '资源列表',
            api: getAllData,		 //数据
            // dataSource: [],
            columns: columns,        //表头配置
            bordered: false,
            striped: false,
            useSearchForm: false,     //开启搜索区域
            // formConfig: formConfig,  //搜索字段配置
            actionColumn: {
                width: 120,
                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
            },
            maxHeight: 400,
            minHeight: 400,
            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('platListCenter')
                        eventBus.emit('addResToCarEventBus')
                    })
                })
            });
        }
        //添加申请
        const handleAdd = () => {
            console.log('开始申请');
            Modal.confirm({
                title: '申请提示',
                icon: createVNode(ExclamationCircleOutlined),
                content: '确定提交申请该资源？',
                centered: true,
                okText: '确定',
                cancelText: '取消',
                onOk: (() => {
                    queryFlowInfoPage({
                        page: 1,
                        rows: 1000000
                    }).then(flowRes => {
                        const rowKeys = getSelectRowKeys();
                        let ids = rowKeys.toString();
                        // console.log(flowRes);
                        let flag = 0
                        flowRes.forEach(item => {
                            if (item.FLOWNAME === judgeType(ids)) {
                                flag = 1
                                let params = {
                                    bussInfo: {
                                        bussname: judgeType(ids),//业务名称
                                        flowid: item.id,//流程id
                                        serverids: ids//资源id
                                    }
                                }
                                submitExamine(params).then(res => {
                                    if (res.resp_code === 0 && res.resp_msg === '提交成功') {
                                        message.success('申请成功')
                                        reload();
                                    } else {
                                        message.error('申请失败')
                                    }
                                })
                            }
                        })
                        clearSelectedRowKeys();
                        !flag && message.info('没有对应流程，请联系管理员');
                    })
                })
            });
        }
        const judgeType = (id) => {
            let resType = ''
            resType = id.indexOf('MR') > -1 ? '地图资源授权' : id.indexOf('ER') > -1 ? '场景资源授权' : '文件资源授权';
            // console.log(resType);
            return resType
        }
        // 关闭请求弹窗
        const onClose = (e) => {
            emit('closeModal')
        }
        //初始化请求所需数据
        onMounted(() => {

        })
        const [registerModal, { openModal }] = useModal();
        /**
         * 申请弹出框
         * @param record
         */
        function handleCreate() {
            var list = getSelectRowKeys();
            openModal(true, {
                isUpdate: false,
                sqzys: list
            });
        }
        /**
         * 申请弹出框
         * @param record
         */
        function applyHandleEdit(record) {
            if (record.serviceid) {
                openModal(true, {
                    record,
                    isUpdate: true,
                    sqzys: [record.serviceid]
                });
            } else {
                message.error('选择的资源没有服务ID!')
            }
        }

        /**
         * 申请成功
         */
        function applyHandleSuccess() {
            reload();
            eventBus.emit('platListCenter')
        }
        return {
            props,
            registerModal,
            handleCreate,
            applyHandleEdit,
            applyHandleSuccess,
            // formRef,
            searchValue,
            selectValue,
            searchTime,
            statusOptions,
            hasSelected,
            ...toRefs(data),
            registerTable,
            handleReset,
            handleSearch,
            handleDelete,
            handleAdd,
            onClose
        };
    },
});
</script>
<style lang="less" scoped>
.modal-wrap {
    .action-content {
        padding: 20px;
        max-height: 800px;
        overflow: auto;
        background-color: #eff0f5;

        .top-search {
            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 {
            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>