<template>
  <div class="page-view overflow-h">
    <el-form ref="form" :disabled="dataSourceDisabled" :model="sourceProp" class="flex-1 overflow-y source-form" label-width="130px">
      <el-card>
        <app-title-bar class="mb-15">
          <span class="fs-17">基础信息</span>
        </app-title-bar>
        <div class="pl-30">
          <el-form-item
            :rules="[
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur',
              },
            ]"
            label="名称"
            prop="name"
          >
            <el-input v-model="sourceProp.name" :maxlength="50" autocomplete="off" clearable placeholder="请输入" show-word-limit @change="getPinyin" />
          </el-form-item>

          <el-form-item
            :rules="[
              {
                required: true,
                pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
                message: '只能输入字母、数字、下划线，且以字母开头',
              },
            ]"
            label="别名(唯一)"
            prop="alias"
          >
            <el-input v-model="sourceProp.alias" :maxlength="50" clearable placeholder="请输入" show-word-limit />
          </el-form-item>

          <ht-form-item label="是否生效">
            <el-switch v-model="sourceProp.enabled" active-text="是" inactive-text="否" />
          </ht-form-item>

          <el-form-item :rules="[{ required: true, message: '请选择数据库类型', trigger: 'change' }]" label="数据库类型" prop="dbType">
            <el-radio-group v-model="sourceProp.dbType" @change="currentSel">
              <el-radio-button v-for="radio in dbTypeList" :key="radio.value" :label="radio.value">{{ radio.value }}</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item :rules="[{ required: true, message: '请选择数据库类型', trigger: 'change' }]" label="数据源类型" prop="datasourcesType">
            <el-radio-group v-model="sourceProp.datasourcesType">
              <el-radio-button v-for="radio in dataSourcesList" :key="radio.value" :label="radio.value">{{ radio.label }}</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item :rules="[{ required: true, message: '请选择数据源', trigger: 'change' }]" label="数据源">
            <el-radio-group v-model="dsId" @change="settingSel">
              <el-radio-button v-for="radio in sysDataSource" :key="radio.id" :label="radio.id">{{ radio.name }}</el-radio-button>
            </el-radio-group>
            <!--
              <ht-select
                v-model="dsId"
                :options="sysDataSource"
                :props="{key: 'id', value: 'name'}"
                :validate="{required: true}"
                @change="settingSel"
              /> -->
          </el-form-item>
        </div>
      </el-card>

      <el-card v-if="sourceProp.settingJson.length" class="mt-11">
        <app-title-bar class="mb-15">
          <span class="fs-17">连接池信息</span>
          <el-tooltip class="ml-5" content="请先选择 ‘数据源’" effect="dark" placement="top-start">
            <i class="el-icon-question fs-16" />
          </el-tooltip>
        </app-title-bar>
        <div class="pl-30">
          <el-row :gutter="15" class="">
            <template v-for="(item, index) in sourceProp.settingJson">
              <el-col :key="`col_${index}`" :span="24">
                <ht-form-item :label="item.comment" class="">
                  <ht-input
                    v-model="item.value"
                    :disabled="['password', 'connectionProperties'].includes(item.name) && isEncrypt === 1"
                    :placeholder="'请输入' + item.comment"
                    :validate="{ required: true }"
                  />
                  ({{ item.type }})
                  <!-- <div v-if="item.name == 'password'"> -->
                  <el-switch
                    v-if="item.name == 'password'"
                    v-model="isEncrypt"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                    active-text="加密"
                    class="ml-15"
                    inactive-color="#ff4949"
                    inactive-text="不加密"
                    @change="encrypt(item)"
                  />
                  <!-- </div> -->
                </ht-form-item>
              </el-col>
            </template>
          </el-row>
        </div>
      </el-card>
    </el-form>
    <div class="mt-10">
      <el-button :disabled="!sourceProp.settingJson.length" size="mini" type="primary" @click="checkConnection">测试连接</el-button>
      <!-- :disabled="!sourceProp.settingJson.length" -->
      <el-button v-show="!dataSourceDisabled" size="mini" type="primary" @click="checkConnection">保存</el-button>

      <!-- <ht-submit-button
              v-show="!dataSourceDisabled"
              :url="savedataSourceUrl()"
              :model="newSourceProp"
              :is-submit="isSubmit"
              request-method="POST"
              size="mini"
              scope-name="editdataSourceForm"
              @before-save-data="beforeSaveData"
              @after-save-data="afterSaveData"
              >保存
            </ht-submit-button> -->
    </div>
  </div>
</template>

<script>
export default {
  props: {
    sysDataSource: {
      type: Array,
      default: () => [],
    },
    dbTypeList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      sourceProp: {
        settingJson: [],
        enabled: true,
        dbType: 'Mysql',
        datasourcesType: 1,
      },
      isEncrypt: 0,
      dataSourcesList: [
        { label: '汇聚源', value: 1 },
        { label: '共享源', value: 4 },
      ],
      enableds: [
        { key: true, value: '是 ' },
        { key: false, value: '否' },
      ],
      dsId: '',
      rowMapArr: [],
      newSourceProp: {},
      isSubmit: false,
      dataSourceDisabled: false,
    };
  },
  watch: {
    dsId: function (newVal, oldVal) {
      if (!newVal) {
        this.sourceProp.settingJson = [];
      }
    },
    'sourceProp.settingJson': {
      deep: true,
      handler(arr) {
        this.handleRows();
      },
    },
  },
  mounted() {
    // const dict = utils.getDictItemsFromCache('fzsjfwtyzd')
  },
  methods: {
    getPinyin() {
      this.$http
        .request({
          url: `${window.context.uc}/base/tools/v1/getPinyin`,
          method: 'GET',
          params: { chinese: this.sourceProp.name, type: 0 },
        })
        .then((res) => {
          if (res.data.state) {
            this.$set(this.sourceProp, 'alias', res.data.value);
            console.log(this.sourceProp.alias);
          }
        });
    },
    handleRows() {
      this.rowMapArr = [];
      const rowMap = Math.ceil(this.sourceProp.settingJson.length / 3);
      let num = 0;
      for (let i = 0; i < rowMap; i++) {
        const arr = [];
        for (let k = 0; k < 3; k++) {
          arr.push(num);
          num++;
        }
        this.rowMapArr.push(arr);
      }
    },
    encrypt(item) {
      if (this.isEncrypt === 1) {
        if (!item.value) {
          this.$message.warning('请输入密码!');
          this.isEncrypt = 0;
          return;
        }
        this.$http
          .post(`${window.context.portal}/base/tools/v1/encryptDbPassword`, {
            password: item.value,
          })
          .then((res) => {
            if (this.dsId != '1') {
              this.$message.error('不支持密码加密');
              return;
            }
            if (!res.data.state) {
              this.$message.error('加密失败');
              return;
            }
            item.value = res.data.value.password;
            const publicKey = {
              name: 'connectionProperties',
              comment: '公钥',
              type: 'java.lang.String',
              baseAttr: '1',
              default: '',
              value: `config.decrypt=true;config.decrypt.key=${res.data.value.publicKey}`,
            };
            this.sourceProp.settingJson.splice(
              this.sourceProp.settingJson.findIndex((item) => item.name === 'connectionProperties'),
              1,
            );
            this.sourceProp.settingJson.splice(this.sourceProp.settingJson.findIndex((item) => item.name === 'password') + 1, 0, publicKey);
          });
      } else {
        item.value = '';
        const index = this.sourceProp.settingJson.findIndex((item) => item.name === 'connectionProperties');
        if (index > 0) {
          this.sourceProp.settingJson.splice(index, 1);
        }
      }
    },
    currentSel(val) {
      console.log(val, this.sourceProp);
      for (var i in this.dbTypeList) {
        var d = this.dbTypeList[i];
        if (d.value != val) continue;
        for (var i = 0; i < this.sourceProp.settingJson.length; i++) {
          var attr = this.sourceProp.settingJson[i];
          if (attr.name.toLowerCase().indexOf('url') != -1) {
            attr.value = d.url;
          } else if (attr.name.toLowerCase().indexOf('driver') != -1) {
            attr.value = d.driverName;
          } else if (attr.name.toLowerCase().indexOf('validationquery') != -1) {
            attr.value = d.validationquery;
          }
        }
      }
    },
    settingSel(dsId) {
      const data = this.sysDataSource.find((o) => o.id == dsId);
      if (data && data.settingJson) {
        this.sourceProp.settingJson = JSON.parse(data.settingJson.replace(/[\\]/g, ''));
        // 改变了数据池id，那么需要输入的属性也变了
        for (var i = 0; i < this.sysDataSource.length; i++) {
          var def = this.sysDataSource[i];
          if (def.id != dsId) continue;
          var settingJson = JSON.parse(def.settingJson.replace(/[\\]/g, ''));
          this.sourceProp.classPath = def.classPath;
          this.sourceProp.initMethod = def.initMethod;
          this.sourceProp.closeMethod = def.closeMethod;
          // 处理配置的初始化值
          this.sourceProp.settingJson = [];
          settingJson.forEach((obj) => {
            obj.value = obj['default'];
            this.sourceProp.settingJson.push(obj);
          });
        }

        // 选择了数据源类型 就替换数据源中的连接地址和驱动
        for (var i in this.dbTypeList) {
          var d = this.dbTypeList[i];
          if (d.value != this.sourceProp.dbType) continue;
          for (var i = 0; i < this.sourceProp.settingJson.length; i++) {
            var attr = this.sourceProp.settingJson[i];
            if (attr.name.toLowerCase().indexOf('url') != -1) {
              attr.value = d.url;
            } else if (attr.name.toLowerCase().indexOf('driver') != -1) {
              attr.value = d.driverName;
            } else if (attr.name.toLowerCase().indexOf('validationquery') != -1) {
              attr.value = d.validationquery;
            }
          }
        }
        // 数据源配置别名跟这里的别名一致
        for (var i = 0; i < this.sourceProp.settingJson.length; i++) {
          var attr = this.sourceProp.settingJson[i];
          if (attr.name.toLowerCase().indexOf('alias') != -1) {
            attr.value = attr.alias;
          }
        }
      }
    },
    checkConnection() {
      this.$refs.form.validate((valid) => {
        console.log(valid, this.sourceProp);
      });
      // if (this.sourceProp.settingJson.length == 0) {
      //   this.$message.error('请选择 “数据源” 并配置数据源信息')
      //   return
      // }
      // var newSourceProp = {}
      // Object.assign(newSourceProp, this.sourceProp)
      // newSourceProp.settingJson = JSON.stringify(newSourceProp.settingJson)
      // sys.checkConnection(newSourceProp).then(
      //   (data) => {
      //     if (data.state) {
      //       this.$message.success(data.message)
      //     }
      //   },
      //   (error) => {
      //     this.$message.error(error || '连接失败')
      //   }
      // )
    },

    savedataSourceUrl: function () {
      return `${window.context.portal}/sys/sysDataSource/v1/save`; // window.context.portal +
    },
    beforeSaveData() {
      this.newSourceProp = {};
      // 克隆一个新对象以免影响页面数据动态绑定上了
      Object.assign(this.newSourceProp, this.sourceProp);
      this.newSourceProp.settingJson = JSON.stringify(this.newSourceProp.settingJson);
    },
    afterSaveData() {},
  },
};
</script>

<style lang="scss" scoped>
.title {
  position: relative;
}
.line-split {
  height: 80%;
  width: 1px;
  background: #eee;
}

.source-form {
  ::v-deep {
    .el-input {
      max-width: 300px;
    }
  }
}
::v-deep {
  .el-form-item__label {
    width: 130px !important;
    overflow: hidden;
    word-break: break-all;
    display: flex;
    align-items: center;
    min-height: 32px;
    text-align: left;
    line-height: normal;
  }

  .el-timeline-item__wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    .el-timeline-item__content {
      flex: 1;
    }
  }

  .el-timeline-item__timestamp {
    font-size: 15px;
    font-weight: bold;
    padding-top: 2px !important;
  }

  .el-card__body {
    height: 100%;
    box-sizing: border-box;
    padding: 15px;
  }
}

.el-timeline {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}
</style>
