<template>
	<view class="page detail">
		<uni-card>
			<view class="form-content">
				<uni-forms ref="formRef" :model-value="form" :rules="rules" err-show-type="toast" labelWidth="140px">
					<!-- 设备 -->
					<uni-forms-item class="form-item align-center" name="deviceName" :label="$t('statusChange.form.device')" required
						@click="selectDevice">
						<uni-easyinput v-model="form.deviceName" :inputBorder="false" :clearable="false"
							:styles="{disableColor:'#fff'}" :placeholder="$t('statusChange.form.deviceHint')"
							style="text-align: right" @click.prevent="selectDevice" />
					</uni-forms-item>

					<!-- 设备状态 -->
					<uni-forms-item class="form-item align-center" name="status" :label="$t('statusChange.form.status')" required>
						<uni-data-picker v-model="form.status" :popup-title="$t('statusChange.form.statusTitle')"
							:localdata="statusList" :map="{ text: 'label', value: 'value' }" />
					</uni-forms-item>

					<!-- 调整原因 -->
					<uni-forms-item class="form-item align-center" name="reason" :label="$t('statusChange.form.reason')" required>
						<uni-easyinput style="text-align: right" :autoHeight="true" :inputBorder="false"
							:clearable="false" :styles="{ disableColor:'#fff' }"
							:placeholder="$t('statusChange.form.reasonHint')" v-model="form.reason" />
					</uni-forms-item>
				</uni-forms>
			</view>
		</uni-card>
		<button class="submit-btn" type="primary" @click="submit">{{ $t('operation.submit') }}</button>
		<uni-popup ref="popup" type="bottom">
			<z-paging class="z-page-popup" style="top: 200px">
				<template #top>
					<view>
						<uni-row class="flex-row justify-center" style="margin-top: 30px">
							<text>{{ $t('statusChange.form.selectDevice') }}</text>
						</uni-row>
						<view style="margin-top: 18px; padding-left: 30px; padding-right: 30px">
							<uni-easyinput v-model="keywords" :styles="inputStyles" :placeholderStyle="placeholderStyle"
								:placeholder="$t('statusChange.form.searchHint')" :input-border="false"
								@input="onKeywordsChanged" />
						</view>
						<view class="choice-row flex-row flex-wrap align-center justify-start" style="margin: 0 28px">
							<view class="choice-item align-center justify-center" v-for="item in selectedList"
								@click="onItemDelete(item)">
								{{item.deviceName}}
								<uni-icons class="choice-close-icon" type="closeempty" color="#fff"></uni-icons>
							</view>
						</view>
					</view>
				</template>
				<template #bottom>
					<button class="submit-btn" type="primary" @click="confirmDevice">
						{{ $t('operation.confirm') }}
					</button>
				</template>
				<view v-for="item of filterList" :key="item.id">
					<view class="device-item" :class="item.selected ? 'selected' : undefined"
						@click="onSelectedItem(item)">
						{{ `${item.deviceCode} (${item.deviceName})` }}
					</view>
					<view class="divider" />
				</view>
			</z-paging>
		</uni-popup>
	</view>
</template>

<script setup>
	import { reactive, ref, onMounted, nextTick, getCurrentInstance } from 'vue'
	import { useDataDictStore } from "@/store/modules/dataDict"
	import { getAllDeviceList } from "@/api"
	import { submitDeviceChangeRecord } from "@/api/statusChange";
	import { getDeptId } from '@/utils/auth';

	const { appContext } = getCurrentInstance()
	const t = appContext.config.globalProperties.$t

	const { getDataDictList } = useDataDictStore()
	const statusList = ref([])

	const formRef = ref()
	const form = reactive({
		deviceName: '',
		status: '',
		reason: '',
	})
	const rules = reactive({
		deviceName: {
			rules: [{
				required: true,
				errorMessage: t('statusChange.form.deviceError')
			}]
		},
		status: {
			rules: [{
				required: true,
				errorMessage: t('statusChange.form.statusError')
			}]
		},
		reason: {
			rules: [{
				required: true,
				errorMessage: t('statusChange.form.reasonError')
			}]
		},
	})

	const popup = ref()
	const selectDevice = () => {
		popup.value.open('bottom')
	}

	const placeholderStyle = ref('color: #ADADAD; font-weight: 500; font-size: 12px')
	const inputStyles = reactive({
		backgroundColor: '#F5F5F5',
		borderRadius: '4px',
		color: '#797979',
		fontSize: '12px',
	})
	const keywords = ref('')
	const onKeywordsChanged = (text) => {
		filterList.value = deviceList.value.filter(item => item.deviceCode.includes(text) || item.deviceName.includes(
			text))
	}

	const selectedList = ref([])
	const onSelectedItem = (row) => {
		row.selected = !row.selected
		if (row.selected) {
			selectedList.value.push(row)
		} else {
			selectedList.value = selectedList.value.filter(item => item.id !== row.id)
		}
	}
	const onItemDelete = (item) => {
		const index = selectedList.value.findIndex((v) => v.id === item.id)
		item.selected = !item.selected
		if (index > -1) {
			selectedList.value.splice(index, 1)
		}
	}
	const confirmDevice = () => {
		form.deviceName = selectedList.value.map(item => item.deviceName).join(',')
		popup.value.close('bottom')
	}

	const submit = async () => {
		try {
			const valid = await formRef.value.validate()
			if (!valid) return

      const list = []
      for (const item of selectedList.value) {
        list.push({
          deviceId: item.id,
          status: form.status,
          reason: form.reason,
        })
      }
			// const requests = []
			// for (const item of selectedList.value) {
			// 	requests.push(submitDeviceChangeRecord({
			// 		deviceId: item.id,
			// 		oldStatus: item.deviceStatus,
			// 		newStatus: form.status,
			// 		reason: form.reason
			// 	}))
			// }
      const response = await submitDeviceChangeRecord(list)
			// const response = await Promise.all(requests)
			if (response.code === 0) {
				uni.showToast({ title: t('statusChange.form.success'), icon: 'none' })
        uni.navigateBack()
        uni.$emit('update')
			}
		} catch (e) {
			console.log(e)
		}
	}

	const deviceList = ref([])
	const filterList = ref([])
	onMounted(async () => {
		statusList.value = getDataDictList('pms_device_status')
		// const deptList = (await getAllDeptList()).data
		// for (const dept of deptList) {
		// 	if (dept.name === '科瑞石油技术') {
    const locale = uni.getLocale()
		// deviceList.value = (await getAllDeviceList(getDeptId())).data.map((item) => {
    //   if (item.deviceName.includes('~~') && item.deviceName.includes('**')) {
    //     const s = item.deviceName.split('~~')
    //     if (locale.startsWith('zh')) {
    //       item.deviceName = s[0]
    //     } else if (locale.startsWith('ru')) {
    //       const s2 = s[2].split('**')
    //       item.deviceName = s2[1]
    //     } else {
    //       const s1 = s[1].split('**')
    //       item.deviceName = s1[1]
    //     }
    //   }
    //   return JSON.parse(JSON.stringify(item))
    // })
    deviceList.value = (await getAllDeviceList(getDeptId())).data
		filterList.value = deviceList.value
		// 		break
		// 	}
		// }

		await nextTick(() => {
			const inputViews = document.getElementsByClassName('uni-input-input');
			inputViews[0].readOnly = true
		})
	})
</script>

<style lang="scss" scoped>
	@import "@/style/choose-device.scss";
	.form-item{
		min-height: 45px;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}

	:deep(.input-value-border) {
		border: 0 !important;
	}

	:deep(.input-value) {
		text-align: end;
	}

	:deep(.selected-list) {
		display: block;
	}

	:deep(.selected-area) {
		display: block;
		margin-right: 5px;
	}

	:deep(.uni-data-pickerview .selected-area) {
		display: none;
	}

	:deep(.tab-c) {
		margin-left: 30px;
		margin-right: 30px;
		border-top: 1px dashed #CACCCF;

		.item {
			border-bottom: 1px dashed #CACCCF;
		}
	}

	:deep(.uni-forms-item) {
		margin-bottom: 0;
		border-bottom: 1px dashed #CACCCF;
	}

	:deep(.uni-card) {
		padding: 0 !important;
		margin: 0 0 10px 0 !important;
	}

	.popup-content {
		height: 500px;
	}

	.device-item {
		height: 35px;
		line-height: 35px;
		padding: 0 30px;
		font-size: 13px;
		color: #333333;
		border-bottom: 1px #CACCCF;
	}

	.selected {
		color: #004098;
	}

	.divider {
		height: 0.5px;
		margin: 0 28px;
		background-color: #CACCCF;
	}

	.z-page-popup {
		padding: 0;
		background: white;
		border-radius: 10px 10px 0 0;
	}

	.submit-btn {
		width: 100%;
		height: 48px;
		border-radius: 0;
	}
</style>