<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.type }}</span>
    </el-card>
    <div class="btns">
      <div>
          <el-button type="primary" @click="saveP"> 保存 </el-button>
          <el-button @click="closeDialog">取消</el-button>
      </div>
      <div>
          <el-button type="primary" @click="importData"> 导入 </el-button>
          <el-button type="primary" @click="exportData"> 导出 </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="address"
          label="点位地址"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.address"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="datatype"
          label="点位类型"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-select v-model="scope.row.datatype" size="mini">
              <el-option
                v-for="item in datatypeArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="byteorder"
          label="字节顺序"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-select v-model="scope.row.byteorder" size="mini">
              <el-option
                v-for="item in byteorderArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="multplier"
          label="缩放系数"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.multplier"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="unit"
          label="点位单位"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.unit"
              clearable
            />
          </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 { m_point, m_properties, mb_info, response} from '../proto/data/pd'
export default {
  props: ["formData", "dialogVisible"],
  emits: ["dialogClose", "dialogSuccess"],
  setup(props, ctx) {
    const state = reactive({
      addForm: {},
      propertiesData: [],
      datatypeArr: [{
        label: 'bool',
        value: 'bool'
      },{
        label: 'int16',
        value: 'int16'
      },{
        label: 'int32',
        value: 'int32'
      },{
        label: 'unit16',
        value: 'unit16'
      },{
        label: 'unit32',
        value: 'unit32'
      },{
        label: 'float32',
        value: 'float32'
      },{
        label: 'float64',
        value: 'float64'
      }],
      byteorderArr: [{
        label: 'null',
        value: 'null'
      },{
        label: '12',
        value: '12'
      },{
        label: '21',
        value: '21'
      },{
        label: '1234',
        value: '1234'
      },{
        label: '4321',
        value: '4321'
      },{
        label: 'ABCD',
        value: 'ABCD'
      },{
        label: 'DCBA',
        value: 'DCBA'
      }]
    });
    const visible = computed(() => {
      return props.dialogVisible;
    });

    onMounted(() => {
      state.addForm = props.formData;
      console.log(123, props.formData)
      // 获取点位列表
      getPointList();
    });
    const getPointList = async() => {
      const parm = mb_info.encode({
          name: state.addForm.name
      }).finish();
      // 截取有效长度
      const parm_data = parm.slice(0, parm.length);
      const res = await infoApi.getP(parm_data);
      const ret = response.decode(new Uint8Array(res));
      if (ret.code == 0) {
        const propArr = mb_info.decode(ret.data).points;
        state.propertiesData = [];
        propArr.forEach(v => {
          state.propertiesData.push({
            name: v.name, 
            address: v.properties[0].value, 
            datatype: v.properties[1].value, 
            byteorder: v.properties[2].value, 
            multplier: v.properties[3].value, 
            unit: v.properties[4].value, 
            description: v.properties[5].value, 
          })
        })
      } else {
          console.log(res);
      }
    };
    const closeDialog = () => {
      ctx.emit("dialogClose");
    };

    const importData = () => {};

    const exportData = () => {};

    const saveP = async () => {
      if (state.propertiesData.length<1) {
        return ElMessage.error("请添加一条点位");
      }
      const newArr = [];
      state.propertiesData.forEach(item => {
        newArr.push(m_point.create({
          name: item.name,
          properties: [
            m_properties.create({
              name: 'address',value:item.address
            }),
            m_properties.create({
              name: 'datatype',value:item.datatype
            }),
            m_properties.create({
              name: 'byteorder',value:item.byteorder
            }),
            m_properties.create({
              name: 'multplier',value:item.multplier
            }),
            m_properties.create({
              name: 'unit',value:item.unit
            }),
            m_properties.create({
              name: 'description',value:item.description
            })
          ]
        }))
      })
      console.log(123, newArr)
      const req_databuf = mb_info.encode({
          name: state.addForm.name,
          type: state.addForm.type,
          description: state.addForm.description,
          points: newArr
      }).finish();
      // 截取有效长度
      const req_data = req_databuf.slice(0, req_databuf.length);
      const res = await infoApi.addP(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) || "请求成功");
        // 获取数据
        getPointList();
      }
          
    };
    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,
      importData,
      exportData,
      addRow,
      saveP,
      delData
    };
  },
};
</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>
