<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", "onDelete"]);

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

const formRef = ref<FormInstance>();
const titleName = ref('');
const dbtypeData = ref({
  type: 0,
  list: []
})
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>{
    user: [],
  },
  rules: {
    dbtype: [
      {
        required: true,
        message: "请选择数据源类型",
        trigger: ["change"],
      },
    ],
    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.map((item) => {
          return { id: item };
        })
      : [],
  };
  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;
    form.value.user = form.value.user
      ? form.value.user.map((item) => {
          return item.id;
        })
      : [];
    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 = (index) => {
  form.value.oracleIns.splice(index, 1);
};

// 删除
const onDelete = () => {
  emit("onDelete", form.value);
};

const titleNameChange = () => {
  // dbtypeData
  dbtypeData.value.type = 0
  formRef.value?.resetFields()
  const currentData = props.typeData.find((item) => item.name === titleName.value);
  dbtypeData.value = Object.assign({...dbtypeData.value, ...currentData})
  if (dbtypeData.value.type !== 4) {
    if (titleName.value === 'ORACLE') {
      form.value.oracleisins = '0'
    }else{
      form.value.oracleisins = ''
    }
    form.value.dbtype = titleName.value
    getQueryDatadis();
    pagecodeList.value = getCode(titleName.value.toLowerCase());
  }else{
    form.value.dbtype = ''
  }
}

const dbtypeChange = () => {
  getQueryDatadis();
  pagecodeList.value = getCode(titleName.value.toLowerCase());
}


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

onMounted(() => {
  getQueryUser();
});
</script>

<template>
  <div class="dataList">
    <el-form ref="formRef" class="form" :model="form" :rules="rules" label-width="150px" :disabled="readOnly" :label-position="page === 'add' ? 'left' : 'right'">
      <DividerTitle title-name="数据源明细" />
      <div class="foundationBox">
        <el-row :gutter="page === 'add' ? 50 : 0">
          <el-col :span="(page === 'add' && dbtypeData.type === 0) ? 12 : 24" v-if="page === 'add'">
            <el-row :gutter="50">
              <el-col :span="dbtypeData.type === 0 ? 24 : 12">
                <el-form-item label="数据源类型" prop="dbtype" required>
                  <div class="inputBox">
                    <el-select v-model="titleName" @change="titleNameChange" placeholder="请选择数据源类型">
                      <el-option v-for="item in typeData" :key="item.name" :label="item.name"
                        :value="item.name">
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="1" v-if="dbtypeData.type === 4" style="padding: 0;">
                <div style="width: 100%;height: 1px;background-color: #D2DCE7;margin-top: 36%;display: flex;justify-content: center;"></div>
              </el-col>
              <el-col :span="4" v-if="dbtypeData.type === 4" style="padding-left: 0;">
                <el-form-item label="" label-width="0"  prop="dbtype" required>
                  <div class="inputBox">
                    <el-select v-model="form.dbtype" @change="dbtypeChange" placeholder="请选择数据源类型">
                      <el-option v-for="item in dbtypeData.list" :key="item.name" :label="item.name"
                        :value="item.name">
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24">
            <el-form-item label="数据源名称" prop="sysname" required>
              <div class="inputBox">
                <el-input v-model="form.sysname" placeholder="请输入数据源名称"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype === 'ORACLE'">
            <el-form-item label="连接类型" prop="oracleisins">
              <div class="inputBox">
                <el-select v-model="form.oracleisins" @change="oracleisinsChange" placeholder="请选择连接类型">
                  <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-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype === 'ORACLE' && form.oracleisins !== '1'">
            <el-form-item label="服务名" prop="dbservername" required>
              <div class="inputBox">
                <el-input v-model="form.dbservername" placeholder="请输入服务名"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.oracleisins !== '1'">
            <el-form-item label="IP地址" prop="dbip" required>
              <div class="inputBox">
                <el-input v-model="form.dbip" placeholder="请输入IP地址"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.oracleisins !== '1'">
            <el-form-item label="端口号" prop="dbport" required>
              <div class="inputBox">
                <el-input v-model="form.dbport" placeholder="请输入端口号"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype === 'GBASE8S'">
            <el-form-item label="实例名" prop="servername" required >
              <div class="inputBox">
                <el-input v-model="form.servername" placeholder="请输入实例名"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype !== 'ES' && form.dbtype !== 'KAFKA' && form.dbtype !== 'ORACLE' && form.dbtype !== 'HIVE_TDH'">
            <el-form-item label="数据库名" prop="dbservername" required>
              <div class="inputBox">
                <el-input v-model="form.dbservername" placeholder="请输入数据库名"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype === 'HIVE_TDH'">
            <el-form-item label="HIVE 数据库名" prop="dbservername" required>
              <div class="inputBox">
                <el-input v-model="form.dbservername" placeholder="请输入数据库名"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype === 'HIVE'">
            <el-form-item label="Driver Classpath" prop="Classpath">
              <div class="inputBox">
                <el-input v-model="form.Classpath" placeholder="请输入Driver Classpath"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype !== 'KAFKA'">
            <el-form-item label="用户名" prop="username" required>
              <div class="inputBox">
                <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24" v-if="form.dbtype !== 'KAFKA'">
            <el-form-item label="密码" prop="password" required>
              <div class="inputBox">
                <el-input v-model="form.password" show-password placeholder="请输入密码"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24">
            <el-form-item label="数据库版本" prop="version" :required="form.dbtype !== 'KAFKA'">
              <div class="inputBox" style="display: flex;align-items: center;">
                <el-input v-model="form.version" v-if="readOnly"></el-input>
                <el-select v-model="form.version" v-if="!readOnly" placeholder="请选择数据库版本">
                  <el-option v-for="item in datadisList" :key="item.dictvalue" :label="item.dictvalue"
                    :value="item.dictvalue">
                  </el-option>
                </el-select>
                <el-button type="primary" style="width: 60px;height: 90%;margin-left: 5px;border-radius: 0;"
                  @click="detection" v-if="!readOnly">检测</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24">
            <el-form-item label="字符编码" prop="pagecode" required>
              <div class="inputBox">
                <el-input v-model="form.pagecode" v-if="readOnly"></el-input>
                <el-select v-model="form.pagecode" v-if="!readOnly" placeholder="请选择字符编码">
                  <el-option v-for="item in pagecodeList" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="page === 'add' ? 12 : 24">
            <el-form-item label="授权用户" prop="user">
              <div class="inputBox">
                <div class="userEmpty" v-if="readOnly && form.user.length <= 0">—</div>
                <el-select v-model="form.user" multiple v-if="!readOnly || form.user.length > 0" placeholder="请选择授权用户">
                  <el-option v-for="item in userList" :key="item.id" :label="item.realname" :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="oracleisinsBox" v-if="form.oracleisins === '1'">
        <DividerTitle title-name="oracle实例">
          <el-button type="primary" link icon="Plus" v-if="!readOnly" @click="oracleisinsAdd">新增oracle实例</el-button>
        </DividerTitle>
        <!-- <div class="top">
          <span>oracle实例</span>
          <div class="oracleInsBut">
            
            <el-button type="info" link icon="Minus" @click="oracleisinsDelete">删除</el-button>
          </div>
        </div> -->
        <el-table :data="form.oracleIns" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="100" align="center" />
          <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" placeholder="请输入实例名"></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" placeholder="请输入IP地址"></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" placeholder="请输入端口号"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="insport" label="操作" align="center" width="150">
            <template #default="scope">
              <el-button type="primary" link icon="delete" @click="oracleisinsDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <div class="buttonBox mt20">
      <el-button v-if="!readOnly" style="width: 80px;" @click="onCancel">取消</el-button>
      <el-button v-if="!readOnly" type="primary" style="width: 80px;" @click="onConfirm">确认</el-button>
      <el-button v-if="!readOnly" type="primary" style="width: 80px;background: #FF8D1A;border: 1px solid #FF8D1A;"
        @click="test">测试</el-button>
      <el-button v-if="readOnly" type="primary" style="width: 80px;" @click="readOnly = false">编辑</el-button>
      <el-button v-if="readOnly" type="primary" style="width: 80px;background: #FF8D1A;border: 1px solid #FF8D1A;"
        @click="onDelete">删除</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%;
  }
  .inputBox {
    margin-left: 1px;
    width: 100%;
    height: 100%;
  }
  .userEmpty {
    width: 100%;
    height: 100%;
    background: #f5fcff;
    display: flex;
    align-items: center;
    padding-left: 13px;
  }
}

.oracleisinsBox {
  margin-top: 24px;
  .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) {
    margin-bottom: 0 !important;
  }
  :deep(.el-form-item__error) {
    right: 6px !important;
    top: 30% !important;
  }
  :deep(.el-table__header .el-table__cell) {
    background-color: #ebf2ff !important;
  }
  :deep(.el-table__row--striped .el-table__cell) {
    background-color: #ebf2ff !important;
  }

  :deep(.el-form-item__error) {
    left: auto !important;
    right: 10px !important;
  }
}
</style>
