<template>
    <div class="app-container">
        <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="获奖级别" prop="awardsLevel">
                <el-select v-model="queryForm.awardsLevel" placeholder="请选择" clearable style="width: 100%;">
                    <el-option v-for="dict in dict.type.awards_level" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="获奖类型">
                <el-select v-model="queryForm.awardsType" placeholder="请选择" clearable style="width: 100%;">
                    <el-option v-for="dict in dict.type.awards_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="时间段">
                <el-date-picker v-model="queryForm.startTime" type="date" placeholder="选择" value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-date-picker v-model="queryForm.endTime" type="date" placeholder="选择" value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="主导部门">
                <Treeselect v-model="queryForm.competentDeptId" :options="deptOptions" :show-count="true" placeholder="请选择"
                    :defaultExpandLevel=1 style="width: 208px" filterable />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['system:student:export']">导出
                </el-button>
            </el-form-item>
            <el-row :gutter="10" class="mb8">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>

            </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="55" />
            <el-table-column align="center" prop="competitionName" label="比赛名称" width="130" show-overflow-tooltip />
            <el-table-column align="center" prop="awardsName" label="获奖名称" />
            <el-table-column align="center" prop="competentDept" label="主导部门" />
            <el-table-column align="center" prop="awardsLevel" label="获奖级别">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.awards_level, row.awardsLevel) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="awardsType" label="获奖类型">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.awards_type, row.awardsType) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="deptDirector" label="部门主任" width="90px" />
            <el-table-column align="center" prop="organizer" label="主办单位" />
            <el-table-column align="center" prop="awardsTime" label="获奖时间" width="100px" />
            <el-table-column align="center" prop="证书图片" label="证书图片" width="120px">
                <template slot-scope="scope">
                    <el-carousel :interval="4000" height="100px">
                        <el-carousel-item v-for="(item, index) in scope.row.schoolAccessoryList" :key="index">
                            <el-image style="width: 100px; height: 100px" :src="pev + item.accessoryUrl"
                                :preview-src-list="[pev + item.accessoryUrl]"></el-image>
                        </el-carousel-item>
                    </el-carousel>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="auditState" label="审核状态">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.audit_state, row.auditState) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="remark" label="公布形式" width="120" show-overflow-tooltip>
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.announcement, row.remark) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                    <div>
                        <div>
                            <el-button v-if="['1', '3'].includes(scope.row.auditState)" @click="handleExamine(scope.row)"
                                type="text" size="small">审核</el-button>
                            <el-button v-if="['1', '3'].includes(scope.row.auditState)" @click="handleEdit(scope.row)"
                                type="text" size="small">编辑</el-button>
                            <el-button v-if="['1', '3'].includes(scope.row.auditState)" @click="handleDelete(scope.row)"
                                type="text" size="small">删除</el-button>
                        </div>
                        <el-button v-if="scope.row.auditState === '2'" @click="handleEdit(scope.row)" type="text"
                            size="small">编辑</el-button>
                        <el-button v-if="scope.row.auditState === '2'" @click="handleDelete(scope.row)" type="text"
                            size="small">删除</el-button>
                    </div>



                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryForm.pageNum" :limit.sync="queryForm.pageSize"
            @pagination="getList" />

        <!-- 新增/编辑弹框 -->
        <el-dialog title="详细信息" :visible.sync="dialogTableVisible" width="1100px">
            <el-form :model="form" ref="form" size="small" label-width="110px" :rules="rules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="比赛名称" prop="competitionName">
                            <el-input v-model="form.competitionName" placeholder="请输入" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="主办单位" prop="organizer">
                            <el-input v-model="form.organizer" placeholder="请输入" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="获奖名称" prop="awardsName">
                            <el-input v-model="form.awardsName" placeholder="请输入" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="主管部门" prop="competentDeptId">
                            <Treeselect v-model="form.competentDeptId" :options="deptOptions" :show-count="true"
                                placeholder="请选择" :default-expand-level=1 :style="{ width: '100%' }" @select="deptIdAndName"
                                filterable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="部门主任" prop="deptDirectorId">
                            <el-select v-model="form.deptDirectorId" placeholder="请选择" :style="{ width: '100%' }"
                                filterable>
                                <el-option v-for="item in getDeptLeaders" :key="item.id" :label="item.teacherName"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="获奖时间" prop="awardsTime">
                            <el-date-picker v-model="form.awardsTime" type="date" placeholder="选择" value-format="yyyy-MM-dd"
                                :style="{ width: '100%' }">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="获奖等级" prop="awardsLevel">
                            <el-select v-model="form.awardsLevel" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.awards_level" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="获奖类型" prop="awardsType">
                            <el-select v-model="form.awardsType" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.awards_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="remark">
                            <el-select v-model="form.remark" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.announcement" :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="schoolAccessoryList">
                            <el-upload v-loading="uploadLoading" class="avatar-uploader" multiple :action="uploadFileUrl"
                                accept="image/*" :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload" :on-remove="handleRemove">
                                <div v-if="form.schoolAccessoryList.length === 0">
                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                </div>
                                <div v-else>
                                    <div v-for="(item, index) in form.schoolAccessoryList" :key="index">
                                        <img :src="pev + item.accessoryUrl" class="avatar" />
                                    </div>
                                </div>
                            </el-upload>
                            <i class="el-icon-delete" @click="handleRemove(index)"></i>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button type="primary" @click="submitForm"> 确 定</el-button>
                <el-button @click="cancelDialog"> 取 消 </el-button>
            </div>
        </el-dialog>
        <!-- 审核弹框 -->
        <el-dialog title="审核信息" :visible.sync="open" width="1100px">
            <el-form :model="form" ref="form" size="small" label-width="110px" :disabled="isEdit">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="比赛名称" prop="competitionName">
                            <el-input v-model="form.competitionName" placeholder="请输入" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="主办单位" prop="organizer">
                            <el-input v-model="form.organizer" placeholder="请输入" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="获奖名称" prop="awardsName">
                            <el-input v-model="form.awardsName" placeholder="请输入" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="主管部门" prop="competentDeptId">
                            <Treeselect v-model="form.competentDeptId" :options="deptOptions" :show-count="true"
                                placeholder="请选择" :default-expand-level=1 :style="{ width: '100%' }" @select="deptIdAndName"
                                :disabled="isEdit" filterable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="部门主任" prop="deptDirectorId">
                            <el-select v-model="form.deptDirectorId" placeholder="请选择" :style="{ width: '100%' }">
                                <el-option v-for="item in getDeptLeaders" :key="item.id" :label="item.teacherName"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="获奖时间" prop="awardsTime">
                            <el-date-picker v-model="form.awardsTime" type="date" placeholder="选择" value-format="yyyy-MM-dd"
                                :style="{ width: '100%' }">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="获奖等级" prop="awardsLevel">
                            <el-select v-model="form.awardsLevel" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.awards_level" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="获奖类型" prop="awardsType">
                            <el-select v-model="form.awardsType" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.awards_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="remark">
                            <el-select v-model="form.remark" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.announcement" :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="schoolAccessoryList">
                            <el-upload v-loading="uploadLoading" class="avatar-uploader" multiple :action="uploadFileUrl"
                                accept="image/*" :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload" :on-remove="handleRemove">
                                <div v-if="form.schoolAccessoryList.length === 0">
                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                </div>
                                <div v-else>
                                    <div v-for="(item, index) in form.schoolAccessoryList" :key="index">
                                        <img :src="pev + item.accessoryUrl" class="avatar" />
                                    </div>
                                </div>
                            </el-upload>
                            <i class="el-icon-delete" @click="handleRemove(index)"></i>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="handleAgree" type="primary" size="small">同意</el-button>
                <el-button @click="handleDisagree" type="danger" size="small">不同意</el-button>
            </div>

        </el-dialog>

    </div>
</template>

<script>

import {
    addawards,
    updateAwards,
    listAwards,
    getAwards,
    delAwards,
    subApply,
    getdeptTree,
    getDeptLeader,
    addawardsgr,
    listAwardsgr,
    listAwardstg
} from '@/api/smartSchool/awardsDisciplinary/schoolAwards/awardManagement'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import picAvatar from '@/views/smartSchool/schoolManage/introduce/schoolInfo/profile/picAvatar'
export default {
    name: 'index',
    components: { Treeselect, picAvatar },
    dicts: ['awards_type', 'awards_level', 'audit_state', 'announcement'],
    data() {
        return {
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
            queryForm: {
                pageNum: 1,
                pageSize: 10,
                awardsLevel: "",
                awardsType: "",
                startTime: "",
                endTime: "",
                competentDeptId: null,
            },
            nowType: 0, // 0新增、1编辑、2查看
            uploadLoading: false,
            pev: process.env.VUE_APP_BASE_API,
            getDeptLeaders: [],
            deptOptions: [],
            //表格数据
            tableData: [],
            //查看弹窗表格
            ExperimentalData: [],
            form: {
                pageNum: 1,
                pageSize: 10,
                competitionName: "",
                organizer: "",
                awardsName: "",
                competentDeptId: null,
                awardsLevel: "",
                deptDirectorId: null,
                awardsTime: "",
                awardsType: "",
                remark: "",
                schoolAccessoryList: [],

            },
            rules: {
                competitionName: [
                    { required: true, message: "比赛名称不能为空", trigger: "change" }
                ],
                organizer: [
                    { required: true, message: "主办单位不能为空", trigger: "change" }
                ],
                awardsName: [
                    { required: true, message: "获奖名称不能为空", trigger: "change" }
                ],
                competentDeptId: [
                    { required: true, message: "主管部门不能为空", trigger: "change" }
                ],
                awardsTime: [
                    { required: true, message: "获奖时间不能为空", trigger: "change" }
                ],
                deptDirectorId: [
                    { required: true, message: "部门主任不能为空", trigger: "change" }
                ],

                awardsLevel: [
                    { required: true, message: "获奖等级不能为空", trigger: "change" }
                ],
                awardsType: [
                    { required: true, message: "获奖类型不能为空", trigger: "change" }
                ],
                schoolAccessoryList: [
                    { required: true, message: "证书照片不能为空", trigger: "change" }
                ],
                remark: [
                    { required: true, message: "公布形式不能为空", trigger: "change" }
                ],

            },
            //弹窗
            dialogTableVisible: false,
            open: false,
            isEdit: false,
            total: 0,
        }
    },
    created() {
        this.getList();
        this.getDeptTree();
    },

    methods: {

        handleAdd() {
            this.reset();
            this.dialogTableVisible = true;
        },
        handleEdit(row) {
            console.log(row);
            const id = row.id || this.ids;
            getAwards(id).then((response) => {
                this.form = response.data;
                this.accessoryUrl = this.pev + this.picUrl
                this.form.competentDeptId = response.data.competentDeptId;
                const params = {
                    competentDeptId: this.form.competentDeptId
                }
                getDeptLeader(params).then(response => {
                    this.getDeptLeaders = response.rows;

                }).catch(error => {

                });
                this.dialogTableVisible = true;
            }
            ).catch(error => {
                this.$modal.closeLoading();
            })

        },
        cancelDialog() {
            this.dialogTableVisible = false;
        },
        reset() {
            this.form = {
                pageNum: 1,
                pageSize: 10,
                competitionName: "",
                organizer: "",
                awardsName: "",
                competentDeptId: null,
                awardsLevel: "",
                deptDirectorId: null,
                awardsTime: "",
                awardsType: "",
                remark: "",
                schoolAccessoryList: [],

            },
                this.schoolAccessoryList = [],
                this.resetForm('form')
        },
        handleExamine(row) {
            this.open = true;
            const id = row.id || this.ids;
            getAwards(id).then((response) => {
                this.form = response.data;
                this.form.id = response.data.id;
                console.log(this.form.id, ' this.form.id ');
                this.isEdit = true,
                    this.title = "审核信息"
                this.accessoryUrl = this.pev + this.picUrl
                this.form.competentDeptId = response.data.competentDeptId;
                const params = {
                    competentDeptId: this.form.competentDeptId
                }
                getDeptLeader(params).then(response => {
                    this.getDeptLeaders = response.rows;
                }).catch(error => {
                    this.$modal.closeLoading();
                });

            }
            ).catch(error => {
                this.$modal.closeLoading();
            })
        },
        // 同意
        handleAgree() {
            const params = {
                id: this.form.id,
                auditState: '2'  // 表示同意
            };
            subApply(params).then(({ code }) => {
                console.log(this.form, 'this.form');
                if (code == 200) {
                    this.$modal.msgSuccess('操作成功')
                    this.open = false;
                    this.getList()
                }
            })
        },

        // 不同意
        handleDisagree() {
            const params = {
                id: this.form.id,
                auditState: '3'  // 表示不同意
            };
            subApply(params).then(({ code }) => {
                console.log(this.form, 'this.form');
                if (code == 200) {
                    this.$modal.msgSuccess('操作成功')
                    this.open = false
                    this.getList()
                }
            })
        },


        // 删除
        handleDelete(row) {
            this.$modal.confirm(`是否确认删除此数据？`).then(() => {
                this.loading = true;
                return delAwards(row.id);
            }).then(() => {
                this.getList();
                this.loading = false;
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
                this.loading = false
            });
        },

        // 移除图片
        handleRemove(index) {
            this.form.schoolAccessoryList.splice(index, 1);
        },
        // 上传成功回调
        handleAvatarSuccess(response, file) {
            console.log('response', response);
            console.log('file', file);
            // 处理上传成功的逻辑
            const picUrl = response.fileName; // 假设响应中包含了图片的访问URL
            const accessoryName = response.originalFilename; // 获取上传文件的名称
            this.form.schoolAccessoryList.push({
                // url: this.pev + picUrl,
                accessoryUrl: picUrl,
                accessoryName: accessoryName
            });
            console.log('this.form.schoolAccessoryList', this.form.schoolAccessoryList);
        },

        // 上传前格式和图片大小限制
        beforeAvatarUpload(file) {
            const type = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!type) {
                this.$message.error('图片格式不正确!(只能包含jpg，png，webp，JPEG)')
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return type && isLt2M
        },
        //查询列表
        getList() {
            listAwards(this.queryForm).then(response => {
                this.tableData = response.rows;
                console.log('response', response);
                this.total = response.total;
                this.loading = false;
            })
                .catch(error => {
                    this.loading = false;
                    console.log(error);
                });
        },
        // 获取组织机构
        getDeptTree() {
            getdeptTree().then(response => {
                this.deptOptions = response.data;
                console.log(this.deptOptions, ' this.deptOptions ');
            });
        },
        // 当选择组织机构后触发的方法
        deptIdAndName(node) {
            console.log(node, 'node');
            this.form.competentDeptId = node.id;
            this.getLeader(this.form.competentDeptId); // 调用获取部门主任的方法并传递选中的组织机构id
        },

        getLeader(competentDeptId) {
            getDeptLeader({ competentDeptId }).then(response => {
                this.getDeptLeaders = response.rows;
                console.log(response.rows, 'response.rows');
                console.log(this.getDeptLeaders, 'getDeptLeaders');
            }).catch(error => {
                console.error('Error while fetching department leaders: ' + error);
            });
        },

        resetQuery() {
            this.queryForm = {
                pageNum: 1,
                pageSize: 10,
                awardsLevel: "",
                awardsType: "",
                startTime: "",
                endTime: "",
                competentDeptId: null,

            },
                this.schoolAccessoryList = [],
                this.getList();
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('/school/awards/exportYtg', {
                ...this.queryForm
            }, `获奖管理_${Date.now()}.xlsx`)

        },
        //确定按钮
        submitForm: function () {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateAwards(this.form).then(({ code }) => {
                            console.log(this.form, 'this.form');
                            if (code == 200) {
                                this.$modal.msgSuccess('修改成功')
                                this.dialogTableVisible = false
                                this.getList()
                            }
                        }).catch(() => {
                            this.$modal.msgError("修改失败");
                        });
                    } else {
                        addawards(this.form).then(response => {
                            console.log(this.form, 'this.form');
                            this.$modal.msgSuccess('新增成功')
                            this.dialogTableVisible = false
                            this.getList()
                        }).catch(() => {
                            this.$modal.msgError("新增失败");
                        });
                    }
                }
            });
        },


    },
}
</script>

<style lang="scss" scoped>
.mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
}

.mask-content {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #1a74be;
    font-size: 16px;
}

.custom-blue-button {
    background: #409eff;
    /* 蓝色 */
    border-color: #409eff;
    /* 也可以设置边框颜色 */
    color: #fff;
    /* 按钮文字颜色 */
}
</style>