<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item label="应用名称" prop="applicationName">
                        <el-input
                            v-model="queryParams.applicationName"
                            placeholder="请输入应用名称"
                            clearable
                            style="width: 240px"
                            @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="图标" prop="icon">
                        <el-input v-model="queryParams.icon" placeholder="请输入图标" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="跳转地址" prop="url">
                        <el-input v-model="queryParams.url" placeholder="请输入跳转地址" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>

        <el-tabs v-model="activeTab" style="padding: 5px;">
            <el-tab-pane label="千寻应用" name="tab1">
                <el-card shadow="never">
                    <template #header>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="1.5">
                                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['smarttrace:application:add']"
                                    >新增</el-button
                                >
                            </el-col>
                            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                        </el-row>
                    </template>

                    <el-table v-loading="loading" :data="applicationList" border>
                        <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="url" />
                        <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 in row.precondition" style="display: flex;">
                                    <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 }">
                                <el-switch
                                    v-model="row.status"
                                    active-value="1"
                                    @change="changeStatus($event, row.id)"
                                    inactive-value="0"
                                    active-text="启用"
                                    inactive-text="未启用"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="备注" align="center" prop="remark" />
                        <el-table-column label="应用ID" align="center" prop="id" />
                        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-tooltip content="编辑" placement="top">
                                    <el-button
                                        link
                                        type="primary"
                                        icon="Edit"
                                        @click="handleEdit(scope.row)"
                                        v-hasPermi="['smarttrace:application:remove']"
                                    ></el-button>
                                </el-tooltip>
                                <el-tooltip content="删除" placement="top">
                                    <el-button
                                        link
                                        type="primary"
                                        icon="Delete"
                                        @click="handleDelete(scope.row)"
                                        v-hasPermi="['smarttrace:application:remove']"
                                    ></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination
                        v-show="total > 0"
                        :total="total"
                        v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize"
                        @pagination="getList"
                    />
                </el-card>
            </el-tab-pane>
            <el-tab-pane label="合作伙伴应用" name="tab2">
                <el-table v-loading="loading" :data="applicationList2" border>
                    <el-table-column type="index" width="55" align="center" label="序号" />
                    <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="url" />
                    <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="状态" align="center" width="180" prop="status">
                        <template #default="{ row }">
                            <el-switch v-model="row.status" active-value="1" inactive-value="0" disabled active-text="启用" inactive-text="未启用" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" align="center" prop="remark" />
                    <el-table-column label="应用ID" align="center" prop="id" />
                    <el-table-column label="授权开始日期" align="center" prop="startAt" />
                    <el-table-column label="授权结束日期" align="center" prop="endAt" />
                    <el-table-column label="千寻应用" align="center" prop="originName" />
                    <el-table-column label="合作伙伴" align="center" prop="partner">
                        <template #default="{ row }"> </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime" width="120">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList2"
                />
            </el-tab-pane>
        </el-tabs>
        <!-- 添加或修改应用信息对话框 -->
        <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
            <el-form ref="applicationFormRef" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="应用名称" prop="applicationName">
                            <el-input v-model="form.applicationName" placeholder="请输入应用名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应用类型" prop="type">
                            <el-select v-model="form.type" style="width: 100%;" placeholder="请选择应用类型" clearable>
                                <el-option v-for="dict in application_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="图标" prop="icon">
                            <div>
                                <UploadAvatar title="应用图标" v-model="form.icon"></UploadAvatar>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="背景" prop="bgUrl">
                            <div class="flex1">
                                <PhotoUpload v-model="form.bgUrl"></PhotoUpload>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" placeholder="请输入排序" />
                </el-form-item>
                <el-form-item label="按钮配置" prop="btnConf">
                    <el-input v-model="form.btnConf" placeholder="请输入按钮配置" />
                </el-form-item>
                <el-form-item label="跳转地址" prop="url">
                    <el-input v-model="form.url" placeholder="请输入跳转地址" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-divider>前置条件（任意一个）</el-divider>
                <div class="cpy-container" v-loading="loading">
                    <div class="cpy-item" v-for="(item, index) in form.precondition" :key="index">
                        <el-form-item
                            label="企业类型"
                            :prop="`precondition.${index}.cpyType`"
                            :rules="{ required: true, message: '企业类型不能为空', trigger: 'blur' }"
                        >
                            <el-select v-model="item.cpyType" placeholder="企业类型" clearable>
                                <el-option v-for="dict in enterprise_type" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item
                            label="行业类别"
                            :prop="`precondition.${index}.industryType`"
                            :rules="{ required: true, message: '行业类别不能为空', trigger: 'blur' }"
                            clearable
                        >
                            <el-select v-model="item.industryType" placeholder="行业类别">
                                <el-option v-for="dict in industry_type" :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-button type="text" icon="remove" @click="handleRemovePrecondition(index)"></el-button>
                    </div>
                </div>
                <span v-show="form.precondition.length == 0">无需前置条件</span>
                <div style="display: flex;">
                    <el-button type="primary" style="flex:1" @click="handleAddPrecondition">添加条件</el-button>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Application" lang="ts">
import {
    listApplicationQx,
    listApplicationOther,
    getApplication,
    delApplication,
    addApplication,
    updateApplication,
    ApplicationOnshelf,
    ApplicationLeaveshelf
} from '@/api/permission/application';
import { ApplicationVO, ApplicationQuery, ApplicationForm } from '@/api/permission/application/types';
import { UploadAvatar } from '@/views/components';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { application_type, enterprise_type, industry_type } = toRefs<any>(proxy?.useDict('application_type', 'industry_type', 'enterprise_type'));
const applicationList = ref<ApplicationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const applicationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData = (): ApplicationForm => ({
    id: undefined,
    applicationName: undefined,
    icon: undefined,
    url: undefined,
    type: undefined,
    remark: undefined,
    keyInfo: {},
    sort:0,
    btnConf: undefined,
    precondition: []
});
const data = reactive<PageData<ApplicationForm, ApplicationQuery>>({
    form: initFormData(),
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationName: undefined,
        type: undefined,
        status: undefined,
        params: {}
    },
    rules: {
        applicationName: [{ required: true, message: '应用名称不能为空', trigger: 'blur' }],
        icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
        url: [{ required: true, message: '跳转地址不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '应用类型不能为空', trigger: 'change' }]
    }
});

const { queryParams, form, rules } = toRefs(data);
/** 启用和未启用开关 */
const changeStatus = async (event: string, id: string) => {
    let res = null;
    loading.value = true;
    if (+event) {
        res = await ApplicationOnshelf(id);
    } else {
        res = await ApplicationLeaveshelf(id);
    }
    getList();
};
/** 查询应用信息列表 */
const getList = async () => {
    loading.value = true;
    const res = await listApplicationQx(queryParams.value);
    applicationList.value = res.rows;
    total.value = res.total;
    loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
    form.value = initFormData();
    applicationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    queryParams2.value.pageNum = 1;
    getList();
    getList2();
};

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
/** 添加前置条件 */
const handleAddPrecondition = () => {
    form.value.precondition.push({ cpyType: undefined, industryType: undefined });
};
const handleRemovePrecondition = (index: number) => {
    form.value.precondition.splice(index, 1);
};
/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = '添加应用信息';
};
const handleEdit = (row: any) => {
    reset();
    Object.assign(form.value, row);
    dialog.visible = true;
    dialog.title = '修改应用信息';
};

/** 提交按钮 */
const submitForm = () => {
    applicationFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateApplication(form.value).finally(() => (buttonLoading.value = false));
            } else {
                await addApplication(form.value).finally(() => (buttonLoading.value = false));
            }
            proxy?.$modal.msgSuccess('修改成功');
            dialog.visible = false;
            await getList();
        }
    });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ApplicationVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除应用信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
    await delApplication(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
};
/**合作伙伴应用 */
const activeTab = ref('tab1');
const applicationList2 = ref<ApplicationVO[]>([]);
const queryParams2 = ref<ApplicationQuery>({
    pageNum: 1,
    pageSize: 10,
    applicationName: undefined,
    type: undefined,
    status: undefined
});
watch(queryParams, (newValue) => {
    queryParams2.value.applicationName = newValue.applicationName;
    queryParams2.value.type = newValue.type;
    queryParams2.value.status = newValue.status;
});
const total2 = ref(0);
const loading2 = ref(false);
/** 查询合作伙伴应用信息列表 */
const getList2 = async () => {
    loading2.value = true;
    const res = await listApplicationOther(queryParams2.value);
    applicationList2.value = res.rows;
    total2.value = res.total;
    loading2.value = false;
};

onMounted(() => {
    getList();
    getList2();
});
</script>
<style scoped>
.cpy-container {
    margin-top: 20px;
    margin-bottom: 20px;

    .cpy-item {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
    }
}
</style>
