<template>
<<<<<<< HEAD
    <el-dialog  :title="dialogTitle" v-model='dialogVisible' @close="close" v-bind="dialogBig">
        <el-tabs type="border-card">
            <el-tab-pane label="设备台账信息">
                <div class="form-grid">
                    <el-form :model='formContent' ref='dialogFormRef' :rules='rules' :disabled="false">
                        <el-row  :gutter="24" >
                            <el-col :span="8">
                                <el-form-item label="设备名称" prop="name" :label-width="100">
                                    <el-input v-model='formContent.name' placeholder="请输入设备名称"/>
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label='设备类型'  prop='devType' :label-width="100">
                                    <el-select v-model="formContent.devType"  clearable placeholder="请选择设备类型">
                                    <el-option
                                    v-for="item in dictStore.getDictData('Dev_Type')"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code"
                                    />
                                </el-select>
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label='通讯协议'  prop='protocol' :label-width="100">
                                    <el-select v-model="formContent.protocol"  clearable placeholder="请选择通讯协议">
                                    <el-option
                                    v-for="item in dictStore.getDictData('Event_Type')"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code"
                                    />
                                </el-select>
                                </el-form-item>         
                            </el-col>
                            
                        </el-row>     
                        <el-row  :gutter="24" >
                            <el-col :span="8">
                                <el-form-item label="设备通道数" prop="devChns" :label-width="100">
                                    <el-select v-model="formContent.devChns"  clearable placeholder="请选择设备通道数">
                                    <el-option
                                    v-for="item in dictStore.getDictData('Dev_Chns')"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code"
                                    />
                                </el-select>
                                </el-form-item>            
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="额定电压(V)" prop="devVolt" :label-width="100">
                                    <el-select v-model="formContent.devVolt"  clearable placeholder="请选择额定电压">
                                    <el-option
                                    v-for="item in dictStore.getDictData('Dev_Volt')"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code"
                                    />
                                </el-select>
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="额定电流(A)" prop="devCurr" :label-width="100">
                                    <el-select v-model="formContent.devCurr"  clearable placeholder="请选择额定电流">
                                    <el-option
                                    v-for="item in dictStore.getDictData('Dev_Curr')"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code"
                                    />
                                </el-select>
                                </el-form-item>            
                            </el-col>
                            
                        </el-row>     
                        <el-row  :gutter="24" >
                            <el-col :span="8">
                                <el-form-item label='生产厂商'  prop='manufacturer' :label-width="100">
                                    <el-select v-model="formContent.manufacturer"  clearable placeholder="请选择生产厂商">
                                    <el-option
                                    v-for="item in dictStore.getDictData('Dev_Manufacturers')"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.code"
                                    />
                                </el-select>
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="生产日期" prop="createDate" :label-width="100">
                                    <el-date-picker 
                                        v-model="formContent.createDate" 
                                        placeholder="请选择生产日期"
                                        :disabled-date="disabledDate"
                                        />
                                
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="出厂编号" prop="createId" placeholder="请输入出厂编号" :label-width="100">
                                    <el-input v-model="formContent.createId" />
                                </el-form-item>            
                            </el-col>
                        </el-row>
                        <el-row  :gutter="24" >
                            <el-col :span="8">
                                <el-form-item label="固件版本" prop="hardwareVersion" :label-width="100">
                                    <el-input v-model="formContent.hardwareVersion" placeholder="请输入固件版本"/>
                                </el-form-item>            
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="软件版本" prop="softwareVersion" :label-width="100">
                                    <el-input v-model="formContent.softwareVersion" placeholder="请输入软件版本"/>
                                </el-form-item>            
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label='设备模式'  prop='pattern' :label-width="100">
                                    <el-input v-model='formContent.pattern' disabled/>
                                </el-form-item>           
                            </el-col>
                        </el-row> 
                        <el-row  :gutter="24" >
                            <el-col :span="8">
                                <el-form-item label="IP地址" prop="ip" :label-width="100">
                                    <IPAddress v-model:value="formContent.ip"/>
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="端口号" prop="port" placeholder="请输入端口号" :label-width="100">
                                    <el-input v-model="formContent.port" />
                                </el-form-item>            
                            </el-col>
                        </el-row>       
                      
                        <el-row  :gutter="24" >
                        <el-col :span="8">
                                <el-form-item label='是否加密'  prop='encryptionFlag' :label-width="100">
                                    <el-select v-model="formContent.encryptionFlag"  clearable placeholder="请选择是否加密" @change="handleEncryptionChange">
                                        <el-option label="是" :value="1"></el-option>
                                        <el-option label="否" :value="0"></el-option>
                                    </el-select>
                                </el-form-item>           
                        </el-col>
                        <el-col :span="8" v-if="IsPasswordShow">
                                <el-form-item label='识别码'  prop='series' clearable placeholder="请输入识别码" :label-width="100">
                                    <el-input v-model='formContent.series'  show-password/>
                                </el-form-item>           
                        </el-col>
                        <el-col :span="8" v-if="IsPasswordShow">
                                <el-form-item label='密钥'  prop='devKey' clearable placeholder="请输入密钥" :label-width="100">
                                    <el-input v-model='formContent.devKey'  show-password/>
                                </el-form-item>           
                        </el-col>
                        </el-row>
                        <el-row  :gutter="24" v-if="DevIsShow">
                            <el-col :span="8">
                                <el-form-item label='样品编号'  prop='sampleID' clearable placeholder="请输入样品编号" :label-width="100">
                                    <el-input v-model='formContent.sampleID' />
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label='送样日期'  prop='arrivedDate' :label-width="100">
                                    <el-date-picker 
                                        v-model="formContent.arrivedDate" 
                                        placeholder="请选择送样日期"
                                        :disabled-date="disabledDate"
                                        />
                                </el-form-item>           
                            </el-col>
                        </el-row>
                        <el-row  :gutter="24" v-if="MonIsShow">
                            <el-col :span="8">
                                <el-form-item label='所属地市'  prop='cityName' clearable placeholder="请输入所属地市" :label-width="100">
                                    <el-input v-model='formContent.cityName' />
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label='所属供电公司'  prop='gDName' clearable placeholder="请输入所属供电公司" :label-width="100">
                                    <el-input v-model='formContent.gDName' />
                                </el-form-item>           
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label='所属电站'  prop='subName' clearable placeholder="请输入所属电站" :label-width="100">
                                    <el-input v-model='formContent.subName' />
                                </el-form-item>           
                            </el-col>
                        </el-row>   
                    </el-form>            
                </div>  
            </el-tab-pane>
            <el-tab-pane label="监测点台账信息" v-if="MonIsShow">
                <div class='table-box' ref='popupBaseView'>
                    <ProTable
                        ref='proTable'
                        :columns='columns'
                        :request-api='getPqMonList'
                    >
                    <!-- 表格 header 按钮 -->
                    <template #tableHeader='scope'>
                        <el-button type='primary' :icon='CirclePlus' >新增</el-button>
                        <el-button type='danger' :icon='Delete' plain :disabled='!scope.isSelected'>批量删除</el-button>
                    </template>
                    <!-- 表格操作 -->
                    <template #operation>
                        <el-button type='primary' link :icon='EditPen'>复制</el-button>
                        <el-button type='primary' link :icon='EditPen'>编辑</el-button>
                        <el-button type='primary' link :icon='Delete'>删除</el-button>
                    </template>
                    </ProTable>
                </div>
            </el-tab-pane>
   
        </el-tabs>
        <template #footer>
            <div >
                <el-button @click='close()'>取 消</el-button>
                <el-button type="primary" @click='save()'>保存</el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script setup lang='ts'>

import IPAddress from '@/components/IpAddress/index.vue'
import { dialogBig } from '@/utils/elementBind'
import { type Device } from '@/api/device/interface'
import { ElMessage, type FormItemRule } from 'element-plus'
import { addPqDev, updatePqDev } from '@/api/device/device.ts'
import { computed, reactive, type Ref, ref } from 'vue'
import { useDictStore } from '@/stores/modules/dict'
import { CirclePlus, Delete, EditPen } from '@element-plus/icons-vue'
// 使用 dayjs 库格式化
import dayjs from 'dayjs'
import { getPqMonList } from '@/api/monitor/monitor.ts'
import { type ColumnProps } from '@/components/ProTable/interface'
import { type Monitor } from '@/api/monitor/interface'

const MonIsShow = ref(false)
const DevIsShow = ref(false)
const IsPasswordShow = ref(false)
const dictStore = useDictStore()
// 定义弹出组件元信息
const dialogFormRef = ref()
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

  function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<Device.ResPqDev>({
      id: '',
      name: '',
      pattern:'模拟式',
      devType:'',
      devChns:1,
      devVolt:57.74,
      devCurr:1,
      manufacturer: '',
      createDate: '',
      createId: '', 
      hardwareVersion: '',
      softwareVersion: '',
      protocol: '',
      ip: '',
      port: 102,
      encryptionFlag: 1,
      reCheckNum:0,
      state: 1,
    })
    return { dialogVisible, titleType, formContent }
  }
  
  const { dialogVisible, titleType, formContent } = useMetaInfo()
  // 清空formContent
  const resetFormContent = () => {
    formContent.value = {
        id: '',
        name: '',
        pattern:'模拟式',
        devType:'',
        devChns:1,
        devVolt:57.74,
        devCurr:1,
        manufacturer: '',
        createDate: '',
        createId: '', 
        hardwareVersion: '',
        softwareVersion: '',
        protocol: '',
        ip: '',
        port: 102,
        encryptionFlag: 1,
        reCheckNum:0,
        state: 1,
    }
  }
  

  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增被检设备' : '编辑被检设备'
  })


  // 定义表单校验规则
  const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    devType: [{ required: true, message: '设备类型必选！', trigger: 'change' }],
    pattern: [{ required: true, message: '设备模式必填！', trigger: 'blur' }],
    name: [{ required: true, message: '设备名称必填！', trigger: 'blur' }],
    devChns: [{ required: true, message: '设备通道数必填！', trigger: 'blur' },
                // 指定正则，此处是数字正则
              { pattern: /^[1-9]\d*$/, message: '设备通道数为大于1的整数', trigger: 'blur' }],
    devVolt: [{ required: true, message: '额定电压必填！', trigger: 'blur' },
                { pattern: /^\d+(\.\d+)?$/, message: '额定电压格式错误', trigger: 'blur' }],
    devCurr: [{ required: true, message: '额定电流必填！', trigger: 'blur' },
                { pattern: /^\d+(\.\d+)?$/, message: '额定电流格式错误', trigger: 'blur' }],
    createDate: [{ required: true, message: '生产日期必填！', trigger: 'blur' }],
    createId: [{ required: true, message: '出厂编号必填！', trigger: 'blur' }],
    hardwareVersion: [{ required: true, message: '固件版本必填！', trigger: 'blur' }],
    softwareVersion: [{ required: true, message: '软件版本必填！', trigger: 'blur' }],
    ip:[{ required: true, message: 'IP地址必填！', trigger: 'blur' } ,
        { pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: 'IP地址格式错误', trigger: 'blur' }],
    port:[{ required: true, message: '端口号必填！', trigger: 'blur' },
          { pattern: /^(6553[0-5]|655[0-2][0-9]|64[0-9]{3}|[1-5]?[0-9]{1,4})$/, message: '端口号范围0到65535的整数', trigger: 'blur' }],
    manufacturer: [{ required: true, message: '生产厂家必选！', trigger: 'change' }],
    encryptionFlag: [{ required: true, message: '是否加密必选！', trigger: 'change' }],
    protocol: [{ required: true, message: '通讯协议必选！', trigger: 'change' }],
    series: [],
    devKey: []
})
  
  // 关闭弹窗
  const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {

            if (formContent.value.encryptionFlag === 1) {
                handleEncryptionChange(1)
            } else {
                handleEncryptionChange(0)
            }

        if (valid) {
          formContent.value.createDate = dayjs(formContent.value.createDate).format('YYYY-MM-DD');
          if (formContent.value.arrivedDate) 
          {
            formContent.value.arrivedDate = dayjs(formContent.value.arrivedDate).format('YYYY-MM-DD');
          }
          if (formContent.value.id) {
                await updatePqDev(formContent.value);
                ElMessage.success({ message: `${dialogTitle.value}成功！` })
            } else {
              await addPqDev(formContent.value);
              ElMessage.success({ message: `${dialogTitle.value}成功！` })
                
          }
          close()
          // 刷新表格
          await props.refreshTable!()

        }
    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }
}

// 打开弹窗，可能是新增，也可能是编辑
const open = (sign: string, data: Device.ResPqDev) => {
  titleType.value = sign
  dialogVisible.value = true

    if(data.pattern ==='比对式'){
        DevIsShow.value = false
        MonIsShow.value = true
    }else{
        DevIsShow.value = true
        MonIsShow.value = false
    }

  if (data.encryptionFlag === 1) {
    handleEncryptionChange(1)
  } else {
    handleEncryptionChange(0)
  }
  if (data.id) {
    formContent.value = { ...data }
  } else {
    resetFormContent()
    handleEncryptionChange(1)
  }
}
  const handleEncryptionChange = (value: number) => {
    // 根据是否加密来显示或隐藏识别码和密钥
    if(value === 1){
        IsPasswordShow.value = true
        rules.value.series = [
      { required: true, message: '请输入识别码', trigger: 'blur' }
    ];
    rules.value.devKey = [
      { required: true, message: '请输入密钥', trigger: 'blur' }
    ];
    }else
    {
        IsPasswordShow.value = false
        formContent.value.series = ''
        formContent.value.devKey = ''
        rules.value.series = [];
        rules.value.devKey = [];
    }
    
    // 如果选择"是"，则显示；否则隐藏
    dialogFormRef.value?.clearValidate(); // 清除验证状态

}

// 对外映射
defineExpose({ open })
const props = defineProps<{
  refreshTable: (() => Promise<void>) | undefined;
}>()



// 表格配置项
const columns = reactive<ColumnProps<Monitor.ResPqMon>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  { type: 'index', fixed: 'left', width: 70, label: '序号' },
  {
    prop: '',
    label: '所属母线',
    width: 200,
  },
  {
    prop: '',
    label: '被检通道',
    width: 200,
  },
  {
    prop: '',
    label: 'PT变比',
    width: 110,
  },
  {
    prop: '',
    label: 'CT变比',
    width: 130,
  },
  {
    prop: '',
    label: '接线方式',
    width: 130,

  },
  {
    prop: '',
    label: '谐波系统监测点ID',
    minWidth: 250,
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200 },
])
</script>