<template>
  <div>
    <el-dialog
      v-model="state.showDialog"
      destroy-on-close
      :title="title"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="900px"
    >
      <el-form :model="form" ref="formRef" size="default" label-width="120px">
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备编号" prop="deviceNo" :rules="[{ required: true, message: '请输入设备编号', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.deviceNo" clearable placeholder="请输入设备编号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="资产编号" prop="assetNo">
                <el-input v-model="form.assetNo" clearable placeholder="请输入资产编号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="型号" prop="model">
                <el-select v-model="form.model" placeholder="请选择设备型号" clearable style="width: 100%">
                  <el-option
                    v-for="model in state.modelOptions"
                    :key="model.value"
                    :label="model.label"
                    :value="model.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="规格" prop="specification">
                <el-input v-model="form.specification" clearable placeholder="请输入设备规格" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="房间" prop="roomID" :rules="[{ required: true, message: '请选择房间', trigger: ['blur', 'change'] }]">
                <el-select v-model="form.roomID" placeholder="请选择设备所在房间" style="width: 100%">
                  <el-option
                    v-for="room in state.roomOptions"
                    :key="room.id"
                    :label="room.roomName"
                    :value="room.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备负责人" prop="principalId">
                <el-select
                  v-model="form.principalId"
                  placeholder="请输入姓名搜索设备负责人"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="user in state.userOptions"
                    :key="user.id"
                    :label="`${user.name} (${user.userName})`"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 技术参数 -->
        <div class="form-section">
          <div class="section-title">技术参数</div>
          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="精度(g)" prop="scalePrecision">
                <el-input-number v-model="form.scalePrecision" :min="0" :precision="1" style="width: 100%" placeholder="请输入设备精度" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="报警下限值(g)" prop="warningLowerLimit">
                <el-input-number v-model="form.warningLowerLimit" :min="0" :precision="2" style="width: 100%" placeholder="请输入报警下限值" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 设备配置 -->
        <div class="form-section">
          <div class="section-title">设备配置</div>
          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="维护标记">
                <el-switch
                  v-model="form.maintenanceFlag"
                  active-text="维护中"
                  inactive-text="正常"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="是否补料地秤">
                <el-switch
                  v-model="form.isFeedingScale"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="启用状态">
                <el-switch
                  v-model="form.enabled"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="通讯设置">
                <el-button type="primary" @click="openCommunicationForm" icon="ele-Setting">
                  配置通讯参数
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 通讯设置表单 -->
    <communication-form ref="communicationFormRef" @confirm="onCommunicationConfirm" />
  </div>
</template>

<script lang="ts" setup name="admin/Uspscale/form">
import { reactive, toRefs, ref, getCurrentInstance, onMounted, defineAsyncComponent } from 'vue'
import { UspscaleUpdateInput, RoomGetPageOutput, PageInputRoomGetPageInput, UserGetPageOutput, PageInputUserGetPageInput } from '/@/api/admin/data-contracts'
import { UspscaleApi } from '/@/api/admin/UspscaleApi'
import { RoomApi } from '/@/api/admin/Room'
import { UserApi } from '/@/api/admin/User'
import eventBus from '/@/utils/mitt'

// 引入通讯设置表单组件
const CommunicationForm = defineAsyncComponent(() => import('./communication-form.vue'))

const { proxy } = getCurrentInstance() as any

defineProps({
  title: {
    type: String,
    default: '',
  },
})

const formRef = ref()
const communicationFormRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,
  form: {
    enabled: true,
    maintenanceFlag: false,
    isFeedingScale: false,
    roomID: 0,
  } as UspscaleUpdateInput,
  roomOptions: [] as Array<RoomGetPageOutput>,
  userOptions: [] as Array<UserGetPageOutput>,
  modelOptions: [
    { label: 'CAIS2-U 1500kg', value: '001' },
    { label: 'METTLER', value: '3' },
    { label: 'OHAUS', value: '5' }
  ],
  data: [],
})

const { form } = toRefs(state)

onMounted(() => {
  getRoomOptions()
  getUserOptions()
})

const getRoomOptions = async () => {
  try {
    const roomPageInput = {
      currentPage: 1,
      pageSize: 1000, // 获取足够多的数据
      filter: {
        keyWord: '',
      }
    } as PageInputRoomGetPageInput

    const res = await new RoomApi().getPage(roomPageInput)
    if (res?.success) {
      state.roomOptions = res.data?.list ?? []
    }
  } catch (error) {
    console.error('获取房间列表失败:', error)
  }
}

const getUserOptions = async () => {
  try {
    const userPageInput = {
      currentPage: 1,
      pageSize: 1000, // 获取足够多的数据
      filter: {
        orgId: null,
      }
    } as PageInputUserGetPageInput

    const res = await new UserApi().getPage(userPageInput)
    if (res?.success) {
      state.userOptions = res.data?.list ?? []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 打开对话框
const open = async (row: any = {}) => {
  proxy.$modal.loading()

  if (row.id > 0) {
    const res = await new UspscaleApi().get({ id: row.id }, { loading: true })
    if (res?.success) {
      let formData = res.data as UspscaleUpdateInput
      state.form = formData
    }
  } else {
    state.form = {
      enabled: true,
      maintenanceFlag: false,
      isFeedingScale: false,
      roomID: undefined,
      principalId: undefined,
      warningLowerLimit: 0,
      scalePrecision: 0,
      deviceNo: '',
      assetNo: '',
      model: '',
      specification: '',
      subSystemIP: '',
      subSystemIPPort: '',
      deviceIP: '',
      deviceIPPort: '',
      serviceName: '',
    } as UspscaleUpdateInput
  }

  proxy.$modal.closeLoading()
  state.showDialog = true
}

// 打开通讯设置表单
const openCommunicationForm = () => {
  const communicationData = {
    subSystemIP: state.form.subSystemIP,
    subSystemIPPort: state.form.subSystemIPPort,
    deviceIP: state.form.deviceIP,
    deviceIPPort: state.form.deviceIPPort,
    serviceName: state.form.serviceName,
  }
  communicationFormRef.value.open(communicationData)
}

// 通讯设置确认回调
const onCommunicationConfirm = (data: any) => {
  state.form.subSystemIP = data.subSystemIP
  state.form.subSystemIPPort = data.subSystemIPPort
  state.form.deviceIP = data.deviceIP
  state.form.deviceIPPort = data.deviceIPPort
  state.form.serviceName = data.serviceName
}

// 取消
const onCancel = () => {
  state.showDialog = false
}

// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return



    state.sureLoading = true
    let res = {} as any
    if (state.form.id != undefined && state.form.id > 0) {
      res = await new UspscaleApi().update(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    } else {
      res = await new UspscaleApi().add(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    }

    state.sureLoading = false

    if (res?.success) {
      eventBus.emit('refreshRoom')
      state.showDialog = false
    }
  })
}

defineExpose({
  open,
})
</script>

<style lang="scss" scoped>
.form-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    left: 0;
    bottom: -2px;
    width: 40px;
    height: 2px;
    background: #409eff;
  }
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-switch__label) {
  font-size: 13px;
}
</style>
