<template>
	<view class="mainBox">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="手动集抄" @clickLeft="back">
			<template slot="right">
				<u-button type="success" size="small" class="u-reset-button" @click="$refs.treePicker._show()"
					text="选择分类"></u-button>
			</template>
		</uni-nav-bar>

		<view class="top-wrapper">
			<uni-section>

				<zxz-uni-data-select :localdata="energyConsumingUnitList" v-model="energyClassificationCode"
					dataValue='value' style="width: 500rpx;" dataKey="label" filterable
					format='{label}'></zxz-uni-data-select>
			</uni-section>
			<button class="search_btn" @click="doSearch">搜索</button>
		</view>
		<div style="height: 100rpx; width: 475rpx"></div>
		<view class="wrapper">
			<u-list @scrolltolower="scrolltolower" class="listContent">
				<view v-for="(item, index) in tableList" :key="index" style="position: relative">
					<myCard :item="item" :index="index + 1" :btnList="btnList" :columns="columns" :title="item.code"
						:status="statusMap[item.status]" @goDetail="goDetail(item, 'view')"
						@handlePublish="handlePublish(item, 1)" @handleDelete="handleDelete(item)"
						@handleSubmit="handleSubmit(item)" @edit="goDetail(item, 'edit')">
					</myCard>
				</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="暂无数据"> </u-empty>
				</view>
			</u-list>
		</view>

		<u-toast ref="uToast"></u-toast>
		<ba-tree-picker ref="treePicker" :multiple="false" @select-change="confirm" :localdata="listData" valueKey="id"
			textKey="name" childrenKey="children" />
		<workOrderReport ref="workOrderReportRef" :pageName="pageName" @refresh="successInit"></workOrderReport>
		<view class="add" @click="goDetail({},'add')">
			<u-icon name="plus" color="#fff"></u-icon>
		</view>
	</view>
</template>

<script>
	import dictMixns from "@/mixins/dictMixins";
	import myCard from "./components/myCard.vue";
	import {
		getTreeByPid
	} from "@/api/classifyManage";
	import workOrderReport from "./components/workOrderReport.vue";
	import {
		getList,
		deleteById,
		updatePublishStatus
	} from "@/api/centralizedMeterReading/index";
	import {
		parameterGetByCode
	} from '@/api/mainData/index.js'
	import {
		energyConsumingUnitList
	} from '@/enum/dict.js';
	import {
		processInstanceCreateAPI,
		processInstancePage
	} from '@/api/wt/index.js'
	export default {
		components: {
			myCard,
			workOrderReport,
		},
		mixins: [dictMixns],
		props: {
			pageName: {
				default: "",
			},
		},
		data() {
			return {
				statusMap: {
					0: "未报工",
					1: "执行中",
					2: "已执行",
				},
				energyConsumingUnitList,
				planTypeList: {
					productionRecords: 2,
					steamInjectionInspectionRecord: 3,
					solidWasteRecord: 4,
					qualityTestRecords: 5,
					boilerOperationRecord: 6,
				},

				columns: [
					[{
						prop: "substanceName",
						label: "表计设备名称",
						className: "perce100",
					}, ],
					[{
						prop: "currentMeterReadingTime",
						label: "本期抄表时间",
						className: "perce100",
					}, ],
					[{
							prop: "currentMeterReadingNum",
							label: "本期抄表数",
							className: "perce50",
						},
						{
							prop: "unit",
							label: "单位",
							className: "perce50",
						},
					],

					[{
						prop: "meterReadingName",
						label: "抄表人",
						className: "perce100",
					}, ],
					[{
						prop: "meterEquipmentNumber",
						label: "表计设备编号",
						className: "perce100",
					}, ],
					[{
						prop: "meterType",
						label: "表计类型",
						className: "perce100",

						formatter: (_row) => {
							return this.getDictValue("表计类型", _row.meterType);
						},
					}, ],
					[{
						prop: "correlationSubstanceName",
						label: "关联设备",
						className: "perce100",
					}, ],
					[{
						prop: "areaName",
						label: "区域",
						className: "perce100",
					}, ],
					[{
						prop: "energyClassificationName",
						label: "用能分类",
						className: "perce100",
					}, ],
					[{
						prop: "energyTypeName",
						label: "能源名称",
						className: "perce100",
					}, ],
					[{
							prop: "approvalStatus",
							label: "审核状态",
							className: "perce50",
							formatter: (row) => {
								const reviewStatus = {
									0: "未提交",
									1: "审核中",
									2: "已审核",
									3: "审核不通过",
								};
								return reviewStatus[row.approvalStatus];
							},
						},
						{
							prop: "publishStatus",
							label: "发布状态",
							className: "perce50",
							formatter: (_row, _column, cellValue) => {
								return _row.publishStatus == 1 ?
									"已发布" :
									_row.publishStatus == 2 ?
									"已撤销" :
									"未发布";
							},
						},
					],
					[{
						label: "操作：",
						prop: "action",
						type: "action",
						className: "perce100",
					}, ],
				].filter((item) => !item.isNone),
				listData: [],
				tableList: [],
				categoryLevelId: '',
				energyClassificationCode: '',
				page: 1,
				size: 10,
				isEnd: false,
				keyWord: "",
				userInfo: {},
				approval: '1',
			};
		},
		computed: {
			btnList() {
				return [{
						name: "编辑",
						apiName: "edit",
						btnType: "primary",
						judge: [{
							fn: (item) => {
								return (
									[0, 3].includes(item.approvalStatus) &&
									item.publishStatus != 1
								);
							},
						}, ],
					},
					{
						name: "提交",
						apiName: "handleSubmit",
						btnType: "primary",
						judge: [{
							fn: (item) => {
								return (
									this.approval == 1 && [0, 3].includes(item.approvalStatus) && item
									.publishStatus != 1
								);
							},
						}, ],
					},
					{
						name: "删除",
						apiName: "handleDelete",
						btnType: "danger",
						judge: [{
							fn: (item) => {
								return (
									item.publishStatus != 1 && [0].includes(item.approvalStatus)
								);
							},
						}, ],
					},
					{
						name: "发布",
						apiName: "handlePublish",
						btnType: "primary",
						judge: [{
							fn: (item) => {
								return (
									item.publishStatus == 0 &&
									this.approval != 1
								);
							},
						}, ],
					},
				];
			},
		},
		created() {
			//用能集抄人工录入审批：0不审批，1审批

			parameterGetByCode({
				code: 'ems_manual_entry_for_approval'
			}).then((res) => {
				if (res.value) {
					this.approval = res.value;
				}
			});
			this.requestDict("表计类型");
			getTreeByPid('29').then((res) => {
				this.listData = res.data;

			});
		},
		onLoad() {},

		methods: {

			confirm(data, name) {
				if (data[0]) {
					this.categoryLevelId = data[0].id
				} else {
					this.categoryLevelId = ''
				}


				this.doSearch()
			},
			goDetail(item, type) {
				this.$refs.workOrderReportRef.open(item, type);
			},
			handleDelete(row) {
				deleteById([row.id]).then((res) => {
					uni.showLoading({
						title: "删除成功",
					});
					this.successInit()
				});
			},

			async handleSubmit(row) {
				try {
					//后台不提供接口
					let list = await processInstancePage({
						pageNo: 1,
						pageSize: 1,
						reset: true,
						key: 'ems_remote_meter_reading'
					})
					let params = {
						businessId: row.id,
						businessKey: 'ems_remote_meter_reading',
						formCreateUserId: row.createUserId,
						processDefinitionId: list?.list[0]?.processDefinition.id,
						variables: {
							businessCode: row.substanceCode,
							businessName: row.substanceName,
							businessType: '人工录入抄表'
						},
					}

					await processInstanceCreateAPI(params)
					uni.showModal({
						title: `提交成功`,
						content: '',
						confirmText: '确认',
						showCancel: false, // 是否显示取消按钮，默认为 true
						success: () => {
							this.successInit()
						}
					})
				} catch {

				}
			},
			// 发布/撤销
			handlePublish(row, status) {
				updatePublishStatus(row.id, status).then(() => {

					uni.showLoading({
						title: "发布成功",
					});
					this.successInit()
				});
			},
			successInit() {
				uni.showLoading({
					title: "加载中",
				});
				let data = {
					pageNum: 1,
					size: this.tableList.length,
					keyword: this.keyWord,
					areaId: "",
					categoryLevelId: this.categoryLevelId,
					meterReadingMethod: 1,
					currentLoginUserId: this.userInfo.userId,
					energyClassificationCode: this.energyClassificationCode
				};
				getList(data)
					.then((res) => {
						this.tableList = res.list;
					})
					.then(() => {
						uni.hideLoading();
					});
			},
			doSearch() {
				this.isEnd = false;
				this.page = 1;
				this.getList();
			},
			//获取列表信息
			getList() {
				this.userInfo = uni.getStorageSync("userInfo");
				if (this.isEnd || !this.userInfo.userId) {
					return;
				}
				uni.showLoading({
					title: "加载中",
				});
				let data = {
					pageNum: this.page,
					size: this.size,
					keyword: this.keyWord,
					areaId: "",
					categoryLevelId: this.categoryLevelId || '',
					meterReadingMethod: 1,
					currentLoginUserId: this.userInfo.userId,
					energyClassificationCode: this.energyClassificationCode
				};

				getList(data)
					.then((res) => {
						if (this.page === 1) {
							this.tableList = res.list;
						} else {
							this.tableList.push(...res.list);
						}
						this.page += 1;
						this.isEnd = this.tableList.length >= res.count;
					})
					.then(() => {
						uni.hideLoading();
					});
			},
			scrolltolower() {
				if (this.isEnd) {
					return;
				}
				this.getList();
			},
		},
	};
</script>

<style lang="scss" scoped>
	.mainBox {
		background-color: #f3f8fb;
	}

	.add {
		width: 96rpx;
		height: 96rpx;
		border-radius: 48rpx;
		background: #3c9cff;
		position: fixed;
		bottom: 100rpx;
		right: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.top-wrapper {
		background-color: #fff;
		display: flex;
		width: 750rpx;
		height: 88rpx;
		padding: 16rpx 32rpx;
		align-items: center;
		// gap: 16rpx;
		position: absolute;
		z-index: 999;
		// top: 44px;
		// // #ifdef APP-PLUS
		// top: 140rpx;

		// // #endif
		/deep/.uni-section {
			margin-top: 0px;
		}

		/deep/.uni-section-header {
			padding: 0px;
		}

		.search_btn {
			width: 120rpx;
			height: 70rpx;
			line-height: 70rpx;
			padding: 0 24rpx;
			background: $theme-color;
			font-size: 32rpx;
			color: #fff;
			margin: 0;
			margin-left: 26rpx;
		}

		.menu_icon {
			width: 44rpx;
			height: 44rpx;
			margin-left: 14rpx;
		}
	}
</style>