<template>
	<div>
		<el-container>
			<el-main>
				<el-form :inline="true" :model="formInline" class="demo-form-inline">
					<el-form-item>
						<el-date-picker size="small" v-model="formInline.startDate" align="right" type="date" placeholder="选择日期" :value-format="'yyyy-MM-dd'" :picker-options="pickerOptions"></el-date-picker>
					</el-form-item>

					<el-form-item>
						<el-input size="small" clearable v-model="formInline.orderNo" placeholder="请输入订单号" @keydown.enter.native="redPackagePage"></el-input>
					</el-form-item>

					<el-form-item>
						<el-input size="small" clearable v-model="formInline.nickName" placeholder="请输入用户昵称" @keydown.enter.native="redPackagePage"></el-input>
					</el-form-item>

					<el-form-item>
						<el-input size="small" clearable v-model="formInline.myAmountStart" placeholder="请输入最小金额" @keydown.enter.native="redPackagePage"></el-input>
					</el-form-item>

					<el-form-item>
						<el-input size="small" clearable v-model="formInline.myAmountEnd" placeholder="请输入最大金额" @keydown.enter.native="redPackagePage"></el-input>
					</el-form-item>

					<el-form-item>
						<el-select size="small" v-model="formInline.itemType" placeholder="请选择红包类型" @change="redPackagePage">
							<el-option v-for="type in itemType" :key="type" :label="type" :value="type"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item>
						<el-select size="small" v-model="formInline.msg" placeholder="请选择当前状态" @change="redPackagePage">
							<el-option v-for="type in msg" :key="type" :label="type" :value="type"></el-option>
						</el-select>
					</el-form-item>
					<br>
					<el-form-item>
						<el-button size="small" type="primary" @click="redPackagePage">查询</el-button>
					</el-form-item>

					<el-form-item>
						<el-button size="small" type="primary" @click="prepareGetToday">今日所得</el-button>
						<el-dialog v-loading="loading" title="今日所得查询" :visible.sync="getTodayDialogVisible" style="width: 100%">
							<el-form :model="form" class="custom-form">
								<el-form-item label="今日所得" class="form-item">
									<el-input v-model="form.todayGet" autocomplete="off" style="width: 100%"></el-input>
								</el-form-item>
								<el-form-item label="累计所得" class="form-item">
									<el-input v-model="form.allGet" autocomplete="off" style="width: 100%"></el-input>
								</el-form-item>
							</el-form>

							<div slot="footer" class="dialog-footer">
								<el-button @click="getTodayDialogVisible = false">取 消</el-button>
								<el-button type="primary" @click="getToday">查 询</el-button>
							</div>
						</el-dialog>
					</el-form-item>

					<el-form-item>
						<el-button size="small" type="primary" @click="prepareViewCountAll">浏览量</el-button>
						<el-dialog title="提示" :visible.sync="viewCountAllDialogVisible" width="30%" :before-close="handleClose">
							<span>确认处理浏览量吗?</span>
							<span slot="footer" class="dialog-footer">
								<el-button @click="viewCountAllDialogVisible = false">取 消</el-button>
								<el-button type="primary" @click.prevent="viewCountAll()">确 定</el-button>
							</span>
						</el-dialog>
					</el-form-item>

					<el-form-item>
						<el-button size="small" type="primary" @click="prepareDetailsInfo">同步详情</el-button>
						<el-dialog title="提示" :visible.sync="detailsInfoDialogVisible" width="30%" :before-close="handleClose">
							<span>确认同步红包详情吗?</span>
							<span slot="footer" class="dialog-footer">
								<el-button @click="detailsInfoDialogVisible = false">取 消</el-button>
								<el-button type="primary" @click.prevent="getTodayRedPackageDetailInfo()">确 定</el-button>
							</span>
						</el-dialog>
					</el-form-item>

					<el-form-item>
						<el-button size="small" type="primary" @click="newRedPackage">最新红包</el-button>
					</el-form-item>
				</el-form>
				<el-table ref="multipleTable" v-loading="loading" :data="csdnRedPackageList" tooltip-effect="dark" style="width: 100%">
					<el-table-column prop="id" label="序号" width="100" sortable></el-table-column>
					<el-table-column prop="nickName" label="用户昵称" show-overflow-tooltip>
						<template slot-scope="scope">
							<a :href="scope.row.shareUrl" target="_blank">{{ scope.row.nickName }}</a>
						</template>
					</el-table-column>

					<el-table-column prop="orderNo" label="订单号" width="175px" show-overflow-tooltip></el-table-column>

					<el-table-column prop="myAmount" label="我的金额" sortable show-overflow-tooltip>
						<template slot-scope="scope">
							<el-tag :type="getTagType(scope.row.myAmount)">{{ scope.row.myAmount }}</el-tag>
						</template>
					</el-table-column>

					<el-table-column prop="msg" label="详情" show-overflow-tooltip>
						<template slot-scope="scope">
							<el-tag :type="getMsgType(scope.row.msg)">{{ scope.row.msg }}</el-tag>
						</template>
					</el-table-column>

					<el-table-column prop="itemType" label="类型" show-overflow-tooltip></el-table-column>
					<el-table-column prop="viewCount" label="浏览量" show-overflow-tooltip></el-table-column>
					<el-table-column prop="totalAmount" label="总金额" show-overflow-tooltip></el-table-column>
					<el-table-column prop="communityId" label="社区id" show-overflow-tooltip></el-table-column>

					<el-table-column label="创建时间">
						<template slot-scope="props">{{ props.row.createTime | dateFormat }}</template>
					</el-table-column>

					<el-table-column prop="操作" label="操作" width="310">
						<template slot-scope="props">
							<el-button size="small" type="success" @click="dealViewCount(props.row.id)">浏览量</el-button>
							<el-button size="small" type="success" @click="syncDetailInfo(props.row.id)">同步详情</el-button>
							<el-button size="small" type="primary" @click.prevent="preEdit(props.row.id, props.row.nickName, props.row.myAmount, props.row.msg)">编辑</el-button>
							<el-button size="small" type="success" @click.prevent="gotoDetail(props.row.id, props.row.orderNo, props.row.communityId, props.row.postId)">详情</el-button>
							<el-dialog title="编辑红包信息" :visible.sync="editVisible" style="width: 100%">
								<el-form :model="form" class="custom-form">
									<el-form-item label="用户名称" class="form-item">
										<el-input v-model="form.nickName" autocomplete="off" style="width: 100%"></el-input>
									</el-form-item>
									<el-form-item label="我的金额" class="form-item">
										<el-input v-model="form.myAmount" autocomplete="off" style="width: 100%"></el-input>
									</el-form-item>
									<el-form-item label="详细信息" class="form-item">
										<el-select v-model="form.msg" placeholder="请选择" style="width: 100%">
											<el-option v-for="item in msg" :key="item" :label="item" :value="item"></el-option>
										</el-select>
									</el-form-item>
								</el-form>
								<div slot="footer" class="dialog-footer">
									<el-button @click="editVisible = false">取 消</el-button>
									<el-button type="primary" @click="editConfirm">确 定</el-button>
								</div>
							</el-dialog>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[8, 10, 50, 100, 200, 400]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
			</el-main>
			<el-backtop class="backtop"></el-backtop>
		</el-container>
	</div>
</template>

<script>
import axios from 'axios'
import ApiService from '../../api/ApiService'
export default {
    name: 'MyRedPackage',

    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now()
                },
                shortcuts: [
                    {
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date())
                        },
                    },
                    {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() - 3600 * 1000 * 24)
                            picker.$emit('pick', date)
                        },
                    },
                    {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', date)
                        },
                    },
                ],
            },
            form: {
                todayGet: '',
                allGet: '',
                myAmount: '',
                nickName: '',
                msg: '',
            },
            formInline: {
                nickName: '',
                itemType: '',
                myAmount: '',
                msg: '',
                myAmountStart: '',
                myAmountEnd: '',
                startDate: '',
                orderNo: '',
            },
            itemType: ['全部', 'article', 'blink', 'topic'],
            msg: ['全部', 'received', 'completed', 'unreceived', 'uncompleted', '其它'],
            deleteDialogVisible: false,
            editVisible: false,
            viewCountAllDialogVisible: false,
            getTodayDialogVisible: false,
            detailsInfoDialogVisible: false,
            // 用户列表数据
            csdnRedPackageList: [],
            loading: false,
            elementui_page_component_key: 0,
            currentPage: Number(localStorage.getItem('redPackagePage')) || 1,
            pageSize: 10,
            total: 0,
            currentRowId: null,
            currentUserName: null,
        }
    },
    watch: {
        formInline: {
            handler(newVal, oldVal) {
                this.currentPage = 1
                localStorage.setItem('redPackagePage', this.currentPage)
                this.redPackagePage()
            },
            deep: true,
        },
        // 监听currentPage的变化，将新值保存到localStorage中
        currentPage(newPage) {
            localStorage.setItem('redPackagePage', newPage.toString())
        },
    },
    created() {
        //获取问题类型的枚举
        this.$nextTick(() => {
            const foo = this.$route.query.back
            if (foo === 'back') {
                this.currentPage = Number(localStorage.getItem('redPackagePage')) || 1
            } else {
                localStorage.setItem('redPackagePage', 1)
                this.currentPage = 1
            }
            // 调用请求数据的方法
            this.redPackagePage()
        })
    },
    mounted() {
        this.currentPage = Number(localStorage.getItem('redPackagePage')) || 1
        this.elementui_page_component_key++
    },
    methods: {
        prepareViewCountAll() {
            this.viewCountAllDialogVisible = true
        },
        prepareDetailsInfo() {
            this.detailsInfoDialogVisible = true
        },
        prepareGetToday() {
            this.form.todayGet = ''
            this.form.allGet = ''
            this.getTodayDialogVisible = true
        },
        prepareDelete(id) {
            this.currentRowId = id
            this.deleteDialogVisible = true
        },

        preEdit(id, nickName, myAmount, msg) {
            this.form.nickName = nickName
            this.form.myAmount = myAmount
            this.form.msg = msg
            this.currentRowId = id
            this.editVisible = true
        },
        refreshPage() {
            location.reload()
        },
        gotoDetail(id, orderNo, communityId, postId) {
            this.$router.push(`/home/redPackageDetail/${id}/${orderNo}/${communityId}/${postId}`)
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then((_) => {
                    done()
                })
                .catch((_) => {})
        },
        handleConfirm(addType) {
            this.dialogFormVisible = false // 关闭对话框
            this.dialogMutiFormVisible = false
            this.addUser(addType) // 发送请求
        },

        async redPackagePage() {
            this.loading = true
            const { data: res } = await ApiService.redPackagePage(this.currentPage, this.pageSize, this.formInline)
            if (res.code === 200) {
                this.total = res.result.totalElements
                this.csdnRedPackageList = res.result.content
            }
            this.loading = false
        },

        async dealViewCount(id) {
            this.loading = true
            const { data: res } = await ApiService.dealViewCount(id)
            if (res.code === 200) {
                this.redPackagePage()
            } else {
                console.error('Received non-200 status code', res)
            }
            this.loading = false
        },

        async syncDetailInfo(id) {
            this.loading = true
            const { data: res } = await ApiService.syncDetailInfo(id)
            if (res.code === 200) {
                this.redPackagePage()
            } else {
                console.error('Received non-200 status code', res)
            }
            this.loading = false
        },

        async getTodayRedPackageDetailInfo() {
            this.loading = true
            this.detailsInfoDialogVisible = false
            const { data: res } = await ApiService.getTodayRedPackageDetailInfo()
            if (res.code === 200) {
                this.redPackagePage()
            } else {
                console.error('Received non-200 status code', res)
            }
            this.loading = false
        },

        async editConfirm() {
            try {
                this.loading = true
                const { data: res } = await axios.post('http://43.139.90.182:8888/csdn/redPackage/update', {
                    id: this.currentRowId,
                    nickName: this.form.nickName,
                    myAmount: this.form.myAmount,
                    msg: this.form.msg,
                })
                if (res.code === 200) {
                    this.form.nickName = ''
                    this.form.myAmount = ''
                    this.form.msg = ''
                    this.editVisible = false
                    currentRowId: null
                    this.redPackagePage()
                } else {
                    console.error('Received non-200 status code', res)
                }
            } catch (error) {
                console.error('An error occurred while adding the questionName:', error)
                // 异常处理逻辑
            } finally {
                this.loading = false
            }
        },

        async viewCountAll() {
            this.loading = true
            this.viewCountAllDialogVisible = false
            const { data: res1 } = await axios.get('http://43.139.90.182:8888/csdn/redPackage/getViewCountAll')
            if (res1.code === 200) {
                this.redPackagePage()
            } else {
                console.error('Received non-200 status code', res1)
            }
            this.loading = false
        },
        async getToday() {
            const { data: res } = await axios.get('http://43.139.90.182:8888/csdn/redPackage/getMyAmount')
            if (res.code === 200) {
                this.form.todayGet = res.result.todayGet
                this.form.allGet = res.result.allGet
            } else {
                console.error('Received non-200 status code', res)
            }
        },
        async onDelete(id) {
            this.loading = true
            const { data: res } = await axios.get('http://43.139.90.182:8888/csdn/user/delete', {
                params: {
                    id: id,
                },
            })
            this.deleteDialogVisible = false
            this.redPackagePage()
            this.loading = false
        },
        refreshPage() {
            //获取问题类型的枚举
            this.redPackagePage()
            location.reload()
        },
        handleCurrentChange(currentPage) {
            this.currentPage = currentPage
            this.redPackagePage()
        },
        handleSizeChange(currentSize) {
            this.pageSize = currentSize
            this.redPackagePage()
        },

        newRedPackage() {
            // 新页面打开
            window.open('https://bbs.csdn.net/?type=4&header=0&utm_source=wwwtab')
        },
        getTagType(myAmount) {
            if (myAmount >= 0.3) {
                return 'success'
            } else if (myAmount >= 0.2) {
                return 'primary'
            } else if (myAmount >= 0.1) {
                return 'warning'
            } else {
                return 'danger'
            }
        },
        getMsgType(msg) {
            if (msg == 'received' || msg == 'completed') {
                return 'success'
            } else {
                return 'danger'
            }
        },
    },
}
</script>

<style lang="less" scoped>
.el-header {
	background-color: #b3c0d1;
	color: #333;
	line-height: 60px;
}

.el-aside {
	color: #333;
}

.pagination {
	margin-top: 16px;
	text-align: right;
}
.header-button-item {
	margin-right: 15px;
	font-size: 20px;
}

.red-title {
	line-height: 24px;
	font-size: 18px;
	color: red;
}

.backtop {
	position: fixed;
	bottom: 50px;
	right: 50px;
	height: 40px;
	width: 40px;
	line-height: 40px;
	text-align: center;
	border-radius: 20px;
	background-color: #007aff;
	color: #fff;
	cursor: pointer;
	z-index: 999;
}
.custom-textarea {
	width: 100%;
	text-align: left;
}
.backtop:hover {
	background-color: #0050a0;
}
</style>