<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-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="比赛名称" />
            <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="部门主任" />
            <el-table-column align="center" prop="organizer" label="主办单位" />
            <el-table-column align="center" prop="awardsTime" label="获奖时间" />
            <el-table-column align="center" prop="证书图片" label="证书图片">
                <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_state1, row.auditState) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="remark" label="备注" />
            <el-table-column align="center" fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                    <div>
                        <div v-if="scope.row.auditState === '0' || scope.row.auditState === '3'">
                            <el-button @click="handleExamine(scope.row)" type="text" size="small">提交</el-button>
                            <el-button @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
                            <el-button @click="handleLook(scope.row)" type="text" size="small">查看</el-button>
                            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
                        </div>
                        <div v-else>
                            <el-button @click="handleLook(scope.row)" type="text" size="small">查看</el-button>
                        </div>
                    </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="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入" clearable type="textarea" :rows="2"
                                :style="{ width: '100%' }"></el-input>
                        </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" :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" :rules="rules" :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" />
                        </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="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入" clearable type="textarea" :rows="2"
                                :style="{ width: '100%' }"></el-input>
                        </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" :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="cancelDialog"> 取 消 </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_state1'],
    data() {
        return {
            isEdit: false,
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
            queryForm: {
                pageNum: 1,
                pageSize: 10,
                awardsLevel: "",
                awardsType: "",
                startTime: "",
                endTime: "",
                competentDeptId: null,

            },
            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" }
                ],

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

    methods: {
        handleAdd() {
            this.reset();
            this.dialogTableVisible = true;
        },

        handleLook(row) {
            console.log(row);
            const id = row.id || this.ids;
            getAwards(id).then((response) => {
                this.form = response.data;
                this.isEdit = true;
                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.open = true;
            }
            ).catch(error => {
                this.$modal.closeLoading();
            })

        },
        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;
            this.open = 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) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm("是否提交该信息？")
                .then(function () {
                    const params = {
                        id: row.id,
                        auditState: '1'  // 表示同意
                    };
                    return subApply(params);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("提交成功");
                })
                .catch((err) => {
                    console.error(err);
                });
        },

        // 删除
        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() {
            listAwardsgr(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 => { // 使用 ES6 简写对象字面量
                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();
        },
        //确定按钮
        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 {
                        addawardsgr(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>
.custom-blue-button {
    background: #409eff;
    /* 蓝色 */
    border-color: #409eff;
    /* 也可以设置边框颜色 */
    color: #fff;
    /* 按钮文字颜色 */
}
</style>