<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label="所属部门" prop="deptId">
                <el-input v-model="queryParams.deptId" placeholder="请输入所属部门" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="证书名称" prop="certificateName">
                <el-input v-model="queryParams.certificateName" placeholder="请输入证书名称" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="签发日期" prop="certificateIssueDate">
                <el-date-picker clearable v-model="queryParams.certificateIssueDate" type="date"
                    value-format="YYYY-MM-DD" placeholder="请选择签发日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="下次检验时间" prop="certificateNextDate">
                <el-date-picker clearable v-model="queryParams.certificateNextDate" type="date"
                    value-format="YYYY-MM-DD" placeholder="请选择下次检验时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="有效期" prop="certificateEffectiveDate">
                <el-date-picker clearable v-model="queryParams.certificateEffectiveDate" type="date"
                    value-format="YYYY-MM-DD" placeholder="请选择有效期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="使用期限" prop="certificateTerm">
                <el-input v-model="queryParams.certificateTerm" placeholder="请输入使用期限" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="证书状态" prop="certificateState">
                <el-input v-model="queryParams.certificateState" placeholder="请输入证书状态" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="备注" prop="certificateRemarks">
                <el-input v-model="queryParams.certificateRemarks" placeholder="请输入备注" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="证书类别" prop="certificateCategory">
                <el-input v-model="queryParams.certificateCategory" placeholder="请输入证书类别" clearable
                    @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>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:add']">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:edit']">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:export']">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出
                </el-button>
            </el-col>
			<el-col :span="1.5" v-hasPermi="['certificate:certificate:import']">
			  <ImportData url="certificate/certificate" title="导入" @success="getList" />
			</el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-card shadow="never" :body-style="{padding: '0px'}">
            <el-table v-loading="loading" :data="certificateList" 
				:header-cell-style="{ color: 'var(--white)',background: '#30B08E' }"
				@selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"
                    v-hasPermi="['certificate:certificate:edit', 'certificate:certificate:remove']" />
                <el-table-column type="expand" width="30">
                    <template #default="scope">
                        <div class="padding">
                            <el-descriptions :column="1">
                                <el-descriptions-item label="编号">
                                    <el-link v-copy="scope.row.certificateId">{{ scope.row.certificateId }}</el-link>
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="所属部门">
									{{scope.row.deptName}}
                                   <!-- <TextTag :options="deptList" column="deptId" label="deptName"
                                        :value="scope.row.deptId" text /> -->
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="证书名称">
                                    {{ scope.row.certificateName }}
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="证书正面">
                                    <image-preview :src="scope.row.certificatePositve" :width="50" :height="50" />
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="证书内容">
                                    {{ scope.row.certificateContent }}
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="签发日期">
                                    {{ parseTime(scope.row.certificateIssueDate, '{y}-{m}-{d}') }}
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="证书类别">
									<TextTag :options="certificate_category" column="value" label="label"
									    :value="scope.row.certificateCategory" text />
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="下次检验时间">
                                    {{ parseTime(scope.row.certificateNextDate, '{y}-{m}-{d}') }}
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="有效期">
                                    {{ parseTime(scope.row.certificateEffectiveDate, '{y}-{m}-{d}') }}
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="使用期限">
                                    {{ scope.row.certificateTerm }}
                                </el-descriptions-item>
                            </el-descriptions>
                            <el-descriptions :column="1">
                                <el-descriptions-item label="备注">
                                    {{ scope.row.certificateRemarks }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="序号" align="center" type="index" width="50" />
                <el-table-column label="编号" align="center" prop="certificateId" show-overflow-tooltip />
				<el-table-column label="证书正面" align="center" prop="certificatePositve" width="100">
				    <template #default="scope">
				        <image-preview :src="scope.row.certificatePositve" :width="50" :height="50" />
				    </template>
				</el-table-column>
                <el-table-column label="所属部门" align="center" prop="deptName"/>
                <el-table-column label="证书名称" align="center" prop="certificateName" />
                <el-table-column label="签发日期" align="center" prop="certificateIssueDate" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.certificateIssueDate, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="有效期" align="center" prop="certificateEffectiveDate" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.certificateEffectiveDate, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="检验类别" align="center" prop="certificateType" /> -->
                <el-table-column label="下次检验时间" align="center" prop="certificateNextDate" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.certificateNextDate, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="使用期限" align="center" prop="certificateTerm" />
				
                <el-table-column label="证书内容" align="center" prop="certificateContent" />
                <!-- <el-table-column label="证书状态" align="center" prop="certificateState" /> -->
                <el-table-column label="证书类别" align="center" prop="certificateCategory">
                    <template #default="scope">
                       <TextTag :options="certificate_category" column="value" label="label"
                           :value="scope.row.certificateCategory" text />
                    </template>
                </el-table-column>
				<el-table-column label="到期提醒" align="center" prop="isRemind">
				    <template #default="scope">
				       <el-switch v-model="scope.row.isRemind"
				         active-value="1"
				         inactive-value="0"
				       ></el-switch>
					   <!-- @change="handleCertificateChange(scope.row)" -->
				    </template>
				</el-table-column>
				
                <el-table-column label="备注" align="center" prop="certificateRemarks" />
					
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200"
                    fixed="right" v-hasPermi="['certificate:certificate:edit', 'certificate:certificate:remove']">
                    <template #default="scope">
                        <!-- <el-button link icon="View" @click="handleView(scope.row)"
                        v-hasPermi="['certificate:certificate:query']">详细
                    </el-button> -->
                        <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                            v-hasPermi="['certificate:certificate:edit']">修改
                        </el-button>
                        <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['certificate:certificate:remove']">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改证书对话框 -->
        <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
            <el-form ref="certificateRef" :model="form" :rules="rules" label-width="120px" class="grid col-2">
                <el-form-item label="所属部门" prop="deptId" class="flex">
                    <el-tree-select v-model="form.deptId" :data="deptOptions" class="flex-sub"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                        placeholder="请选择所属部门" check-strictly />
                </el-form-item>
                <el-form-item label="证书名称" prop="certificateName">
                    <el-input v-model="form.certificateName" placeholder="请输入证书名称" />
                </el-form-item>
                <el-form-item label="签发日期" prop="certificateIssueDate" class="flex">
                    <el-date-picker :clearable="false" v-model="form.certificateIssueDate" type="date" class="flex-sub"
                        value-format="YYYY-MM-DD" placeholder="请选择签发日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="下次检验时间" prop="certificateNextDate" class="flex">
                    <el-date-picker clearable v-model="form.certificateNextDate" type="date" value-format="YYYY-MM-DD"
                        class="flex-sub" placeholder="请选择下次检验时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="有效期" prop="certificateEffectiveDate" class="flex">
                    <el-date-picker clearable v-model="form.certificateEffectiveDate" type="date" class="flex-sub"
                        value-format="YYYY-MM-DD" placeholder="请选择有效期">
                    </el-date-picker>
                </el-form-item>
              <!--  <el-form-item label="使用期限" prop="certificateTerm">
                    <el-input v-model="form.certificateTerm" placeholder="请输入使用期限" />
                </el-form-item> -->
                <el-form-item label="证书类别" prop="certificateCategory">
					<el-select v-model="form.certificateCategory" placeholder="请选择证书类别" style="width:100%;display:block">
					    <el-option v-for="dict in certificate_category" :key="dict.value" :label="dict.label"
					        :value="dict.value"></el-option>
					</el-select>
                </el-form-item>
                <el-form-item label="证书内容">
                    <el-input v-model="form.certificateContent" type="textarea" :rows="3" placeholder="请输入证书内容" />
                </el-form-item>
                <!-- <el-form-item label="证书状态" prop="certificateState">
                    <el-input v-model="form.certificateState" placeholder="请输入证书状态" />
                </el-form-item> -->
                <el-form-item label="备注" prop="certificateRemarks">
                    <el-input v-model="form.certificateRemarks" type="textarea" :rows="3" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="证书正面">
                    <image-upload v-model="form.certificatePositve" :limit="1" />
                </el-form-item>
				<el-form-item label="到期提醒" prop="certificateRemarks">
				    <el-switch v-model="form.isRemind"
				      active-value="1"
				      inactive-value="0"
				    ></el-switch>
				</el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Certificate">
import ImportData from "@/components/ImportData";
import { listCertificate, getCertificate, delCertificate, addCertificate, updateCertificate, downloadCertificate } from "@/api/certificate/certificate";
import { treeselect } from "@/api/system/dept";
import { listDept } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
const { certificate_category } = proxy.useDict("certificate_category");
const certificateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const deptList = ref([]);
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        certificateName: null,
        certificateIssueDate: null,
        certificateType: null,
        certificateNextDate: null,
        certificateEffectiveDate: null,
        certificateTerm: null,
        certificatePositve: null,
        certificateContent: null,
        certificateState: null,
        certificateRemarks: null,
        certificateCategory: null
    },
    rules: {
        deptId: [
            {
                required: true, message: "所属部门不能为空", trigger: "blur"
            }
        ],
        certificateName: [
            {
                required: true, message: "证书名称不能为空", trigger: "blur"
            }
        ],
        certificateIssueDate: [
            {
                required: true, message: "签发日期不能为空", trigger: "blur"
            }
        ],
    }
})
    ;

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 查询证书列表 */
function getList() {
    loading.value = true;
    listCertificate(queryParams.value).then(response => {
        certificateList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

function addList() {
    loading.value = true;
    listCertificate(queryParams.value)
        .then(response => {
            certificateList.value.push(...response.rows);
            total.value = response.total;
            if (certificateList.value.length >= total.value) finished.value = true;
            loading.value = false;
        })
        .catch(response => {
            loading.value = false;
        });
}

// 下拉刷新
function handlePullDownRefresh() {
    queryParams.value.pageNum = 1;
    certificateList.value = [];
    addList();
}

// 滚动到底部的事件
function handleReachBottom() {
    queryParams.value.pageNum++;
    addList();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        certificateId: null,
        deptId: null,
        certificateName: null,
        certificateIssueDate: null,
        certificateType: null,
        certificateNextDate: null,
        certificateEffectiveDate: null,
        certificateTerm: null,
        certificatePositve: null,
        certificateContent: null,
        certificateState: null,
        certificateRemarks: null,
        createBy: null,
        createTime: null,
        certificateCategory: '1',
		isRemind: '1'
    };
    proxy.resetForm("certificateRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.certificateId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}
function handleCertificateChange(row) {
    // console.log(row)
    if (row.isRemind == undefined) {
        return
    }
    let text = row.isRemind === "0" ? "关闭" : "开启";
    proxy.$modal.confirm('确认要"' + text + '"证书《' + row.certificateName + '》的到期提醒功能?').then(function () {
        let data = {
            isRemind: row.isRemind,
            certificateId: row.certificateId
        }
        return updateCertificate(data);
    }).then(() => {
        proxy.$modal.msgSuccess(text + "成功");
    }).catch(function () {
        row.isRemind = row.isRemind === "0" ? "1" : "0";
    });
};
/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加证书";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const certificateId =
        row.certificateId || ids.value
    getCertificate(certificateId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改证书";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["certificateRef"].validate(valid => {
        if (valid) {
            if (form.value.certificateId != null) {
                updateCertificate(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addCertificate(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const certificateIds = row.certificateId || ids.value;
    proxy.$modal.confirm('是否确认删除证书编号为"' + certificateIds + '"的数据项？').then(function () {
        return delCertificate(certificateIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    downloadCertificate(queryParams.value)
    // proxy.download('certificate/certificate/export', {
    //   ...queryParams.value
    // }, `certificate_${new Date().getTime()}.xlsx`)
}

/** 详细按钮操作 */
function handleView(row) {
}

/** 查询部门下拉树结构 */
function getTreeselect() {
    treeselect().then(response => {
        deptOptions.value = response.data;
    });
};


function initialData() {
    // listDept({
    //     pageNum: 1,
    //     pageSize: 9999,
    // }).then(response => {
    //     deptList.value = response.data;
    // });
    getTreeselect();
    getList();
}

onActivated(() => {
    //// console.log("onActivated")
    initialData();
})
onMounted(() => {
    //// console.log("onMounted")
    initialData();
})
</script>

