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

		<view class="top-wrapper">
			<view class="tab-bar">
				<view class="tab-item" :class="{ active: activeTab === 'mine' }" @click="switchTab('mine')">我的工单</view>
				<view class="tab-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">全部工单</view>
				<view class="tab-item" :class="{ active: activeTab === 'plan' }" @click="switchTab('plan')"  >计划</view>
			</view>
			<uni-section>
				<uni-easyinput prefixIcon="search" style="width: 460rpx" v-model="keyWord" :placeholder="
            activeTab === 'plan'
              ? '计划单号，计划名称，记录规则名称'
              : '工单单号，计划单号，记录规则名称'
          ">
				</uni-easyinput>
			</uni-section>
			<button class="search_btn" @click="doSearch">搜索</button>
		</view>
		<div style="height: 180rpx; 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="
              activeTab === 'all'
                ? []
                : activeTab === 'plan'
                  ? planBtnList
                  : btnList
            " :columns="activeTab === 'plan' ? planColumns : columns" :title="item.code || item.planCode" :status="
              activeTab === 'plan'
                ? planStatusMap[item.status]
                : statusMap[item.status]
            " :showDetail="activeTab !== 'plan'" @goDetail="goDetail(item, 'view')"
						@openRedeployOther="openRedeployOther(item)" @edit="goDetail(item, 'edit')"
						@dispatch="handleDispatch(item)" @dispatchAll="handleDispatchAll(item)"
						@revoke="handleRevoke(item)">
					</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>
		<workOrderReport ref="workOrderReportRef" :pageName="pageName" @refresh="successInit"></workOrderReport>
		<Assign ref="Assign" @refresh="successInit"></Assign>
		<batchRevokeDialog ref="batchRevokeDialogRef" @refresh="successInit" :pageName="pageName"></batchRevokeDialog>

		<u-popup :show="dispatchAllShow" mode="bottom" :round="20" @close="dispatchAllShow = false">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">批量派单</text>
					<view class="close-btn" @click="dispatchAllShow = false">×</view>
				</view>
				<view class="popup-body">
					<view class="form-item">
						<text class="form-label">派单次数 <text class="required">*</text></text>
						<uni-easyinput v-model="dispatchQuantity" type="number" placeholder="请输入派单次数" />
					</view>
				</view>
				<view class="popup-footer">
					<u-button type="default" @click="dispatchAllShow = false">取消</u-button>
					<u-button type="primary" @click="submitDispatchAll">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import dictMixns from "@/mixins/dictMixins";
	import myCard from "./components/myCard.vue";
	import Assign from "./components/Assign.vue";
	import workOrderReport from "./components/workOrderReport.vue";
	import batchRevokeDialog from "./components/batchRevokeDialog.vue";
	import {
		producetaskrulerecordQueryRecordWorkOrderPage,
		recordrulesplanPage,
		recordrulesplanRevoke,
		dispatchRepeatedly,
		recordrulesplanManualDispatchOrder,
		getRecordRulesPlanDetail
	} from "@/api/recordRules/index";
	export default {
		components: {
			myCard,
			workOrderReport,
			batchRevokeDialog,
			Assign,
		},
		mixins: [dictMixns],
		props: {
			pageName: {
				default: "",
			},
		},
		data() {
			return {
				dispatchAllData:null,
				dispatchAllShow: false,
				dispatchQuantity: "",
				statusMap: {
					0: "未报工",
					1: "执行中",
					2: "已执行",
				},
				planStatusMap: {
					0: "未派单",
					2: "执行中",
					3: "已完成",
					4: "已撤回",
				},
				planTypeList: {
					productionRecords: 2,
					steamInjectionInspectionRecord: 3,
					solidWasteRecord: 4,
					qualityTestRecords: 5,
					boilerOperationRecord: 6,
					QualityInspection: 7,
					HaulSlag: 8,
					TransportAsh: 9,
				},
				btnList: [{
						name: "报工",
						apiName: "edit",
						btnType: "primary",

						judge: [{
							key: "status",
							value: [1],
						}, ],
					},
					{
						name: "转派",
						apiName: "openRedeployOther",
						btnType: "primary",

						judge: [{
							key: "status",
							value: [1],
						}, ],
					},
				],
				planBtnList: [{
						name: "派单",
						apiName: "dispatch",
						btnType: "primary",
						judge: [{
							fn: (row) =>
								row.dispatchType == 1 || (row.status != 2 && row.status != 3),
						}, ],
					},
					{
						name: "批量派单",
						apiName: "dispatchAll",
						btnType: "primary",
						judge: [{
							fn: (row) => row.dispatchType == 1,
						}, ],
					},
					{
						name: "撤回",
						apiName: "revoke",
						btnType: "warning",
						judge: [{
							fn: (row) => row.status == 2,
						}, ],
					},
				],
				columns: [
					[{
						label: "计划单号：",
						prop: "planCode",
						className: "perce100",
					}, ],
					[{
						label: "记录规则名称：",
						prop: "ruleName",
						className: "perce100",
					}, ],
					[{
						label: "场站名称：",
						className: "perce100",
						prop: "productLineName",
					}, ],
					[{
						className: "perce100",
						label: "班组：",
						prop: "teamName",
					}, ],
					[{
						label: "工单生成时间：",
						className: "perce100",
						prop: "createTime",
					}, ],
					[{
						label: "检查时间：",
						className: "perce100",
						prop: "checkStartTime",
					}, ],
					[{
						label: "报工时间：",
						className: "perce100",
						prop: "checkFinishTime",
					}, ],
					[{
						label: "执行人：",
						className: "perce100",
						prop: "executeUsers",
						formatter: (row) => {
							if ((row.type == 1 && row.status == 2) || row.type != 1) {
								return (
									row.executeUsers &&
									row.executeUsers.map((i) => i.userName).join(",")
								);
							}
						},
					}, ],
					[{
							label: "客户：",
							prop: "contactName",
							className: "perce100",
							isNone:
								!["productionRecords", "qualityTestRecords"].includes(
									this.pageName,
								) || this.pageName == "boilerOperationRecord",
						},
						{
							label: "供应商：",
							prop: "supplierName",
							className: "perce100",
							isNone: [
								"productionRecords",
								"qualityTestRecords",
								"boilerOperationRecord",
							].includes(this.pageName),
						},
					],
					[{
						label: "操作：",
						prop: "action",
						type: "action",
						className: "perce100",
					}, ],
				].filter((item) => !item.isNone),
				planColumns: [
					[{
						label: "计划名称：",
						prop: "name",
						className: "perce100",
					}, ],
					[{
						label: "记录规则名称：",
						prop: "ruleName",
						className: "perce100",
					}, ],
					[{
						label: "场站名称：",
						prop: "productLineName",
						className: "perce100",
					}, ],
					[{
						label: "班组：",
						prop: "teamName",
						className: "perce100",
					}, ],
					[{
						label: "部门：",
						prop: "groupNames",
						className: "perce100",
						formatter: (row) => [
							...new Set(
								(row.executeUsers || [])
								.map((i) => i.groupName)
								.filter((i) => i),
							),
						].join(","),
					}, ],
					[{
						label: "负责人：",
						prop: "userNames",
						className: "perce100",
						formatter: (row) =>
							(row.executeUsers || []).map((i) => i.userName).join(","),
					}, ],
					[{
						label: "记录对象：",
						prop: "recordObject",
						className: "perce100",
						formatter: (row) =>
							row.associatedObject == 1 ? row.workshopName : row.deviceName,
					}, ],
					[{
						label: "派单类型：",
						prop: "dispatchTypeText",
						className: "perce100",
						formatter: (row) => (row.dispatchType ? "多次" : "单次"),
					}, ],
					[{
						label: "状态：",
						prop: "statusText",
						className: "perce100",
						formatter: (row) => this.planStatusMap[row.status] || "",
					}, ],
					[{
						label: "创建人：",
						prop: "createUserName",
						className: "perce100",
					}, ],
					[{
						label: "创建时间：",
						prop: "createTime",
						className: "perce100",
					}, ],
					[{
						label: "操作：",
						prop: "action",
						type: "action",
						className: "perce100",
					}, ],
				],

				tableList: [],
				page: 1,
				size: 10,
				isEnd: false,
				keyWord: "",
				userInfo: {},
				activeTab: "mine",
			};
		},
		computed: {
			getTitle() {
				return this.pageName == "productionRecords" ?
					"生产记录" :
					this.pageName == "steamInjectionInspectionRecord" ?
					"注汽检查记录" :
					this.pageName == "solidWasteRecord" ?
					"固废记录" :
					this.pageName == "qualityTestRecords" ?
					"质量检查检测记录" :
					this.pageName == "HaulSlag" ?
					"拉渣记录表" :
					this.pageName == "TransportAsh" ?
					"拉灰记录表" :
					this.pageName == "QualityInspection" ?
					"来煤质检记录" :
					"锅炉运行记录";
			},
		},
		created() {
			this.requestDict("记录规则类型");
		},
		onLoad() {},

		methods: {
			goDetail(item, type) {
				console.log(item, "item");
				this.$refs.workOrderReportRef.open(item, type);
			},
			openRedeployOther(row) {
				this.$refs.Assign.open(row);
			},
			switchTab(tab) {
				if (this.activeTab === tab) return;
				this.activeTab = tab;
				this.isEnd = false;
				this.page = 1;
				this.tableList = [];
				this.getList();
			},

			successInit() {
				uni.showLoading({
					title: "加载中",
				});

				if (this.activeTab === "plan") {
					let data = {
						pageNum: 1,
						size: this.tableList.length,
						keyword: this.keyWord,
						planType: this.planTypeList[this.pageName],
					};
					recordrulesplanPage(data)
						.then((res) => {
							this.tableList = res.list;
						})
						.then(() => {
							uni.hideLoading();
						});
					return;
				}

				let data = {
					pageNum: 1,
					size: this.tableList.length,
					keyword: this.keyWord,
					planType: this.planTypeList[this.pageName],
				};
				if (this.activeTab === "mine") {
					data.currentLoginUserId = this.userInfo.userId;
				}

				producetaskrulerecordQueryRecordWorkOrderPage(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: "加载中",
				});

				if (this.activeTab === "plan") {
					let data = {
						pageNum: this.page,
						size: this.size,
						keyword: this.keyWord,
						planType: this.planTypeList[this.pageName],
					};
					recordrulesplanPage(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();
						});
					return;
				}

				let data = {
					pageNum: this.page,
					size: this.size,
					keyword: this.keyWord,
					planType: this.planTypeList[this.pageName],
				};
				if (this.activeTab === "mine") {
					data.currentLoginUserId = this.userInfo.userId;
				}

				producetaskrulerecordQueryRecordWorkOrderPage(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();
			},
			async handleDispatch(item) {
				try {
					const data = await getRecordRulesPlanDetail(item.id)
					await recordrulesplanManualDispatchOrder(data)
					this.$refs.uToast.show({
						type: "success",
						icon: false,
						message: `派单成功`,
					});
					this.successInit();
				} catch (error) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `派单失败`,
					});
				}

			},
			async handleDispatchAll(item) {
				this.dispatchAllData = await getRecordRulesPlanDetail(item.id)
				this.dispatchQuantity = ""
				this.dispatchAllShow = true
			},
			async submitDispatchAll() {
				if (!this.dispatchQuantity || Number(this.dispatchQuantity) <= 0) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `请输入派单次数`,
					});
					return;
				}
				try {
					const body = {
						...this.dispatchAllData,
						dispatchQuantity: Number(this.dispatchQuantity)
					};
					await dispatchRepeatedly(body);
					this.$refs.uToast.show({
						type: "success",
						icon: false,
						message: `批量派单成功`,
					});
					this.dispatchAllShow = false;
					this.successInit();
				} catch (error) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `批量派单失败`,
					});
				}
			},
			async revoke(id) {
				await recordrulesplanRevoke({
					id
				});
				this.successInit();
			},
			handleRevoke(item) {
				if (item.dispatchType == 1) {
					// 多次派单，打开批量撤回弹窗
					this.$refs.batchRevokeDialogRef.open(item.code);
				} else {
					this.revoke(item.id);
				}
			},
		},
	};
</script>

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

	// .wrapper{

	// }
	.top-wrapper {
		background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		width: 750rpx;
		padding: 16rpx 32rpx;
		align-items: center;
		position: absolute;
		z-index: 999;

		.tab-bar {
			display: flex;
			width: 100%;
			margin-bottom: 16rpx;
			border-bottom: 2rpx solid #eee;
		}

		.tab-item {
			flex: 1;
			text-align: center;
			padding: 16rpx 0;
			font-size: 30rpx;
			color: #666;
			position: relative;

			&.active {
				color: $theme-color;
				font-weight: bold;

				&::after {
					content: "";
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 60rpx;
					height: 4rpx;
					background: $theme-color;
					border-radius: 4rpx;
				}
			}
		}

		/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;
		}
	}

	.popup-content {
		width: 100vw;
		height: 60vh;
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #e5e5e5;

		.popup-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}

		.close-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 60rpx;
			color: #999;
			line-height: 1;
		}
	}

	.popup-body {
		flex: 1;
		padding: 28rpx;
	}

	.form-item {
		margin-bottom: 24rpx;

		.form-label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 16rpx;
			display: block;

			.required {
				color: #ff4d4f;
			}
		}
	}

	.popup-footer {
		display: flex;
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #e5e5e5;
		gap: 20rpx;

		/deep/ .u-button {
			flex: 1;
		}
	}
</style>