<template>
  <el-dialog :visible.sync="dialogTableVisible" :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false" destroy-on-close lock-scroll append-to-body width="600px"  class="ems-dialog" :title="mode === 'add'?'新增设备':`编辑设备` " >
    <el-form v-loading="loading>0" ref="addTempForm" :model="formData" :rules="rules" size="medium" label-width="140px">
      <el-form-item label="站点" prop="siteId">
        <el-select v-model="formData.siteId" placeholder="请选择" :style="{width: '100%'}" @change="changeType">
          <el-option :label="item.siteName" :value="item.siteId" v-for="(item,index) in siteList" :key="index+'siteOptions'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备id" prop="deviceId" >
        <el-input v-model="formData.deviceId" placeholder="请输入" maxlength="60" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="formData.deviceName" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="设备描述" prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="工作状态" prop="communicationStatus">
        <el-select v-model="formData.communicationStatus" placeholder="请选择" :style="{width: '100%'}">
          <el-option :label="value" :value="key" v-for="(value,key) in communicationStatusOptions" :key="key+'communicationStatusOptions'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="formData.deviceType" placeholder="请选择" :style="{width: '100%'}">
          <el-option :label="value" :value="key" v-for="(value,key) in deviceTypeOptions" :key="key+'deviceTypeOptions'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备类别" prop="deviceCategory">
        <el-select v-model="formData.deviceCategory" placeholder="请选择" :style="{width: '100%'}" @change="changeType">
          <el-option :label="item.name" :value="item.code" v-for="(item,index) in deviceCategoryList" :key="index+'deviceCategoryList'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上级设备" prop="parentId" v-if="dccDeviceCategoryList.includes(formData.deviceCategory)">
        <el-select v-model="formData.parentId" :placeholder="parentDeviceList.length === 0 && !formData.siteId ? '请先选择站点' : '请选择'" :style="{width: '100%'}">
          <el-option :label="item.deviceName" :value="item.id" v-for="(item,index) in parentDeviceList" :key="index+'parentDeviceList'" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="TCP设备的ip地址" prop="ipAddress" v-if="formData.deviceType === 'TCP'">
        <el-input v-model="formData.ipAddress" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="TCP设备的端口号" prop="ipPort" v-if="formData.deviceType === 'TCP'">
        <el-input v-model="formData.ipPort" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>

      <el-form-item label="串口路径" prop="serialPort">
        <el-input v-model="formData.serialPort" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="波特率" prop="baudRate">
        <el-input v-model="formData.baudRate" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="数据位" prop="dataBits">
        <el-input v-model="formData.dataBits" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="停止位" prop="stopBits">
      <el-input v-model="formData.stopBits" placeholder="请输入" clearable :style="{width: '100%'}">
      </el-input>
    </el-form-item>
      <el-form-item label="校验位" prop="parity">
        <el-input v-model="formData.parity" placeholder="请输入" clearable :style="{width: '100%'}">
        </el-input>
      </el-form-item>
      <el-form-item label="图片" prop="pictureUrl">
        <image-upload :limit="1" :drag="false" @input="uploadImage" :value="formData.pictureUrl"/>
      </el-form-item>

    </el-form>
    <div slot="footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="saveDialog">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {mapState} from "vuex";
import {getAllSites} from '@/api/ems/zddt'
import {validText} from '@/utils/validate'
import {getDeviceDetailInfo,updateDevice,addDevice,getParentDeviceId} from "@/api/ems/site";
import {getAllDeviceCategory} from '@/api/ems/search'
export default {
  props:{
    mode:{
      type:String,
      default:"add"
    },
    id:{
      type:String|Number,
      required:false
    }
  },
  data() {
    const validateText=(rule, value, callback) =>{
      if (value !== '' && !validText(value)) {
        callback(new Error('只能输入中文、英文、数字和特殊字符!'));
      } else {
        callback();
      }
    }
    const validateDeviceId=(rule, value, callback) =>{
      if (value !== '' && !/^[a-zA-Z0-9]+$/.test(value)) {
        callback(new Error('只能输入英文和数字!'));
      } else {
        callback();
      }
    }
    return {
      loading:0,
      dccDeviceCategoryList:['CLUSTER','BATTERY'],//需要展示上级设备的设备类型
      dialogTableVisible:false,
      parentDeviceList:[],//上级设备列表  从接口获取数据
      siteList:[],//站点列表  从接口获取数据
      deviceCategoryList:[],//设备类别列表 从接口获取数据
      formData: {
        id:'',//设备唯一标识
        siteId:'',//站点ID
        deviceId:'',//设备id
        deviceName:'',//设备名称
        description:'',//设备描述
        communicationStatus:'',//工作状态
        deviceType:'',//设备类型
        deviceCategory:'',//设备类别
        parentId:'',//上级设备id
        ipAddress:'',//TCP设备的ip地址
        ipPort:"",//TCP端口号
        serialPort:'',//串口路径
        baudRate:'',//波特率
        dataBits:'',//数据位
        stopBits:'',//停止位
        parity:'',//校验位
        pictureUrl:'',//设备图片
      },
      rules: {
        siteId:[
          { required: true, message: '请选择站点', trigger: ['blur','change']}
        ],
        deviceId:[
          { required: true, message: '请输入设备id', trigger: 'blur'},
          { validator: validateDeviceId, trigger: 'blur' }
        ],
        deviceName:[
          { required: true, message: '请输入设备名称', trigger: 'blur'},
          { validator: validateText, trigger: 'blur' }
        ],
        description:[
          { required: true, message: '请输入设备描述', trigger: 'blur'},
          { validator: validateText, trigger: 'blur' }
        ],
        communicationStatus:[
          { required: true, message: '请选择工作状态', trigger: ['blur','change']}
        ],
        deviceType:[
          { required: true, message: '请选择设备类型', trigger:['blur','change']}
        ],
        deviceCategory:[
          { required: true, message: '请选择设备类别', trigger: ['blur','change']}
        ],
        ipAddress:[
          { validator: validateText, trigger: 'blur' }
        ],
        ipPort:[
          { validator: validateText, trigger: 'blur' }
        ],
        serialPort:[
          { validator: validateText, trigger: 'blur' }
        ],
        baudRate:[
          { validator: validateText, trigger: 'blur' }
        ],
        dataBits:[
          { validator: validateText, trigger: 'blur' }
        ],
        stopBits:[
          { validator: validateText, trigger: 'blur' }
        ],
        parity:[
          { validator: validateText, trigger: 'blur' }
        ],
        // pictureUrl:[
        //   { required: true, message: '请上传图片', trigger: ['blur', 'change']}
        // ],
      },
    }
  },
  computed: {
    ...mapState({
      communicationStatusOptions: state => state?.ems?.communicationStatusOptions || {},
      deviceTypeOptions:state=>state?.ems?.deviceTypeOptions || {}
    })
  },
  watch:{
    dialogTableVisible:{
      handler(newVal){
        //打开弹窗
        if(newVal){
          this.getZdList()
          this.getDeviceCategoryList()
        }
      },
      immediate: true,
    },
    id:{
      handler(newVal){
        if((newVal || newVal===0) && this.mode !== 'add'){
          this.loading+=1
          getDeviceDetailInfo(newVal).then(response => {
            this.formData = JSON.parse(JSON.stringify(response?.data || {}));
            if(this.dccDeviceCategoryList.includes(this.formData.deviceCategory)){
              this.getParentDeviceList(true)
            }
          }).finally(() => {this.loading-=1})
        }
      },
      immediate: true,
    }
  },
  methods: {
    changeType(){
      if(this.dccDeviceCategoryList.includes(this.formData.deviceCategory)){
        this.getParentDeviceList()
      }
    },
    uploadImage(data){
      this.formData.pictureUrl = data
    },
    //获取站点列表
    getZdList(){
      this.loading+=1
      getAllSites().then(response => {
        this.siteList = response?.data || []
      }).finally(() => {this.loading-=1})
    },
    // 获取设备类别
    getDeviceCategoryList(){
      this.loading+=1
      getAllDeviceCategory().then(response => {
        this.deviceCategoryList = response?.data || []
      }).finally(() => {this.loading-=1})
    },
    //获取上级id列表
    getParentDeviceList(init=false){
      if(!this.formData.siteId){
       return  console.log('请先选择站点')
      }
      !init && (this.formData.parentId='')
      this.loading= this.loading+1
      getParentDeviceId({siteId:this.formData.siteId,deviceCategory:this.formData.deviceCategory}).then(response => {
        this.parentDeviceList = JSON.parse(JSON.stringify(response?.data || []));
      }).finally(() => {
        this.loading=this.loading -1
      })
    },
    saveDialog() {
      this.$refs.addTempForm.validate(valid => {
        if (!valid) return
        this.loading+=1
        const {
          id='',
          siteId='',//站点ID
          deviceId='',//设备id
          deviceName='',//设备名称
          description='',//设备描述
          communicationStatus='',//工作状态
          deviceType='',//设备类型
          deviceCategory='',//设备类别
          parentId='',//上级设备id
          ipAddress='',//TCP设备的ip地址
          ipPort="",//TCP端口号
          serialPort='',//串口路径
          baudRate='',//波特率
          dataBits='',//数据位
          stopBits='',//停止位
          parity='',//校验位
          pictureUrl='',//设备图片
        }= this.formData;
        if(this.mode === 'add'){
          addDevice({siteId,deviceId,deviceName,description,communicationStatus,deviceType,deviceCategory,parentId,ipAddress,ipPort,serialPort,baudRate,dataBits,stopBits,parity,pictureUrl}).then(response => {
            if(response.code === 200){
              //新增成功
              // 关闭弹窗 更新表格
              this.$emit('update')
              this.closeDialog()
            }
          }).finally(() => {
            this.loading-=1
          })
        }else{
          updateDevice({id,siteId,deviceId,deviceName,description,communicationStatus,deviceType,deviceCategory,parentId,ipAddress,ipPort,serialPort,baudRate,dataBits,stopBits,parity,pictureUrl}).then(response => {
            if(response.code === 200){
              //新增成功
              // 关闭弹窗 更新表格
              this.$emit('update')
              this.closeDialog()
            }
          }).finally(() => {
            this.loading-=1
          })
        }

      })
    },
    closeDialog(){
      this.$emit('clear')
      // 清空所有数据
      this.formData= {
        id:'',//设备唯一标识
        siteId:'',//站点ID
        deviceId:'',//设备id
        deviceName:'',//设备名称
        description:'',//设备描述
        communicationStatus:'',//工作状态
        deviceType:'',//设备类型
        deviceCategory:'',//设备类别
        parentId:'',//上级设备id
        ipAddress:'',//TCP设备的ip地址
        ipPort:"",//TCP端口号
        serialPort:'',//串口路径
        baudRate:'',//波特率
        dataBits:'',//数据位
        stopBits:'',//停止位
        parity:'',//校验位
        pictureUrl:'',//设备图片
      }
      this.$refs.addTempForm.resetFields()
      this.dialogTableVisible=false
    }
  }
}

</script>
<style scoped>
</style>
