<template>
	<view class="mainBox">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" :title="navTitle" @clickLeft="back" />

		<!-- 搜索区域 -->
		<view class="top-wrapper">
			<uni-forms :modelValue="where" label-width="100px" class="search-form">
				<uni-forms-item label="处理结果">
					<uni-data-select v-model="where.handleResult" :localdata="resultOptions" placeholder="全部"
						clearable />
				</uni-forms-item>
			</uni-forms>
			<button class="search_btn" @click="handleSearch">搜索</button>
		</view>

		<view class="wrapper">
			<u-list @scrolltolower="scrolltolower" class="listContent">
				<view v-for="(item, idx) in tableList" :key="item.id" style="position: relative">
					<myCard :item="item" :index="idx + 1" :btnList="currentBtnList" :columns="currentColumns"
						:title="item.description" :status="statusMap[item.handleResult]" @goDetail="goDetail"
						@edit="handleEdit(item)" @handleDelete="handleDelete(item)" @handleProcess="handleProcess(item)" />
				</view>
				<view style="width: 100%; height: 40rpx"></view>
				<view style="margin-top: 20vh" v-if="tableList.length == 0">
					<u-empty iconSize="150" textSize="32" text="暂无数据" />
				</view>
			</u-list>
		</view>

		<!-- 新增/编辑/查看/处理弹窗 -->
		<snapshot-dialog ref="snapshotDialog" @reload="reloadList" @rectify="onRectify" @discard="onDiscard" />
		<!-- 废弃弹窗（仅管理模式） -->
		<discard-dialog v-if="mode === 'manage'" ref="discardDialogRef" @confirm="doDiscard" />

		<!-- 新增按钮（仅我的随手拍） -->
		<view v-if="mode === 'my'" class="add" @click="handleAdd">
			<u-icon name="plus" color="#fff"></u-icon>
		</view>
	</view>
</template>

<script>
	import myCard from "@/components/myCard.vue";
	import snapshotDialog from "./snapshotDialog.vue";
	import discardDialog from "./discardDialog.vue";
	import {
		getList,
		remove,
		discard,
		handle
	} from "@/api/snapshot/index.js";

	export default {
		components: {
			myCard,
			snapshotDialog,
			discardDialog
		},
		props: {
			mode: {
				type: String,
				default: "my",
				validator: (v) => ["my", "manage"].includes(v),
			},
		},
		data() {
			return {
				where: {
					handleResult: ""
				},
				resultOptions: [{
						value: 0,
						text: "待处理"
					},
					{
						value: 1,
						text: "下发整改"
					},
					{
						value: 2,
						text: "废弃"
					},
				],
				statusMap: {
					0: "待处理",
					1: "已整改",
					2: "已废弃"
				},
				tableList: [],
				page: 1,
				size: 10,
				isEnd: false,
				userInfo: {},
				currentId: null,
			};
		},
		computed: {
			navTitle() {
				return this.mode === "my" ? "我的随手拍" : "随手拍管理";
			},
			currentColumns() {
				return [
					[{
						prop: "location",
						label: "位置",
						className: "perce100"
					}],
					[{
						prop: "problemDeptName",
						label: "所属部门",
						className: "perce100"
					}],
					[{
						prop: "reporterName",
						label: "上报人",
						className: "perce100"
					}],
					[{
						prop: "createTime",
						label: "上报时间",
						className: "perce100"
					}],
					[{
						prop: "handleResult",
						label: "处理结果",
						className: "perce100",
						formatter: (row) => this.statusMap[row.handleResult],
					}, ],
					[{
						label: "操作：",
						prop: "action",
						type: "action",
						className: "perce100",
					}, ]
				];

			},
			currentBtnList() {
				if (this.mode === "my") {
					return [{
							name: "编辑",
							apiName: "edit",
							btnType: "primary",
							judge: [{
								fn: (item) => item.handleResult === 0
							}],
						},
						{
							name: "删除",
							apiName: "handleDelete",
							btnType: "danger",
							judge: [{
								fn: (item) => item.handleResult === 0
							}],
						},
					];
				} else {
					return [{
						name: "处理",
						apiName: "handleProcess",
						btnType: "primary",
						judge: [{
							fn: (item) => item.handleResult === 0
						}],
					}, ];
				}
			},
		},
		created() {
			this.userInfo = uni.getStorageSync("userInfo") || {};
			this.getList();
		},
		methods: {
			back() {
				uni.navigateBack();
			},

			// 列表查看详情
			goDetail(item) {
				this.$refs.snapshotDialog.open("view", item);
			},

			// 新增（仅 my 模式）
			handleAdd() {
				this.$refs.snapshotDialog.open("add");
			},

			// 编辑（my 模式按钮）
			handleEdit(row) {
				this.$refs.snapshotDialog.open("edit", row);
			},

			// 删除（my 模式按钮）
			async handleDelete(row) {
				const res = await uni.showModal({
					title: "提示",
					content: "确认删除该记录吗？",
				});
				if (res[1].confirm) {
					await remove([row.id]);
					uni.showToast({
						title: "删除成功",
						icon: "success"
					});
					this.reloadList();
				}
			},

			// 处理（manage 模式按钮）
			handleProcess(row) {
				this.$refs.snapshotDialog.open("handle", row);
			},

			// 下发整改（manage 模式）
			onRectify(data) {
				this.currentId = data.id;
				this.$refs.hazardDialogRef &&
					this.$refs.hazardDialogRef.open("add", "", "report", {
						sourceType: 4,
						sourceId: data.id,
						sourceName: "随手拍",
						foundUserName: data.reporterName,
						foundUserId: data.reporterId,
						foundTime: data.createTime,
						description: data.location + data.description,
						reportAttachments: data.attachment,
					});
			},
			doRectify(opinion) {
				handle({
					id: this.currentId,
					handleOpinion: opinion,
					invHazardId: "下发整改",
				}).then(() => {
					uni.showToast({
						title: "下发整改成功",
						icon: "success"
					});
					this.reloadList();
				});
			},

			// 废弃（manage 模式）
			onDiscard(data,type) {
				this.$refs.discardDialogRef.open(data,type);
			},
			doDiscard({
				id,
				handleOpinion
			}) {
				discard({
					id,
					handleOpinion
				}).then(() => {
					uni.showToast({
						title: "废弃成功",
						icon: "success"
					});
					this.reloadList();
				});
			},

			// 通用方法
			reloadList() {
				this.page = 1;
				this.isEnd = false;
				this.getList();
			},
			handleSearch() {
				this.page = 1;
				this.isEnd = false;
				this.getList();
			},
			async getList() {
				if (this.isEnd) return;
				uni.showLoading({
					title: "加载中"
				});
				try {
					const baseData = {
						pageNum: this.page,
						size: this.size,
						handleResult: this.where.handleResult !== "" ?
							this.where.handleResult :
							undefined,
					};
					// 不同模式参数不同
					if (this.mode === "my") {
						baseData.reporterId = this.userInfo.userId;
					}
					const res = await getList(baseData);
					const newList = this.mode === "my" ? res.list || [] : res.list || [];
					if (this.page === 1) this.tableList = newList;
					else this.tableList.push(...newList);
					if (this.mode === "my") {
						this.isEnd = this.tableList.length >= res.count;
					} else {
						this.isEnd = newList.length < this.size;
					}
					this.page += 1;
				} catch (e) {
					console.error(e);
				} finally {
					uni.hideLoading();
				}
			},
			scrolltolower() {
				if (!this.isEnd) this.getList();
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "../common-style.scss";
</style>