<template>
    <div>
        <el-table :data="list" border v-loadding="loadding" style="width: 100%">
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column label="应用名称" align="center" prop="applicationName" />
            <el-table-column label="图标" align="center" prop="icon">
                <template #default="{ row }">
                    <ImagePreview :src="row.icon" style="width: 50px;height: 50px;"></ImagePreview>
                </template>
            </el-table-column>
            <el-table-column label="背景" align="center" prop="bgUrl">
                <template #default="{ row }">
                    <ImagePreview :src="row.bgUrl" style="width: 50px;height: 50px;"></ImagePreview>
                </template>
            </el-table-column>
            <el-table-column label="应用类型" align="center" prop="type">
                <template #default="{ row }">
                    <span>{{ selectDictLabel(application_type, row.type) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="前置条件" width="200">
                <template #default="{ row }">
                    <div v-for="(item, index) in row.precondition" style="display: flex;" :key="index">
                        <div>
                            <dict-tag :options="enterprise_type" :value="item.cpyType" />
                        </div>
                        -
                        <div>
                            <dict-tag :options="industry_type" :value="item.industryType" />
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="180" prop="status">
                <template #default="{ row }">
                    {{ +row.status ? '启用': '未启用' }}
                </template>
            </el-table-column>
            <el-table-column label="授权时间范围" align="center" width="180" prop="status">
                <template #default="{ row }">
                    {{ row.applicationCpyVo.startAt  }}
                    ~ {{ row.applicationCpyVo.endAt }}
                </template>
            </el-table-column>
            <el-table-column width="180" fixed="right" label="操作" align="center">
                <template #default="{ row }">
                    <el-button @click="deleteRow(row)" type="danger" text>删除</el-button>
                    <el-button @click="editRow(row)" type="primary" text>编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="d-flex j-c" style="padding-top: 16px;">
            <el-pagination
                v-model:page-size="queryParams.pageSize"
                background
                v-model:current-page="queryParams.pageNum"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                hide-on-single-page
                @size-change="changePageSize"
                @current-change="changePage"
            />
        </div>
        <el-dialog v-model="dialog.show" :title="dialog.title" width="500" :before-close="handleClose">
            <el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="auto">
                <el-form-item prop="applicationIds" label="授权应用名称">
                    <el-select v-model="form.applicationIds" placeholder="授权应用名称" multiple style="width: 100%">
                        <el-option v-for="item in options" :key="item.id" :label="item.applicationName" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="rangeTime" label="授权日期范围">
                    <el-date-picker
                        v-model="form.rangeTime"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD hh:mm:ss"
                        :disabled-date="disabledDate"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup name="authApp">
import { listApplication } from '@/api/permission/application';
import { batchGrant, batchRemove } from '@/api/settled';
import { propTypes } from '@/utils/propTypes';
import { debounce } from 'lodash';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { application_type, enterprise_type, industry_type } = toRefs<any>(proxy?.useDict('application_type', 'industry_type', 'enterprise_type'));
const formRef = ref<any>(null);
const total = ref<any>(0);
const props = defineProps({
    cpyid: propTypes.string.def('')
});
const dialog = reactive({
    show: false,
    title: '新增应用'
});
const queryParams = ref({
    pageSize: 10,
    pageNum: 1
});
const rules = reactive<any>({
    applicationIds: [{ required: true, type: 'array', message: '请选择应用', trigger: 'change' }],
    rangeTime: [{ required: true, type: 'array', message: '请选择授权时间段', trigger: 'change' }]
});
const form = ref<any>({
    applicationIds: undefined,
    rangeTime: []
});
const editRow = (row: any) => {
    form.value = {
        applicationIds: [row.id],
        rangeTime: [row.applicationCpyVo.startAt, row.applicationCpyVo.endAt]
    };
    dialog.title = '编辑授权';
    dialog.show = true;
};
const deleteRow = (row: any) => {
    ElMessageBox.confirm('您确定要删除该应用么?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
    })
        .then(() => {
            const params = [row.id];
            batchRemoveFn(params);
        })
        .catch(() => {
            proxy?.$modal.msgWarning('取消删除');
        });
};
const batchRemoveFn = async (params: any) => {
    proxy?.$modal.loading('删除中');
    const res = await batchRemove(params, props.cpyid).catch(() => {
        proxy?.$modal.closeLoading();
    });
    if (!res || res.code !== 200) return;
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgSuccess('删除成功');
    getList();
};

const submitForm = async (formRef: any) => {
    if (!formRef) return;
    const valid = await formRef.validate();
    if (!valid) return;
    proxy?.$modal.loading('操作中...');
    const params = {
        ...form.value,
        cpyids: [props.cpyid],
        startAt: form.value.rangeTime[0],
        endAt: form.value.rangeTime[1]
    };
    if (form.value.id) {
        await batchGrant(params).finally(() => proxy?.$modal.closeLoading());
    } else {
        await batchGrant(params).finally(() => proxy?.$modal.closeLoading());
    }
    proxy?.$modal.msgSuccess('操作成功');
    dialog.show = false;
    getList();
};
const list = ref<any[]>([]);
const options = ref<any[]>([]);
const loadding = ref(false);
const getList = debounce(async () => {
    proxy?.$modal.loading('加载中');
    const res = await listApplication({ ...queryParams.value, cpyid: props.cpyid }).catch(() => {
        proxy?.$modal.closeLoading();
    });
    if (!res || res.code !== 200) return;
    proxy?.$modal.closeLoading();
    total.value = res.total;
    list.value = [...res.rows];
}, 300);

const getOptions = async () => {
    const params = {
        pageSize: 1000,
        pageNum: 1
    };
    const res = await listApplication(params);
    if (!res) return;
    console.log(res, '-----');
    options.value = [...res.rows];
};
const addApp = () => {
    console.log('hehe');
    dialog.title = '新增应用';
    dialog.show = true;
};
const handleClose = () => {
    dialog.show = false;
};
const disabledDate = (time: Date) => {
    return time.getTime() < Date.now() - 60 * 60 * 1000 * 24;
};
const changePageSize = (pageSize: number) => {
    queryParams.value.pageSize = pageSize;
    getList();
};
const changePage = (pageNum: number) => {
    queryParams.value.pageNum = pageNum;
    getList();
};
defineExpose({
    addApp
});
onMounted(() => {
    getList();
    getOptions();
});
</script>
