<template>
  <el-dialog
    v-model="visible"
    :title="type == '1' ? '编辑' : '新增'"
    width="45%"
    :before-close="closeDialog"
  >
    <el-form
      label-position="top"
      :model="formData"
      label-width="150px"
      :rules="rules"
      ref="ruleFormRef"
    >
      <el-form-item label="通讯名称:" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入驱动名称"
          clearable
          :disabled="type == '1'"
        />
      </el-form-item>
      <el-form-item label="通讯驱动:" prop="drive" >
        <el-select
          v-model="formData.drive"
          value-key="name"
          clearable
          placeholder="请选择通讯驱动"
          @change="driveChange"
          :disabled="type == '1'"
        >
          <el-option
            v-for="(item, index) of qudongOptions"
            :key="index"
            :label="item.name"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="驱动描述:" prop="description">
        <el-input
          v-model="formData.description"
          placeholder="请输入描述"
          clearable
        ></el-input>
      </el-form-item>
      <!-- 驱动1 -->
      <div v-if="serialConfig">
        <el-form-item label="COM口:">
          <el-select
            v-model="configData.name"
            placeholder="请选择COM口"
            clearable
            @change="selsectCom"
            >
            <el-option
              v-for="(item, index) of com_select"
              :key="index"
              :label="item.name"
              :value="item.name"
              :disabled="item.used"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="波特率:">
          <el-select
            v-model="configData.baudRate"
            placeholder="请选择波频率"
            clearable
          >
            <el-option
              v-for="(item, index) of baud_rate_select"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="校验位:">
          <el-select
            v-model="configData.parity"
            placeholder="请选择校验位"
            clearable
          >
            <el-option
              v-for="(item, index) of parity_select"
              :key="index"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据位:">
          <el-select
            v-model="configData.dataBits"
            placeholder="请选择波频率"
            clearable
          >
            <el-option
              v-for="(item, index) of data_bits_select"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="停止位:">
          <el-select
            v-model="configData.stopBits"
            placeholder="请选择波频率"
            clearable
          >
            <el-option
              v-for="(item, index) of stop_bits_select"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="超时时间:" >
          <el-select
            v-model="configData.timeout"
            placeholder="请选择超时时间"
            clearable
          >
            <el-option
              v-for="(item, index) of timeout_select"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </div>
      <!-- 驱动2 -->
      <div v-if="modbusTCPConfig">
        <el-form-item label="主机地址:">
          <el-input
            v-model="configData1.port"
            placeholder="请输入模板描述"
            clearable
          />
        </el-form-item>
        <el-form-item label="主机端口:">
          <el-input
            v-model="configData1.host"
            placeholder="请输入模板描述"
            clearable
          />
        </el-form-item>
      </div>
    </el-form>

      
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveData"> 保存 </el-button>
      </span>
    </template>
  </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 { response, tx_list, com_info, com_list, tx_drive_list, tx_add, tx_info, tx_drive_config_modbusTCP } from '../proto/data/pd'
export default {
  props: ["formData", "dialogVisible", "type", "qudongOptions"],
  emits: ["dialogClose", "dialogSuccess"],
  setup(props, ctx) {
    const ruleFormRef = ref(null);
    const validName = (rule, value, callback) => {
      var name = /^[a-zA-Z]([_\w]*)$/;
      if (name.test(value) || !value) {
        callback();
      } else {
        callback(new Error("通讯名称格式不正确,支持英文数字和下划线"));
      }
    };
    const state = reactive({
      serialConfig: false,
      modbusTCPConfig: false,
      com_select: [],
      comArr: [],
      configData: {
        name: '',
        baudRate: '',
        parity: '',
        dataBits: '',
        stopBits:'',
        timeout:'',
      },
      configData1: {
        port: '',
        host: ''
      },
      baud_rate_select: [9600, 115200],
      parity_select:[
          { text: "无校验", value: "N" },
          { text: "偶校验", value: "E" },
          { text: "奇校验", value: "O" }
      ],
      data_bits_select: [5, 6, 7, 8],
      stop_bits_select: [1, 2],
      timeout_select: [0, 100, 200, 500, 1000, 2000],
      rules: {
        name: [
          { required: true, message: "请输入通讯名称", trigger: "blur" },
          { required: true, validator: validName, trigger: "blur" },
        ],
        description: [{ required: true, message: "请输入驱动描述", trigger: "blur" }],
        drive: [{ required: true, message: "请选择通讯驱动", trigger: "blur" }],
        // com: [{ required: true, message: "请选择COM口", trigger: "blur" }],
        // baudRate: [{ required: true, message: "请选择波特率", trigger: "blur" }],
        // parity: [{ required: true, message: "请选择校验位", trigger: "blur" }],
        // dataBits: [{ required: true, message: "请选择数据位", trigger: "blur" }],
        // stopBits: [{ required: true, message: "请选择停止位", trigger: "blur" }],
        // timeout: [{ required: true, message: "请选择超时时间", trigger: "blur" }],
        // port: [{ required: true, message: "请填写主机地址", trigger: "blur" }],
        // host: [{ required: true, message: "请填写主机端口", trigger: "blur" }]
      },
    });
    const visible = computed(() => {
      return props.dialogVisible;
    });

    onMounted(async () => {
      if (props.type === '1') {
        if (props.formData.serial) {
          state.serialConfig = true;
          state.modbusTCPConfig = false;
          // 获取com,比对赋值
          getCom();
        } else {
          state.serialConfig = false;
          if (props.formData.drive == "modbusTCP") {
            state.modbusTCPConfig = true;
            // 直接赋值
            state.configData1 = {
              port: props.formData.host.split(":")[0],
              host: props.formData.host.split(":")[1]
            }
          }
        }
      }
      
    });
    const closeDialog = () => {
      ctx.emit("dialogClose");
    };
    const saveData = async () => {
      await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          let req_configbuf;
          if (props.type==='0') {
              if (props.formData.drive.serial) {
                req_configbuf = com_info.encode(state.configData).finish();
              } else {
                if (props.formData.drive.name == "modbusTCP") {
                  req_configbuf = tx_drive_config_modbusTCP.encode(state.configData1).finish();
                }
              }
              var obj = {
                  name: props.formData.name,
                  drive: props.formData.drive.name,
                  description: props.formData.description,
                  serial: props.formData.drive.serial,
                  config: req_configbuf.slice(0, req_configbuf.length),
              };
              console.log('编辑数据3', obj);
          } else {
            console.log('编辑数据1', state.configData)
            console.log('编辑数据2', state.configData1)
            if (props.formData.serial) {
              req_configbuf = com_info.encode(state.configData).finish();
            } else {
              if (props.formData.drive == "modbusTCP") {
                req_configbuf = tx_drive_config_modbusTCP.encode(state.configData1).finish();
              }
            }
            obj = {
              name: props.formData.name,
              drive: props.formData.drive,
              description: props.formData.description,
              serial: props.formData.serial,
              config: req_configbuf.slice(0, req_configbuf.length),
            };
            console.log('编辑数据3', obj);
          }
          
         
          const req_databuf = tx_add.encode(obj).finish();
          // 截取有效长度
          const req_data = req_databuf.slice(0, req_databuf.length);
          const res = props.type === '0' ? await infoApi.saveTx(req_data) : await infoApi.editTx(req_data);
          const ret = response.decode(new Uint8Array(res));
          if (ret.code == 0) {
            ElMessage.success(res.msg || "请求成功");
            ctx.emit("dialogSuccess");
          } else {
            ElMessage.error(res.msg || "请求失败");
          }
        } else {
          console.log("error submit!");
        }
      });
    };
    const driveChange = () => {
      // 如果是串口协议
      if (props.formData.drive.serial) {
        state.serialConfig = true;
        state.modbusTCPConfig = false;
        // 获取com
        getCom();
        
      } else {
        state.serialConfig = false;
        if (props.formData.drive.name == "modbusTCP") {
          state.modbusTCPConfig = true;
        }
      }
    }
    // 获取com
    const getCom = async () => {
      const res = await infoApi.getCom();
      const ret = response.decode(new Uint8Array(res));
      if (ret.code == 0) {
        const infodata = com_list.decode(ret.data);
        state.comArr = infodata.com;
        console.log('comlist',state.comArr)
        state.com_select = [];
        infodata.com.forEach(e => {
          if (!e.used) {
            state.com_select.push(e);
          }
        });
        // 编辑赋值
        if (props.type === '1') {
          const config = infodata.com.filter(item => item.name === props.formData.host)[0];
          state.configData = {
            name: config.name,
            baudRate: config.baudRate,
            parity: config.parity,
            dataBits: config.dataBits,
            stopBits: config.stopBits,
            timeout: config.timeout,
          }
        } 
        if (state.com_select.length == 0) {
          ElMessage.info("没有可用串口，请选择其他驱动");
        }
      }
    }
    // 选择 com 回填数据
    const selsectCom = () => {
      const c = state.comArr.filter(item => item.name === state.configData.name)[0];
      state.configData = {
        name: c.name,
        baudRate: c.baudRate,
        parity: c.parity,
        dataBits: c.dataBits,
        stopBits: c.stopBits,
        timeout: c.timeout,
      }
    }
    
    return {
      ...toRefs(state),
      ruleFormRef,
      visible,
      saveData,
      closeDialog,
      driveChange,
      getCom,
      selsectCom
    };
  },
};
</script>
<style lang="scss" scoped>
.inline-div {
  display: flex;
  width: 100%;
  .el-form-item {
    margin-right: 10px;
    width: 175px;
  }
}
</style>
