<template>
  <el-dialog
   v-model="visible"
   title="设备管理"
   width="60%"
   :before-close="closeDialog"
 >
   <el-card class="top-title">
     <span>通讯名称：{{ addForm.name }}</span>
     <span>通讯描述：{{ addForm.description }}</span>
     <span>通讯主机：{{ addForm.host }}</span>
   </el-card>
   <div class="btns">
     <div>
         <el-button type="primary" @click="saveSet"> 保存 </el-button>
         <el-button @click="closeDialog">取消</el-button>
     </div>
     <div>
         <el-button type="primary" @click="scanData"> 扫描 </el-button>
          
     </div>
   </div>
   <div>
     <el-table
       :data="propertiesData"
       height="230"
       style="width: 100%"
       border
       stripe
       :header-cell-style="{ background: '#F6F7FC' }"
     >
       <el-table-column
         prop="name"
         label="设备名称"
         align="center"
         show-overflow-tooltip
       >
         <template #default="scope">
           <el-input
             v-model="scope.row.name"
             clearable
           />
         </template>
       </el-table-column>
       <el-table-column
         prop="ID"
         label="设备id"
         align="center"
         show-overflow-tooltip
       >
         <template #default="scope">
           <el-input
             v-model="scope.row.ID"
             clearable
           />
         </template>
       </el-table-column>
       <el-table-column
         prop="template"
         label="数据模板"
         align="center"
         show-overflow-tooltip
       >
         <template #default="scope">
           <el-select v-model="scope.row.template" clearable placeholder="请选择模板" size="mini">
             <el-option
               v-for="item in modelArr"
               :key="item.name"
               :label="item.name"
               :value="item.name"
               
             />
           </el-select>
         </template>
       </el-table-column>
      
       <el-table-column
         prop="description"
         label="设备描述"
         align="center"
         show-overflow-tooltip
       >
         <template #default="scope">
           <el-input
             v-model="scope.row.description"
             clearable
           />
         </template>
       </el-table-column>
       <el-table-column label="操作" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="danger" @click="delData(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
     </el-table>
     <div class="flex-center" @click="addRow">
       +新增一行
     </div>
   </div>
 </el-dialog>
</template>
<script>
import { onMounted, reactive, ref, toRefs, computed, nextTick } from "vue";
import infoApi from "@/api/infoApi.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { mb_list, tx_info, response, m_device, m_properties, tx_add_device} from '../proto/data/pd'
export default {
 props: ["formData", "dialogVisible"],
 emits: ["dialogClose", "dialogSuccess"],
 setup(props, ctx) {
   const state = reactive({
     addForm: {},
     propertiesData: [],
     modelArr: []
   });
   const visible = computed(() => {
     return props.dialogVisible;
   });

   onMounted(() => {
     state.addForm = props.formData;
     console.log(123, props.formData)
    // 获取模板数据
    getMbData();
    // 获取点位列表
    getSetList();
   });
   const getMbData = async () => {
      const res = await infoApi.getMb();
      const ret = response.decode(new Uint8Array(res));
      
      if (ret.code == 0) {
          // 获取数据
          state.modelArr = mb_list.decode(ret.data).mb;
          console.log(mb_list.decode(ret.data).mb);
      } else {
          console.log(res);
      }
    };
   const getSetList = async() => {
     const parm = tx_info.encode({
         name: state.addForm.name
     }).finish();
     // 截取有效长度
     const parm_data = parm.slice(0, parm.length);
     const res = await infoApi.getSet(parm_data);
     const ret = response.decode(new Uint8Array(res));
     if (ret.code == 0) {
        console.log(99, tx_info.decode(ret.data).device);
        const propArr = tx_info.decode(ret.data).device;
        state.propertiesData = [];
        propArr.forEach(v => {
          state.propertiesData.push({
            name: v.name,
            ID: v.properties[0].value,
            template: v.properties[1].value,
            description: v.properties[2].value,
          })
        })
         
        
     } else {
        console.log(res);
     }
   };
   const closeDialog = () => {
     ctx.emit("dialogClose");
   };

   const scanData = () => {};

   const saveSet = async () => {
    if (state.propertiesData.length < 1) {
        return ElMessage.error("请至少添加一条数据");
      }
      const newArr = [];
      state.propertiesData.forEach(item => {
        newArr.push({
          name: item.name,
          properties: [
            {
            name: 'ID', value: item.ID
            },{
              name: 'template', value: item.template
            },{
              name: 'description', value: item.description
            }]
        })
      })
      
      const req_databuf = tx_add_device.encode({
          name: state.addForm.name,
          device: newArr
      }).finish();
      
      // 截取有效长度
      const req_data = req_databuf.slice(0, req_databuf.length);
      const res = await infoApi.addSet(req_data);
      const ret = response.decode(new Uint8Array(res));
      
      if (ret.code == 0) {
        console.log(new TextDecoder().decode(ret.data));
        ElMessage.success(new TextDecoder().decode(ret.data) || "请求成功");
        // 获取数据
        getSetList();
      }
         
   };
   const addRow = () => {
     let newRow = { 
       name: '', 
       address: '', 
       datatype: 'bool',
       byteorder: 'null', 
       multplier: '', 
       unit: '',
       description: ''
      };
     state.propertiesData.push(newRow);
   }
   const delData = (index) => {
      state.propertiesData.splice(index, 1);
    }
   return {
     ...toRefs(state),
     visible,
     closeDialog,
     scanData,
     addRow,
     saveSet,
     delData,
     getMbData
   };
 },
};
</script>
<style lang="scss" scoped>
.top-title {
 width: 100%;
 ::v-deep .el-card__body {
   width: 100%;
   display: flex;
   justify-content: space-between;
   font-weight: 800;
   font-size: 16px;
 }
} 
.btns {
 padding: 15px 0;
 width: 100%;
 display: flex;
 justify-content: space-between;
}
.flex-center {
 display: flex;
 justify-content: center;
 padding: 10px 0;
 cursor: pointer;
}
</style>
