<template>
  <div class="app-container">
    <template v-if="!showDesktopConn">
      <el-row :gutter="20">
        <!-- 远程桌面数据 -->
        <el-col :span="24" :xs="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="桌面名称" prop="desktopName">
              <el-input v-model="queryParams.desktopName" placeholder="请输入桌面名称" clearable style="width: 240px"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="IP地址" prop="vncIp">
              <el-input v-model="queryParams.vncIp" placeholder="请输入IP地址" clearable style="width: 240px"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['vnc:item:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['vnc:item:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                @click="handleDelete" v-hasPermi="['vnc:item:remove']">删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="vncDesktopList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column :label="columns[0].label" align="center" key="id" prop="id" v-if="columns[0].visible" />
            <el-table-column :label="columns[1].label" align="center" key="desktopName" prop="desktopName"
              v-if="columns[1].visible" :show-overflow-tooltip="true" />
            <el-table-column :label="columns[2].label" align="center" key="vncIp" prop="vncIp" v-if="columns[2].visible"
              :show-overflow-tooltip="true" />
            <el-table-column :label="columns[3].label" align="center" key="vncPort" prop="vncPort"
              v-if="columns[3].visible" />
            <el-table-column :label="columns[4].label" align="center" key="userName" prop="userName"
              v-if="columns[4].visible" :show-overflow-tooltip="true" />
            <el-table-column :label="columns[5].label" align="center" key="path" prop="path" v-if="columns[5].visible"
              :show-overflow-tooltip="true" />
            <el-table-column :label="columns[6].label" align="center" key="sortNum" prop="sortNum"
              v-if="columns[6].visible" />
            <el-table-column :label="columns[7].label" align="center" prop="createTime" v-if="columns[7].visible"
              width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
              <template slot-scope="scope" v-if="scope.row.userId !== 1">
                <el-button size="mini" type="text" icon="el-icon-s-platform" @click="handleConn(scope.row)"
                  v-hasPermi="['vnc:item:conn']">远程</el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['vnc:item:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['vnc:item:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-col>
      </el-row>
    </template>
    <template v-else>
      <el-row>
        <el-button type="danger" size="mini" style="margin-bottom: 10px;" icon="el-icon-error"
          @click="closeConnDesktop">断开连接</el-button>
      </el-row>
      <el-row :gutter="20">
        <i-frame style="height: calc(100vh - 165px)" :src="vncDesktopPath" />
      </el-row>
    </template>
    <!-- 添加或修改远程管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="60%" @close="cancel"
      destroy-on-close append-to-body>
      <el-form ref="formDataref" :model="formData" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="桌面名称" prop="desktopName">
              <el-input v-model="formData.desktopName" placeholder="请输入桌面名称" maxlength="255" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="IP地址" prop="vncIp">
              <el-input v-model="formData.vncIp" placeholder="请输入IP地址信息" maxlength="255" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="端口信息" prop="vncPort">
              <el-input v-model="formData.vncPort" placeholder="请输入IP地址访问的端口信息" maxlength="255" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="formData.userName" placeholder="请输入用户名" maxlength="255" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入用户密码" maxlength="255" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="排序号" prop="sortNum">
              <el-input v-model.trim="formData.sortNum" placeholder="请输入排序号（数字越大越靠前）"
                oninput="value=value.replace(/[^\d]/g,'')" maxlength="5" @blur="formData.sortNum=$event.target.value" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="访问地址" prop="path">
              <el-input v-model="formData.path" placeholder="请输入访问地址" maxlength="255" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { delVncDesktop, listVncDesktop, addVncDesktop, updateVncDesktop, getVncDesktop } from '@/api/matter/vnc'
  import iFrame from '@/components/iFrame/index.vue'

  export default {
    name: "Vnc",
    components: { iFrame },
    data() {
      let validatevncIp = (rule, value, callback) => {
        var reg = /^(?:(?: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]?)$/;
        if (!reg.test(value)) {
          callback(
            new Error("IP地址格式不正确")
          );
        } else {
          callback();
        }
      };
      let validatevncPort = (rule, value, callback) => {
        var reg = /^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-6][0-5][0-5][0-3][0-5]$)/;
        if (!reg.test(value)) {
          callback(
            new Error("端口号格式不正确")
          );
        } else {
          callback();
        }
      };
      return {
        // 弹出层标题
        title: "",
        open: false,
        // 表单参数
        formData: {},
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 显示搜索条件
        showSearch: true,
        // 显示远程连接
        showDesktopConn: false,
        // 远程连接地址
        vncDesktopPath: undefined,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          desktopName: undefined,
          vncIp: undefined
        },
        // 总条数
        total: 0,
        // 远程桌面表格数据
        vncDesktopList: null,
        // 列信息
        columns: [
          { key: 0, label: `远程编号`, visible: true },
          { key: 1, label: `桌面名称`, visible: true },
          { key: 2, label: `IP地址`, visible: true },
          { key: 3, label: `端口号`, visible: true },
          { key: 4, label: `用户名`, visible: true },
          { key: 5, label: `远程地址`, visible: true },
          { key: 6, label: `排序号`, visible: true },
          { key: 7, label: `创建时间`, visible: true }
        ],
        // 表单校验
        rules: {
          desktopName: [
            { required: true, message: "桌面名称不能为空", trigger: "blur" },
            {
              required: true,
              transform: (value) => value && value.trim(),
              message: '桌面名称不能全部为空',
              trigger: 'blur'
            }
          ],
          vncIp: [
            { required: true, message: "ip地址不能为空", trigger: "blur" },
            { required: true, validator: validatevncIp, trigger: "blur" },
          ],
          vncPort: [
            { required: true, message: "ip地址端口不能为空", trigger: "blur" },
            { required: true, validator: validatevncPort, trigger: "blur" }
          ],
          sortNum: [{ required: true, message: "排序号不能为空", trigger: "blur" }],
        },
      };
    },
    watch: {
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询远程桌面列表 */
      getList() {
        this.loading = true;
        listVncDesktop(this.queryParams).then(response => {
          this.vncDesktopList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
        );
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.title = "添加远程管理";
        this.open = true;
        this.reset();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.title = "修改远程管理";
        const ids = row.id || this.ids;
        getVncDesktop(ids).then((response) => {
          var data = response.data;
          this.formData = {
            desktopName: data.desktopName,
            id: data.id,
            vncIp: data.vncIp,
            vncPort: data.vncPort,
            userName: data.userName,
            password: data.password,
            sortNum: data.sortNum,
            path: data.path
          }
        });
        this.open = true;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除所选择的数据项？', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'custom-confirm-class',
          closeOnClickModal: false // 设置为false表示点击modal区域不关闭
        }).then(function () {
          return delVncDesktop(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 远程连接操作 */
      handleConn(row) {
        this.showDesktopConn = true
        if (row.path) {
          this.vncDesktopPath = row.path
        } else {
          this.vncDesktopPath = 'http://' + row.vncIp + ':' + row.vncPort
        }
      },
      /** 断开远程连接 **/
      closeConnDesktop() {
        this.vncDesktopPath = undefined
        this.showDesktopConn = false
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 多选框选中数据 **/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 表单重置 **/
      reset() {
        this.formData = {
          desktopName: "",
          vncIp: "",
          vncPort: "",
          userName: "",
          password: "",
          sortNum: "",
          path: "",
        }
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["formDataref"].validate((valid) => {
          if (valid) {
            var data = this.formData;
            var params = {
              desktopName: data.desktopName,
              id: data.id ? data.id : "",
              vncIp: data.vncIp,
              vncPort: data.vncPort,
              userName: data.userName,
              password: data.password,
              sortNum: data.sortNum,
              path: data.path
            }
            if (this.formData.id != undefined) {
              updateVncDesktop(params).then((response) => {
                console.log(response)
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addVncDesktop(params).then((response) => {
                console.log(response)
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      // 取消按钮
      cancel() {
        this.$refs.formDataref.resetFields();
        this.open = false;
        this.reset();
      },
    }
  };
</script>