<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="设备名称" prop="name">
                    <el-input v-model="formData.name" clearable placeholder="请输入设备名称" />
                </el-form-item>
                <el-form-item label="设备类型" prop="type">
                    <el-select class="flex-1" v-model="formData.type" clearable placeholder="请选择设备类型">
                        <el-option
                            v-for="(item, index) in dictData.device_type"
                            :key="index"
                            :label="item.name"
                            :value="parseInt(item.value)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属产品" prop="product_id">
                      <el-select
                        v-model="formData.product_id"
                        remote
                        filterable
                        placeholder="请输入产品信息"
                        :remote-method="queryProduct"
                        :loading="loading"
                      >
                      <el-option
                        v-for="(item, index) in optionsData.product"
                        :key="index"
                        :label="item.productinfo"
                        :value="item.id"
                    />
                      </el-select>
                </el-form-item>

              <el-form-item label="设备编码" prop="code" :rules="[{
        required: true,
        message: '请输入设备编码',
        trigger: ['blur']
    }]" v-if="formData.type ==1">
                <el-select
                    v-model="formData.code"
                    remote
                    filterable
                    :remote-method="queryDeviceIccid"
                    @change="deviceChange"
                    :loading="loading"
                >
                  <el-option
                      v-for="(item, index) in optionsData.deviceIccids"
                      :key="index"
                      :label="item.device_sn"
                      :value="item.device_sn"
                  />
                </el-select>
              </el-form-item>
<!--                <el-form-item label="设备编码" prop="code">-->
<!--                    <el-input v-model="formData.code" clearable placeholder="请输入设备编码" />-->
<!--                </el-form-item>-->
                <el-form-item label="硬件ICCID" prop="iccid" v-if="formData.type ==1">
                  <el-input v-model="formData.iccid" disabled placeholder="请输入ICCID" />
                </el-form-item>
              <el-form-item label="监测项" prop="monitor_item"  v-if="formData.type ==1">
                <el-select class="flex-1" v-model="formData.monitor_item" multiple disabled placeholder="请选择设备监测项">
                  <el-option
                      v-for="(item, index) in dictData.monitor_item"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
                <el-form-item label="设备图" prop="image">
                  <el-upload
                      class="avatar-uploader"
                      :accept="acceptFileTypes"
                      v-model="formData.image"
                      :data="{ cid: 1 }"
                      :headers="{ Token: userStore.token }"
                      :action="action"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccessAvatar"
                  >
                    <img
                        v-if="formData.image"
                        :src="formData.image"
                        class="avatar"
                    />
                    <div v-else class="avatar-uploader-icon">
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </div>
                  </el-upload>

                </el-form-item>

                <el-form-item label="视频地址" prop="video_url">
                    <el-input v-model="formData.video_url" clearable placeholder="请输入视频地址" />
                </el-form-item>
                <el-form-item label="设备状态" prop="status">
                    <el-select class="flex-1" v-model="formData.status" clearable placeholder="请选择设备状态">
                        <el-option
                            v-for="(item, index) in dictData.device_status"
                            :key="index"
                            :label="item.name"
                            :value="parseInt(item.value)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否在线" prop="is_online">
                    <el-select class="flex-1" v-model="formData.is_online" clearable placeholder="请选择是否在线">
                        <el-option
                            v-for="(item, index) in dictData.device_online_status"
                            :key="index"
                            :label="item.name"
                            :value="parseInt(item.value)"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="deviceEdit">
import { useDictOptions } from '@/hooks/useDictOptions'
import {type  FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {apiDeviceAdd, apiDeviceEdit, apiDeviceDetail, getUserList, apiProductLists, apiDeviceIccid} from '@/api/device'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import {ref} from "vue";
import config from "@/config";
import useUserStore from "@/stores/modules/user";
import {ElMessage, type UploadProps} from "element-plus";
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const acceptFileTypes = ref(".png, .jpg, .jpeg, image/png, image/jpeg")
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
const userStore = useUserStore()
const handleAvatarSuccessAvatar: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.image = response.data.uri;
}

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑设备' : '新增设备'
})

// 表单数据
const formData = reactive({
    id: '',
    product_id: '',
    code: '',
    iccid: '',
    name: '',
    video_url: '',
    type: '',
    monitor_item: [],
    status: '',
    is_online: '',
    image: ''
})

// 表单验证
const formRules = reactive<any>({
    name: [{
        required: true,
        message: '请输入设备名称',
        trigger: ['blur']
    }],
    type: [{
        required: true,
        message: '请选择设备类型',
        trigger: ['blur']
    }],
    status: [{
        required: true,
        message: '请选择设备状态',
        trigger: ['blur']
    }],
    is_online: [{
        required: true,
        message: '请选择是否在线',
        trigger: ['blur']
    }],
})
const deviceChange = async (value: string) => {
  const temp = await apiDeviceIccid({
    deviceId: value ?? ''
  }).catch((err) =>{
    formData.iccid = ''
    formData.monitor_item = ''
  })
  if (temp.length != 0) {
    formData.iccid = temp[0]['iccid']
    if ( temp[0]['type'] == 0) {
      formData.monitor_item = ['temperature']
    }
    if (temp[0]['type'] == 1) {
      formData.monitor_item =   ['ambient_temperature','ambient_humidity']
    }
    if ( temp[0]['type'] == 2) {
      formData.monitor_item = ['nitrogen']
    }
    if ( temp[0]['type'] == 3) {
      formData.monitor_item = ['methane']
    }
    if ( temp[0]['type'] == 4) {
      formData.monitor_item = ['noise']

    }
    if ( temp[0]['type'] == 5) {
      formData.monitor_item = ['fireproof']

    }
  }
}

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const { optionsData } = useDictOptions<{
    product: any[],
  deviceIccids: any[],
}>({
    product: {
        api: apiProductLists,
        params: {
            all: 1
        }
    },
    deviceIccids:{
      api: apiDeviceIccid,
      params: {
        all: 1
      }
    }
})

const loading = ref(false)

const queryProduct = async (query: string) => {
    loading.value = true
    const productList = await apiProductLists({
        name: query ?? ''
    })
    optionsData.product = productList
    loading.value = false
}

const queryDeviceIccid = async (query: string) => {
  loading.value = true
  const deviceList = await apiDeviceIccid({
    deviceId: query ?? ''
  })
  optionsData.deviceIccids = deviceList
  loading.value = false
}


const getDetail = async (row: Record<string, any>) => {
    const data = await apiDeviceDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData,  }
    mode.value == 'edit' 
        ? await apiDeviceEdit(data) 
        : await apiDeviceAdd(data)
    popupRef.value?.close()
    emit('success')
}
const generateUuid = (length: number) => {
  let result1='',result2='';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  const characters1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  result1 = characters.charAt(Math.floor(Math.random() * characters.length))
  for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters1.length);
      result2 += characters1.charAt(randomIndex);

  }
  return result1+result2;
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
  // formData.code = generateUuid(3)
  popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}



defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  width: 200px;
  height: 130px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>