<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
                class="input-readonly"
                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="userNames"
              :label="$t('deviceUser.form.user')"
              required
              @click="showLeaderPopup"
          >
            <uni-easyinput
                class="input-readonly"
                v-model="form.userNames"
                :inputBorder="false"
                :clearable="false"
                :styles="{disableColor:'#fff'}"
                :placeholder="$t('deviceUser.form.userHint')"
                style="text-align: right"
                @click.prevent="showLeaderPopup"
            />
					</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>

    <!--  责任人  -->
    <uni-popup ref="leaderPopup" 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('deviceUser.form.selectUser') }}</text>
            </uni-row>
            <view style="margin-top: 18px; padding-left: 30px; padding-right: 30px">
              <uni-easyinput
                  v-model="userKeywords"
                  :styles="inputStyles"
                  :placeholderStyle="placeholderStyle"
                  :placeholder="$t('deviceUser.form.userPlaceholder')"
                  :input-border="false"
                  @input="onUserChanged"
              />
            </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 selectUserList"
                    @click="onUserItemDelete(item)">
                {{item.nickname}}
                <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="confirmUser">
            {{ $t('operation.confirm') }}
          </button>
        </template>
        <view v-for="item of filterUserList" :key="item.id">
          <view class="device-item" :class="item.selected ? 'selected' : undefined" @click="onSelectUser(item)">
            {{ item.nickname }}
          </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, getUserListByDeptId } from "@/api"
	import { getDeptId } from '@/utils/auth';
  import { submitDeviceUser } from "@/api/deviceUser";

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

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

	const formRef = ref()
	const form = reactive({
		deviceName: '',
    deviceId: '',
    userIds: '',
    userNames: '',
		reason: '',
	})
	const rules = reactive({
		deviceName: { rules: [{ required: true, errorMessage: t('statusChange.form.deviceError') }] },
    userNames: { rules: [{ required: true, errorMessage: t('deviceUser.form.userHint') }] },
		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 leaderPopup = ref() // 责任人弹窗
  const selectUserList = ref([]) // 已选责任人

  // 弹出责任人弹窗
  const showLeaderPopup = () => {
    leaderPopup.value.open('bottom')
  }

  // 选择责任人
  const onSelectUser = (user) => {
    user.selected = !user.selected
    if (user.selected) {
      selectUserList.value.push(user)
    } else {
      selectUserList.value = selectUserList.value.filter(item => item.id !== user.id)
    }
  }

  // 确认责任人
  const confirmUser = () => {
    form.userNames = selectUserList.value.map(item => item.nickname).join(',')
    leaderPopup.value.close('bottom')
  }

  // 删除责任人
  const onUserItemDelete = (item) => {
    const index = selectUserList.value.findIndex((v) => v.id === item.id)
    item.selected = !item.selected
    if (index > -1) {
      selectUserList.value.splice(index, 1)
    }
  }

  const userKeywords = ref('') // 责任人搜索关键字
  // 搜索责任人监听
  const onUserChanged = (text) => {
    filterUserList.value = text ? userList.value.filter(item => item.nickname.includes(text)) : userList.value
  }

	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,
          reason: form.reason,
          userIds: selectUserList.value.map(item => item.id),
        })
			}

      const response = await submitDeviceUser(list)
			if (response.code === 0) {
				uni.showToast({ title: t('statusChange.form.success'), icon: 'none' })
        uni.navigateBack()
        uni.$emit('update')
			}
		} catch (e) {
			console.log(e)
		}
	}

  const userList = ref([]) // 待选责任人列表
  const filterUserList = ref([]) // 筛选后列表
	const deviceList = ref([]) // 待选设备列表
	const filterList = ref([]) // 筛选后列表
	onMounted(async () => {
		statusList.value = getDataDictList('pms_device_status')
    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

    userList.value = (await getUserListByDeptId(getDeptId())).data
    filterUserList.value = userList.value

		await nextTick(() => {
      const inputViews = document.getElementsByClassName('input-readonly');
      for (const view of inputViews) {
        view.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;
	}

  .input-readonly {
    caret-color: transparent;
  }
</style>