<template>
	<!-- 详情 -->
	<view class="detail-container">
		<view class="info">
			<view class="title">
				<view>维修工单</view>
				<view @click="transfer"
					v-if="data.status == 'PECEIVED' && (!serviceList || serviceList && serviceList.length == 0)">转办
				</view>
			</view>
			<view class="dec">
				<view class="dec-item">
					<view>工单单号：</view>
					<view>{{data.number}}</view>
				</view>
				<view class="dec-item">
					<view>报修描述：</view>
					<view>{{data.describes}}</view>
				</view>
				<u-form :model="data" ref="form1" label-width="160rpx"
					style="border-top: 1px solid rgba(220,220,220,0.5);border-bottom: 1px solid rgba(220,220,220,0.5);margin-bottom: 20rpx;"
					v-if="data.status == 'PECEIVED'&& store.post.code == 'worker'">
					<u-form-item label="班次" prop="classes" required>
						<view class="select" @click="openSingleColumn('classes',data.classes,maintenanceShift)">
							<view class="input" v-if='data.classes||data.classes==0'>
								{{data.classesName}}
							</view>
							<view class="placeholder" v-else>
								{{`请选择班次`}}
							</view>
							<u-icon name="arrow-right" color="#aaaaaa" size="28"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="故障类型" prop="classes" required>
						<view class="select" @click="openSingleColumn('faultType',data.faultType,faultType)">
							<view class="input" v-if='data.faultType'>
								{{data.faultTypeName}}
							</view>
							<view class="placeholder" v-else>
								{{`请选择故障类型`}}
							</view>
							<u-icon name="arrow-right" color="#aaaaaa" size="28"></u-icon>
						</view>
					</u-form-item>
				</u-form>
				<view class="dec-item" v-if="data.status != 'PECEIVED'|| store.post.code != 'worker'">
					<view>班次：</view>
					<view>{{data.classesName}}</view>
				</view>
				<view class="dec-item" v-if="data.status != 'PECEIVED'||store.post.code != 'worker'">
					<view>故障类型：</view>
					<view>{{data.faultTypeName}}</view>
				</view>
				<view class="dec-item" v-if="data.createTime">
					<view>创建时间：</view>
					<view>{{$time.formatDate(data.createTime)}}</view>
				</view>
				<view class="dec-item" v-if="data.creator">
					<view>创建人员：</view>
					<view>{{data.creator}}</view>
				</view>
				<view class="dec-item" v-if="data.receivingTime">
					<view>接单时间：</view>
					<view>{{$time.formatDate(data.receivingTime)}}</view>
				</view>

				<view class="dec-item" v-if="data.maintenanceName">
					<view>接单人员：</view>
					<view>{{data.maintenanceName}}</view>
				</view>
				<view class="dec-item" v-if="data.completionTime">
					<view>完成时间：</view>
					<view>{{$time.formatDate(data.completionTime)}}</view>
				</view>
				<view class="dec-item" v-if="data.verifyTime">
					<view>验证时间：</view>
					<view>{{$time.formatDate(data.verifyTime)}}</view>
				</view>
				<view class="dec-item" v-if="data.verifyer">
					<view>验证人员：</view>
					<view>{{data.verifyer}}</view>
				</view>
			</view>
		</view>
		<div class="line"></div>
		<view class="info" style="padding-bottom: 130rpx;">
			<view class="tab">
				<u-tabs :list="list" :is-scroll="false" bar-height="2" bar-width="250" v-model="current"
					@change="change"></u-tabs>
			</view>

			<view>
				<view class="title">
					<view>{{changeItem.name}}</view>
				</view>
				<view class="dec" v-if="changeItem.value == 1">
					<view class="dec-item">
						<view>设备编号：</view>
						<view>{{data.deviceNumber}}</view>
					</view>
					<view class="dec-item">
						<view>设备名称：</view>
						<view>{{data.name}}</view>
					</view>
					<view class="dec-item">
						<view>所属厂区：</view>
						<view>{{data.factoryAreaName}}</view>
					</view>
					<view class="dec-item">
						<view>设备类型：</view>
						<view>{{data.type == 'DEVICE'?'设备':data.type == 'TECH'?'工艺':'模具'}}</view>
					</view>
				</view>
				<view class="dec" v-if="changeItem.value == 2">
					<view class="dec-item">
						<view>报修单号：</view>
						<view>{{data1.number}}</view>
					</view>
					<view class="dec-item">
						<view>报修描述：</view>
						<view>{{data1.describes}}</view>
					</view>
					<view class="dec-item">
						<view>报修人：</view>
						<view>{{data1.declarName}}</view>
					</view>
					<view class="dec-item">
						<view>报修时间：</view>
						<view>{{$time.formatDate(data.createTime)}}</view>
					</view>
					<!-- <view>图片：</view> -->
					<view class="images">
						<image :src="cur" mode="" v-for="(cur,key) in data1.filePathList" :key='key'
							@click="previewImage(key,data1.filePathList)"></image>
					</view>
				</view>
				<view class="list" v-if="changeItem.value == 3">
					<view class="item " v-for="(item,index) in serviceList" :key="index"
						@click="addSubForm('updata',item)">
						<view class="item-box">
							<view class="spare-title">
								<view class="title-txt">
									{{item.describes}}
								</view>
								<u-icon name="trash" color="#aaaaaa" size="40"
									v-if="(data.status == 'PENDING' || data.status == 'PECEIVED')&& store.post.code == 'worker'"
									@click.native.stop="delService(item)"></u-icon>
							</view>
							<view class="dec2">
								<view>故障真因：</view>
								<view>{{item.describes1}}</view>
							</view>
							<view class="dec2">
								<view>解决措施：</view>
								<view>{{item.workOut}}</view>
							</view>
							<view class="dec2">
								<view>维修人员：</view>
								<view>{{item.maintenancesName}}</view>
							</view>
							<view class="" v-show="item.items&&item.items.length>0">
								<view class="dec2">
									备件：
								</view>
								<view class="items" v-for="(cur,key) in item.items" :key="key">
									<view class="items-name">
										{{cur.name}}
									</view>
									<view class="items-dec">
										备件编号：{{cur.number}}
									</view>
									<view class="items-dec">
										数量：{{cur.qty}}
									</view>
								</view>
							</view>
						</view>
						<!-- <u-icon name="minus-circle" color="#aaaaaa" size="60" ></u-icon> -->
					</view>
					<view class="add-btn"
						v-if="(data.status == 'PENDING' || data.status == 'PECEIVED')&& store.post.code == 'worker'">
						<u-button type="primary" @click="addSubForm('creat')"><u-icon name="plus-circle" color="#ffffff"
								size="36"></u-icon>添加维修内容</u-button>
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<view class="btns" v-if="data.status == 'PENDING'&& store.post.code == 'worker'">
				<u-button type="primary" @click="orderClick(1)" :loading='loading' :disabled='loading'>接单</u-button>
			</view>

			<view class="btns" v-if="data.status == 'PECEIVED'&& store.post.code == 'worker'">
				<u-button shape="shape" type="warning" style="min-width: 120rpx;" :loading='loading1' @click="editForm"
					:disabled='loading1'>修改工单</u-button>
				<u-button type="primary" @click="orderClickSuccess()" :loading='loading'
					:disabled='loading'>完成</u-button>
			</view>
			<view class="btns" v-if="data.status == 'COMPLETED'&& store.post.code == 'engineer'">
				<u-button type="primary" @click="orderClick(3)" :loading='loading' :disabled='loading'>验证完结</u-button>
			</view>
			<view style="height: constant(safe-area-inset-bottom); height: env(safe-area-inset-bottom);"></view>
		</view>
		<!-- 完成类型 -->
		<u-popup v-model="isShowSuccess" mode="center" border-radius="14">
			<view class="popup-title">完成类型</view>
			<view class="popup">
				<u-radio-group v-model="result" @change="radioGroupChange">
					<u-radio v-for="(item, index) in orderCompleteResult" :key="index" :name="item.value">
						{{item.label}}
					</u-radio>
				</u-radio-group>
			</view>
			<view class="popup-footer">
				<view @click="isShowSuccess = false">取消</view>
				<view class="sure" @click="sure">确认</view>
			</view>
		</u-popup>
		<view style="height: constant(safe-area-inset-bottom); height: env(safe-area-inset-bottom);"></view>
		<u-select v-model="singleColumnShow" mode="single-column" :default-value='singleColumnDefaultValue'
			:list="singleColumnList" @confirm="chooseSingleColumn"></u-select>
	</view>
</template>

<script setup lang="ts">
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import * as dictApi from "@/api/dict.js"
	import * as repairOrderApi from "@/api/repairOrder.js"
	import { useCountStore } from '@/store'

	const { proxy } = getCurrentInstance()
	// 获取自定义的store
	const store = useCountStore()

	const list = ref([{
		name: '设备信息',
		value: 1
	}, {
		name: '报修信息',
		value: 2
	}, {
		name: '维修内容',
		value: 3
	}])
	const current = ref(0)
	const changeItem = ref({
		name: '设备信息',
		value: 1
	})
	const data = ref()
	const loading = ref(false)
	const loading1 = ref(false)
	const type = ref('')
	const serviceList = ref([])
	const isShowSuccess = ref(false)
	const orderCompleteResult = ref([]) //订单完成类型
	const result = ref('TEMPORARILY')
	const data1 = ref('')

	const singleColumnShow = ref(false)
	const singleColumnDefaultValue = ref([])
	const singleColumnList = ref([])
	const field = ref('')
	const maintenanceShift = ref([])  //班次字典项
	const faultType = ref([])  //故障类型字典项
	function change(index) {
		current.value = index
		changeItem.value = list.value[current.value]
	}
	// 添加表格表单
	function addSubForm(clickType, item) {
		if (data.value.status == 'PENDING') {
			proxy.$modal.showToast('请先接单')
			return
		}
		if (clickType == 'updata') {
			proxy.$tab.navigateTo(
				`/pages/repairOrder/addServiceRecord?type=${type.value}&factoryAreaNumber=${data.value.factoryAreaNumber}&number=${data.value.number}&data=${encodeURIComponent(JSON.stringify(item))}`
			)
		} else {
			proxy.$tab.navigateTo(
				`/pages/repairOrder/addServiceRecord?type=${type.value}&factoryAreaNumber=${data.value.factoryAreaNumber}&number=${data.value.number}`
			)
		}
	}

	// 完成按钮
	function orderClickSuccess() {
		// 如果点击完成是否与接单人员一致
		if (data.value.status == 'PECEIVED') {
			if (store.id != data.value.maintenance) {
				proxy.$modal.showToast('当前人员与接单人员不一致')
				return;
			}

			if (!serviceList.value || serviceList.value && serviceList.value.length == 0) {
				proxy.$modal.showToast('请添加维修内容')
				return;
			}
			if (!data.value.classesName || !data.value.faultTypeName) {
				proxy.$modal.showToast('请完善班次和故障类型')
				return;
			}
		}
		isShowSuccess.value = true
	}
	function radioGroupChange(e) {
		result.value = e
	}
	function sure() {
		isShowSuccess.value = false
		orderClick(2)
	}
	// APP维修工单接单、点击完成、验证
	function orderClick(type) {
		// 如果是接单
		// if (this.data.status == 'PENDING') {
		// 	if (this.$store.state.user.dept.parentId != this.data.factoryAreaNumber) {
		// 		this.$modal.showToast('当前人员厂区与工单来源的厂区不一致')
		// 		return;
		// 	}
		// 	if (this.$store.state.user.dept.classType != this.data.type) {
		// 		this.$modal.showToast('当前人员班组与工单类型不一致')
		// 		return;
		// 	}
		// }


		const dataOne = {
			number: data.value.number,
			status: data.value.status,
			id: data.value.id,
			result: type == 2 ? result.value : '',
			requestNumber: data.value.requestNumber,
		}
		// 修改工单接口参数
		const dataTwo = {
			id: data.value && data.value.id ? data.value.id : '',
			describes: data.value.describes,
			type: data.value.type,
			deviceNumber: data.value.deviceNumber,
			factoryAreaNumber: data.value.factoryAreaNumber,
			classes: data.value.classes,
			faultType: data.value.faultType
		}
		let tips = data.value.status == 'PENDING' ? '是否接单？' : data.value.status == 'PECEIVED' ? '是否完成？' : data
			.value.status == 'COMPLETED' ? '是否验证完结？' : ''
		proxy.$modal.confirm(tips).then(async () => {
			proxy.$modal.loading('加载中')
			loading.value = true
			// 如果直接点击完成先走修改工单接口
			if (data.value.status == 'PECEIVED') {
				await repairOrderApi.repairOrderUpdate(dataTwo).then((res) => { }).catch(() => {
					proxy.$modal.closeLoading()
					loading.value = false
				})
			}
			await repairOrderApi.orderClick(dataOne).then((res) => {
				if (res.data) {
					proxy.$modal.showToast('操作成功')
					setTimeout(() => {
						proxy.$tab.navigateBack()
						loading.value = false
					}, 1500)
				} else {
					proxy.$modal.showToast('操作失败')
					loading.value = false
				}
			}).catch(() => {
				proxy.$modal.closeLoading()
				loading.value = false
			})
		})
	}
	// 获取维修报修信息
	function getDeviceRepairDetailsByNumber() {
		repairOrderApi.getDeviceRepairDetailsByNumber({
			type: data.value.type,
			requestNumber: data.value.requestNumber
		}).then((res) => {
			if (res.data) {
				data1.value = res.data
			}
		}).catch(() => { })
	}
	// 获取维修内容列表
	function getRepairOrderDetaiList() {
		repairOrderApi.repairOrderDetailList({
			number: data.value.number
		}).then((res) => {
			if (res.data) {
				serviceList.value = res.data
			}
		}).catch(() => { })
	}
	// 删除维修内容
	function delService(item) {
		proxy.$modal.confirm('确定删除维修内容吗？').then(() => {
			proxy.$modal.loading('加载中')
			repairOrderApi.repairOrderDetailDelete(item.id).then((res) => {
				proxy.$modal.closeLoading()
				getRepairOrderDetaiList()
			}).catch(() => { })
		})
	}
	function transfer() {
		proxy.$tab.navigateTo(`/pages/repairOrder/transfer?type=${data.value.type}&id=${data.value.id}&deviceNumber=${data.value.deviceNumber}`)
	}
	function previewImage(current, array) {
		uni.previewImage({
			urls: array,
			current: current,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function (data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function (err) {
					console.log(err.errMsg);
				}
			}
		});
	}
	// 单列模式
	function openSingleColumn(fieldName, val, list) {
		singleColumnList.value = list
		field.value = fieldName
		if (val) {
			singleColumnDefaultValue.value = [list.findIndex(item => item.value == val)]
		} else {
			singleColumnDefaultValue.value = []
		}
		singleColumnShow.value = true
	}
	// 单列模式点击确定之后
	function chooseSingleColumn(e) {
		data.value[field.value] = e[0].value
		console.log(field.value)
		if (field.value == 'classes') {
			data.value.classesName = e[0].label
			console.log(data.value.classesName)
		}
		if (field.value == 'faultType') {
			data.value.faultTypeName = e[0].label
		}
		singleColumnShow.value = false
	}
	// 修改工单
	function editForm() {
		const paramesData = {
			id: data.value && data.value.id ? data.value.id : '',
			describes: data.value.describes,
			type: data.value.type,
			deviceNumber: data.value.deviceNumber,
			factoryAreaNumber: data.value.factoryAreaNumber,
			classes: data.value.classes,
			faultType: data.value.faultType
		}
		proxy.$modal.confirm('是否修改维修工单').then(() => {
			proxy.$modal.loading('加载中')
			loading1.value = true
			repairOrderApi.repairOrderUpdate(paramesData).then((res) => {
				proxy.$modal.closeLoading()
				if (res.data) {
					proxy.$modal.showToast('修改成功')
					// setTimeout(() => {
					// 	this.$tab.navigateBack()
					loading1.value = false
					// }, 1500)
				} else {
					proxy.$modal.showToast('修改失败')
					loading1.value = false
				}
			}).catch(() => {
				proxy.$modal.closeLoading()
				loading.value = false
			})
		})
	}
	onLoad(async (option) => {
		if (option.type) type.value = option.type;
		if (option.data) {
			data.value = JSON.parse(decodeURIComponent(option.data))

		}
		changeItem.value = list.value[current.value]
		orderCompleteResult.value = await dictApi.getDict('order_complete_result')


	})
	onShow(async () => {
		if (data.value.requestNumber) {
			getDeviceRepairDetailsByNumber()
			list.value = [{
				name: '设备信息',
				value: 1
			}, {
				name: '报修信息',
				value: 2
			}, {
				name: '维修内容',
				value: 3
			}]
		} else {
			list.value = [{
				name: '设备信息',
				value: 1
			}, {
				name: '维修内容',
				value: 3
			}]
		}
		getRepairOrderDetaiList()
		maintenanceShift.value = await dictApi.getDict('maintenance_shift')
		faultType.value = await dictApi.getDict('fault_type')
	})
</script>

<style lang="scss" scoped>
	.detail-container {
		min-height: 100vh;
		background: white;
	}

	.line {
		background: #f5f5f5;
		height: 20rpx;
	}

	.info {
		background: white;
	}

	.tab {
		border-bottom: 1px solid #e4e4e4;

	}

	.title {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #e4e4e4;

		view {
			&:nth-child(1) {
				flex: 1;
				border-left: 10rpx solid #409eff;
				padding-left: 20rpx;
				font-weight: bold;
			}
		}
	}

	.dec {
		padding: 30rpx;

		.dec-item {
			padding-bottom: 30rpx;
			display: flex;

			view {
				&:nth-child(1) {
					width: 160rpx;
				}

				&:nth-child(2) {
					color: #888888;
					flex: 1;
					width: 0px;
					word-wrap: break-word;
				}
			}
		}
	}

	.dec2 {
		padding: 10rpx 30rpx;
		display: flex;

		view {
			&:nth-child(1) {
				width: 160rpx;
			}

			&:nth-child(2) {
				color: #888888;
				flex: 1;
				width: 0px;
				word-wrap: break-word;
			}
		}


	}

	.items {
		margin: 20rpx 30rpx;
		border-radius: 12rpx;
		background: #F5F5F5;
		padding-bottom: 20rpx;

		.items-name {
			padding: 20rpx;
			border-bottom: 1px solid #dedede;
		}

		.items-dec {
			padding: 0px 20rpx;
			margin-top: 20rpx;
		}
	}

	.popup-title {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #409eff;
		padding: 30rpx
	}

	.popup {
		width: 600rpx;
		padding: 0rpx 60rpx 0rpx;

	}

	.popup-footer {
		display: flex;
		border-top: 1px solid #e4e4e4;

		view {
			line-height: 100rpx;
			flex: 1;
			text-align: center;

			&.sure {
				color: #409eff;
			}
		}
	}

	.footer {
		position: fixed;
		bottom: 0px;
		left: 0px;
		width: 100%;
		background: white;
		z-index: 22;
	}

	.btns {
		display: flex;

		padding: 20rpx;
		box-shadow: 0px -2rpx 20rpx rgba(0, 0, 0, 0.1);


		button {
			flex: 1;
			margin: 0px 10rpx;
		}

		.sure {
			background: #409eff;
			color: white;
			border-radius: 8rpx;

			&::after {
				border: 1px solid #409eff;
				border-radius: 0px;
			}
		}
	}

	.list {
		padding: 20rpx;

		.item {
			display: flex;
			margin-bottom: 20rpx;

			.item-box {
				border-radius: 12rpx;
				border: 1px solid #dedede;
				border-radius: 12rpx;

				flex: 1;
				width: 0rpx;
			}

			.spare-title {
				padding: 20rpx 30rpx;
				border-bottom: 1px solid #e4e4e4;
				display: flex;

				.title-txt {
					color: #409eff;
					font-size: 30rpx;
					font-weight: bold;
					flex: 1;
				}
			}

			.dec {
				color: #9c9c9c;
				padding: 0rpx 30rpx 20rpx;
			}

		}
	}

	.add-btn {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}

	::v-deep .u-radio-group {
		display: grid !important;
		padding-bottom: 20rpx;
	}

	.images {
		display: flex;
		width: 100%;

		image {
			width: 30%;
			margin-right: 20rpx;
			height: 200rpx;
			border-radius: 10rpx;
		}
	}

	.select {
		display: flex;
		align-items: center;
		height: 72rpx;
		width: 100%;

		.input {
			flex: 1;
			font-size: 28rpx;
			color: #000000;
		}

		.placeholder {
			flex: 1;
			font-size: 28rpx;
			color: rgb(192, 196, 204);

		}
	}
</style>