<script setup lang="ts" name="FormGroup">
import { el } from "element-plus/es/locale";
import { ref, toRefs, reactive, watch, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import {
  queryUser,
  initEdit,
  queryDatadis,
  checkVersion,
  checkRepeatName,
  testConnect,
  add,
} from "@/api/assetLibrary/index";
import { oracleisinsData, getCode } from "@/api/assetLibrary/dict";
import useAppStore from '@/store/modules/app'
const emit = defineEmits(["cancel", "confirm"]);

const appStore = useAppStore()
const props = withDefaults(
  defineProps<{
    id?: string;
    flag?: string;
    page?: string;
    title?: string;
  }>(),
  {
    id: "",
    page: "",
  }
);

const formRef = ref<FormInstance>();
const titleName = ref(props.title);
const pagecodeList = ref([]);
const datadisList = ref([]);
const userList = ref([]);
const readOnly = ref(true);
const modalData = reactive({
  show: false,
  text: "",
  icon: "",
  type: "",
});

const data = reactive({
  form: <any>{
  },
  rules: {
    sysname: [
      {
        required: true,
        message: "请输入数据源名称",
        trigger: ["blur"],
      },
    ],
    dbservername: [
      {
        required: true,
        message: titleName.value === "ORACLE" ? "请输入服务名" : "请输入库名",
        trigger: ["blur"],
      },
    ],
    dbip: [
      { required: true, message: "请输入IP地址", trigger: ["blur"] },
    ],
    dbport: [
      { required: true, message: "请输入端口号", trigger: ["blur"] },
    ],
    servername: [
      { required: true, message: "请输入实例名", trigger: ["blur"] },
    ],
    username: [
      { required: true, message: "请输入用户名", trigger: ["blur"] },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: ["blur"] },
    ],
    version: [
      {
        required: true,
        message: "请选择数据库版本",
        trigger: ["change"],
      },
    ],
    pagecode: [
      {
        required: true,
        message: "请选择字符编码",
        trigger: ["change"],
      },
    ],
  },
});

const { form, rules } = toRefs(data);

// 新增
const onAdd = () => {
  const formData = {
    flag: 1,
    user: form.value.user ? form.value.user : []
  }
  form.value = {...form.value,...formData}
  if (props.page === "edit") {
    form.value = {...form.value, ...{id: form.value.id}}
  } else if (props.page === "add") {
    const username = appStore.userInfo.user.username
    const loginUser = { tsysUser: { username: username }, username: username }
    form.value = {...form.value, ...{loginUser: loginUser,dbtype: titleName.value}}
  }
  
  console.log('add', form.value)
  add(form.value).then((res) => {
    const flag = res.flag;
    if (flag) {
      modalData.icon = "success";
      modalData.text = props.page === "add" ? "新增成功" : "修改成功";
      modalData.show = true;
    }
  });
};

// 确定
const onConfirm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      getCheckRepeatName();
    } else {
    }
  });
};

// 成功回调
const modalConfirm = () => {
  if (modalData.type !== "test") {
    emit("confirm");
    if (props.page === "edit") {
      getInitEdit();
      readOnly.value = true;
    }
  }
  modalData.type = "";
  modalData.show = false;
};

// 关闭回调
const modalCancel = () => {
  if (modalData.icon === "success") {
    emit("confirm");
    if (props.page === "edit") {
      getInitEdit();
      readOnly.value = true;
    }
  }
};

// 取消
const onCancel = () => {
  if (modalData.type !== "test") {
    if (props.page === "add") {
      emit("cancel");
    } else {
      getInitEdit();
      readOnly.value = true;
    }
  }
  modalData.type = "";
  modalData.show = false;
};

// 测试
const test = () => {
  // console.log('测试')
  formRef.value?.validate((valid) => {
    if (valid) {
      getCheckRepeatName("test");
    } else {
    }
  });
};

// 测试数据源名称
const getCheckRepeatName = (type: string = "") => {
  const data = {
    datasystemid: form.value.id,
    sysname: form.value.sysname,
  };
  checkRepeatName(data)
    .then((res) => {
      console.log(res);
      if (res.data) {
        if (type === "test") {
          getTestConnect();
        } else {
          onAdd();
        }
      }
    })
    .catch((err) => {
      // modalData.type = "test";
      // modalData.icon = 'error'
      // modalData.show = true;
    });
};

// 测试连接
const getTestConnect = () => {
  testConnect(form.value).then((res) => {
    if (res.flag) {
      modalData.type = "test";
      modalData.icon = "success";
      modalData.text = "恭喜您，测试通过！";
      modalData.show = true;
    } else {
      modalData.type = "test";
      modalData.icon = "error";
      modalData.text = res.msg;
      modalData.show = true;
    }
  });
};

// 检测
const detection = () => {
  // console.log('检测')
  form.value.dbtype = titleName.value;
  
  checkVersion(form.value).then((res) => {
    const { flag, data, msg } = res
    if (flag) {
      form.value.version = data;
    } else { 
      modalData.type = "test";
      modalData.icon = "error";
      modalData.text = msg;
      modalData.show = true;
    }
  });
};

// 明细查询
const getInitEdit = () => {
  if (!props.id) return;
  const data = {
    id: props.id,
    flag: props.flag,
  };
  initEdit(data).then((res) => {
    // console.log(res)
    form.value = res.data;
    titleName.value = form.value.dbtype
    getQueryDatadis();
    pagecodeList.value = getCode(titleName.value.toLowerCase());
  });
};

// 查询数据库版本
const getQueryDatadis = () => {
  const data = {
    dbtype: titleName.value,
  };
  queryDatadis(data).then((res) => {
    console.log(res);
    datadisList.value = res.data;
  });
};

// 查询用户列表
const getQueryUser = () => {
  queryUser({}).then((res) => {
    userList.value = res.data;
  });
};

// 连接类型监听
const oracleisinsChange = () => {
  if (form.value.oracleisins === "0") {
    form.value.dbservername = "";
    form.value.dbip = "";
    form.value.dbport = "";
    if (props.page === "add") {
      form.value.oracleIns = [];
    }
  } else if (form.value.oracleisins === "1") {
    form.value.oracleIns =
      (form.value.oracleIns && form.value.oracleIns.length > 0)
        ? form.value.oracleIns
        : [{ insip: "", insname: "", insport: "" }];
    form.value.dbservername = "";
    form.value.dbip = "";
    form.value.dbport = "";
  }
};

// 新增实例
const oracleisinsAdd = () => {
  form.value.oracleIns.push({ insip: "", insname: "", insport: "" });
};

// 删除实例
const oracleisinsDelete = () => {
  form.value.oracleIns = form.value.oracleIns.slice(0, -1);
};

watch(
  () => props.id,
  (newVal) => {
    readOnly.value = props.id ? true : false;
    getInitEdit();
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  if (props.page === "add") {
    titleName.value = props.title;
    getQueryDatadis();
    pagecodeList.value = getCode(titleName.value.toLowerCase());
  }
  getQueryUser();
});
</script>

<template>
  <div class="dataList">
    <el-form ref="formRef" class="form" :model="form" :rules="rules" label-width="150px" :disabled="readOnly">
      <el-form-item label="数据源名称" prop="sysname" required>
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.sysname"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="连接类型" prop="oracleisins" v-if="titleName === 'ORACLE'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-select v-model="form.oracleisins" @change="oracleisinsChange">
            <el-option v-for="item in oracleisinsData" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="服务名" prop="dbservername" required
        v-if="titleName === 'ORACLE' && form.oracleisins !== '1'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.dbservername"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="IP地址" prop="dbip" required v-if="form.oracleisins !== '1'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.dbip"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="端口号" prop="dbport" required v-if="form.oracleisins !== '1'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.dbport"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="实例名" prop="servername" required v-if="titleName === 'GBASE8S'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.servername"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="数据库名" prop="dbservername" required
        v-if="titleName !== 'ES' && titleName !== 'KAFKA' && titleName !== 'ORACLE' && titleName !== 'HIVE_TDH'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.dbservername"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="HIVE 数据库名" prop="dbservername" required v-if="titleName === 'HIVE_TDH'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.dbservername"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="Driver Classpath" prop="Classpath" v-if="titleName === 'HIVE'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.Classpath"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="用户名" prop="username" required v-if="titleName !== 'KAFKA'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.username"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="密码" prop="password" required v-if="titleName !== 'KAFKA'">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.password" show-password></el-input>
        </div>
      </el-form-item>
      <el-form-item label="数据库版本" prop="version" :required="titleName !== 'KAFKA'" >
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;display: flex;">
          <el-input v-model="form.version" v-if="readOnly"></el-input>
          <el-select v-model="form.version" v-if="!readOnly">
            <el-option v-for="item in datadisList" :key="item.dictvalue" :label="item.dictvalue"
              :value="item.dictvalue">
            </el-option>
          </el-select>
          <el-button type="primary" @click="detection" v-if="!readOnly">检测</el-button>
        </div>
      </el-form-item>
      <el-form-item label="字符编码" prop="pagecode" required>
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-input v-model="form.pagecode" v-if="readOnly"></el-input>
          <el-select v-model="form.pagecode" v-if="!readOnly">
            <el-option v-for="item in pagecodeList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="授权用户" prop="user">
        <div style="width: 100%;background: #F3F5FA;margin-left: 4px;">
          <el-select v-model="form.user" multiple>
            <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <div class="oracleisinsBox" v-if="form.oracleisins === '1'">
        <div class="title">请新增oracle实例</div>
        <div class="top">
          <span>oracle实例</span>
          <div class="oracleInsBut">
            <el-button type="info" link icon="Plus" @click="oracleisinsAdd">新增</el-button>
            <el-button type="info" link icon="Minus" @click="oracleisinsDelete">删除</el-button>
          </div>
        </div>
        <el-table :data="form.oracleIns" border style="width: 100%">
          <el-table-column prop="insname" label="实例名" align="center">
            <template #default="scope">
              <el-form-item label="" label-width="0" :prop="`oracleIns.${scope.$index}.insname`"
                :rules="[{ required: true, message: '请输入实例名', trigger:'blur' }]">
                <el-input v-model="scope.row.insname"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="insip" label="IP地址" align="center">
            <template #default="scope">
              <el-form-item label="" label-width="0" :prop="`oracleIns.${scope.$index}.insip`"
                :rules="[{ required: true, message: '请输入IP地址', trigger:'blur' }]">
                <el-input v-model="scope.row.insip"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="insport" label="端口号" align="center">
            <template #default="scope">
              <el-form-item label="" label-width="0" :prop="`oracleIns.${scope.$index}.insport`"
                :rules="[{ required: true, message: '请输入端口号', trigger:'blur' }]">
                <el-input v-model="scope.row.insport"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <div class="buttonBox mt20">
      <el-button v-if="!readOnly" type="primary" style="width: 150px;" @click="onConfirm">确认</el-button>
      <el-button v-if="!readOnly" type="primary" style="width: 150px;" @click="test">测试</el-button>
      <el-button v-if="!readOnly" type="info" style="width: 150px;" @click="onCancel">取消</el-button>
      <el-button v-if="readOnly" type="primary" style="width: 150px;" @click="readOnly = false">编辑</el-button>
    </div>
    <Modal v-model="modalData.show" :icon="modalData.icon" :cancel="false" :text="modalData.text"
      @confirm="modalConfirm" @cancel="modalCancel">
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.buttonBox {
  display: flex;
  justify-content: center;
}
.form {
  :deep(.el-form-item__label) {
    background: #f0f0f0;
  }
  :deep(.el-input__wrapper) {
    // background: rgba(255, 255, 255, 0);
    // box-shadow: none;
  }
  :deep(.el-form-item) {
    margin-bottom: 5px;
  }
  :deep(.el-select__wrapper) {
    // background: rgba(255, 255, 255, 0);
    // box-shadow: none;
  }
  :deep(.el-form-item__error) {
    left: auto;
    right: 83px;
    top: 24%;
}
}
.oracleisinsBox {
  .title {
    height: 30px;
    line-height: 30px;
    font-weight: 700;
    color: rgb(81, 90, 110);
  }
  .top {
    position: relative;
    text-align: center;
    height: 40px;
    line-height: 40px;
    font-weight: 700;
    position: relative;
    margin-bottom: 5px;
    background: rgb(210, 210, 210);
    .oracleInsBut {
      position: absolute;
      top: 0;
      right: 20px;
      height: 100%;
      :deep(.is-link) {
        color: rgb(81, 90, 110);
        font-weight: bold;
      }
    }
  }
  :deep(.el-form-item__error){
    right: 10px;
  }
}
</style>

