<template>
  <app-dialog v-model="visible" :loading="loading" :title="title" append-to-body class="app-dialog-content" width="70%" @cancel="onCancel" @confirm="onConfirm">
    <div ref="scroll-box" class="h-100 overflow-y pr-10 demo" style="scroll-behavior: smooth">
      <el-form ref="form" :inline="false" :model="form" :rules="rules" class="demo-form ml-150" label-width="100px">
        <el-divider content-position="left"
          ><i class="el-icon-document" style="color: rgb(24, 144, 255)" /><span class="divider-top">基础信息</span>
        </el-divider>
        <div class="form-content ml-120">
          <el-row :gutter="15">
            <app-filter-item :span="13" label="单位名称" prop="companyName">
              <el-input v-model="form.companyName" clearable placeholder="请输入" />
            </app-filter-item>
            <app-filter-item :span="13" label="单位类型" prop="companyType">
              <el-select v-model="form.companyType" clearable placeholder="请选择单位类型">
                <el-option v-for="dict in DICT.COMPANY_TYPE" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </app-filter-item>
            <app-filter-item :span="13" label="表前缀" prop="sysTableCode">
              <el-input v-model="form.sysTableCode" clearable placeholder="请输入" />
            </app-filter-item>
          </el-row>
          <el-row :gutter="15">
            <app-filter-item :span="13" label="联系人" prop="linkUser">
              <el-input v-model="form.linkUser" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="联系方式" prop="linkPhone">
              <el-input v-model="form.linkPhone" autocomplete="off" clearable placeholder="请输入" type="number" />
            </app-filter-item>
          </el-row>
          <el-row :gutter="15">
            <app-filter-item :span="13" label="系统编码" prop="sysCode">
              <el-input v-model="form.sysCode" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="系统名称" prop="sysName">
              <el-input v-model="form.sysName" clearable placeholder="请输入" />
            </app-filter-item>
          </el-row>
          <el-row :gutter="15">
            <app-filter-item :span="6" label="开通库表" prop="isDatabase">
              <el-switch v-model="form.isDatabase" active-text="是" active-value="1" inactive-text="否" inactive-value="0" is-api is-database is-mq />
            </app-filter-item>

            <!--            <app-filter-item :span="12" label="API接口" prop="isApi">-->
            <!--              <el-switch-->
            <!--                v-model="form.isApi"-->
            <!--                active-text="是"-->
            <!--                active-value="1"-->
            <!--                inactive-text="否"-->
            <!--                inactive-value="0"-->
            <!--                @change="v => onSwitch(v, { label: 'API接口信息', key: 'isApi' })"-->
            <!--              />-->
            <!--            </app-filter-item>-->

            <app-filter-item :span="6" label="离线文件" prop="isFile">
              <el-switch v-model="form.isFile" active-text="是" active-value="1" inactive-text="否" inactive-value="0" />
            </app-filter-item>

            <!--            <app-filter-item :span="12" label="中间件" prop="isMq">-->
            <!--              <el-switch v-model="form.isMq" active-text="是" active-value="1" inactive-text="否"-->
            <!--                         inactive-value="0"-->
            <!--              />-->
            <!--            </app-filter-item>-->
          </el-row>
        </div>
        <el-divider v-if="form.isDatabase === '1'" content-position="left"
          ><i class="el-icon-document" style="color: rgb(24, 144, 255)" /><span class="divider-top">数据库信息</span>
        </el-divider>
        <div v-if="form.isDatabase === '1'" class="form-content ml-120">
          <el-row :gutter="20">
            <app-filter-item :span="13" label="数据源">
              <el-select v-model="form.dataSource" clearable placeholder="请选择数据源" @change="setDatabase">
                <el-option v-for="item in dataSourceList" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left">{{ item.name }} </span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dbType }}</span>
                </el-option>
              </el-select>
            </app-filter-item>

            <app-filter-item :span="10" class="text-color-light" label-width="200px">
              <template #label>
                <span class="text-color-light">注意: (请先选择数据源)</span>
              </template>
            </app-filter-item>
          </el-row>
          <el-row :gutter="20">
            <app-filter-item
              :rules="[{ required: form.isDatabase === '1', message: '不能为空（请先选择数据源）' }]"
              :span="13"
              label="数据库别名"
              prop="databaseAlias"
            >
              <el-input v-model="form.databaseAlias" disabled />
            </app-filter-item>

            <app-filter-item
              :rules="[{ required: form.isDatabase === '1', message: '不能为空（请先选择数据源）' }]"
              :span="13"
              label="数据库类型"
              prop="databaseType"
            >
              <el-input v-model="form.databaseType" disabled />
            </app-filter-item>

            <app-filter-item
              :rules="[{ required: form.isDatabase === '1', message: '不能为空（请先选择数据源）' }]"
              :span="24"
              label=" 连接地址"
              prop="databaseUrl"
            >
              <el-input v-model="form.databaseUrl" disabled type="textarea" />
            </app-filter-item>
            <app-filter-item
              :rules="[
                { required: form.isDatabase === '1', message: '用户名不能为空' },
                { pattern: /^[a-zA-Z]+$/, message: '只能输入英文', trigger: 'blur' },
              ]"
              :span="13"
              label="用户名"
              prop="databaseUser"
            >
              <el-input v-model="form.databaseUser" :disabled="!!form.id" clearable placeholder="请输入">
                <template #append>
                  <el-button size="mini" type="primary" @click="checkAccount">验证</el-button>
                </template>
              </el-input>
            </app-filter-item>

            <app-filter-item
              :rules="[
                { required: form.isDatabase === '1', message: '密码不能为空' },
                {
                  pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
                  message: '长度至少8个字符，至少包含大小写字母、数字和特殊字符',
                  trigger: 'blur',
                },
              ]"
              :span="13"
              label="密码"
              prop="databasePwd"
            >
              <el-input v-model="form.databasePwd" clearable placeholder="请输入" show-password />
            </app-filter-item>

            <!--            <app-filter-item :span="24" label=" 数据提供描述" prop="description">-->
            <!--              <el-input v-model="form.description" type="textarea" />-->
            <!--            </app-filter-item>-->
          </el-row>
        </div>
      </el-form>
    </div>
  </app-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js';
import DICT from '@/utils/dict';
import sourceApi from '@/api/business/changeDataSource'; // import companyApi from '@/api/business/dataCollectCompany';
import companyApi from '@/api/business/dataCollectCompany';
import dictUtils from '@/components/dict/DictSelectUtils.js';

export default {
  name: 'CompanyDialog',
  mixins: [dialogMixin],
  props: {
    selectedRows: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      DICT,
      form: {
        databaseName: 'interchange_library',
        isDatabase: '1',
        companyType: 1,
      },
      rules: {
        companyName: [{ required: true, message: '单位名称不能为空' }],
        companyType: [{ required: true, message: '单位类型不能为空' }],
        // linkUser: [{ required: true, message: '联系人不能为空' }],
        // linkPhone: [{ required: true, message: '联系方式不能为空' }],
        // sysName: [{ required: true, message: '系统名称不能为空' }],
        // sysCode: [{ required: true, message: '系统编码不能为空' }],
        sysTableCode: [
          { required: true, message: '表前缀不能为空' },
          {
            pattern: /^[A-Za-z]{1,3}$/,
            message: '只能输入英文，并且不能超过三个字段',
            trigger: 'blur',
          },
        ],
      },
      loading: false,
      dynamicArea: [],
      dataSourceList: [],
      sysDict: {
        yjdj: dictUtils.getDictItemsFromCache('yjdj'),
      },
    };
  },
  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      this.getDataSource();
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };
      this.dynamicArea = [];
      data?.id && this.getDetail();

      this.$nextTick(() => {
        // if (this.form.isDatabase === '1') {
        //   this.onSwitch('1', { label: '数据库信息', key: 'isDatabase' });
        // }
        // if (this.form.isApi === '1') {
        //   this.onSwitch('1', { label: 'API接口信息', key: 'isApi' });
        // }
        this.$refs.form.clearValidate();
      });
    },
    async getDetail() {
      try {
        this.loading = true;
        const data = await companyApi.getCompanyDetail(this.data.id);
        this.form = { ...data };
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    async checkAccount() {
      const { databaseAlias, databaseUser } = this.form;
      if (!databaseUser || !databaseAlias) {
        this.$message.error('请选择数据源，并填写用户名');
        return;
      }
      try {
        this.loading = true;
        await companyApi.checkAccount({ dbAlias: databaseAlias, user: databaseUser });
        this.$message.success('验证通过，改用户名可以使用');
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    async getDataSource() {
      const data = await sourceApi.getList(1);
      this.dataSourceList = data || [];
    },
    // onSwitch(v, config) {
    //   const { key } = config;
    //   const index = this.dynamicArea.findIndex(item => item.key === key);
    //   if (v === '1') {
    //     if (index > -1) {
    //       this.dynamicArea.splice(index, 1, { ...config, value: v });
    //     } else {
    //       this.dynamicArea.push({ ...config, value: v });
    //     }
    //   } else {
    //     this.dynamicArea.splice(index, 1);
    //   }
    //
    //   this.$nextTick(() => {
    //     this.$refs['scroll-box'].scrollTop = this.$refs['scroll-box'].scrollHeight;
    //   });
    // },
    setDatabase(v) {
      const item = this.dataSourceList.find(item => item.id === v);
      const { alias: databaseAlias, dbType: databaseType, settingJson } = item;
      const settingJson_ = JSON.parse(settingJson.replace(/[\\]/g, ''));

      settingJson_.forEach(item => {
        const { name, value } = item;
        name === 'url' && (this.form['databaseUrl'] = value);
      });

      this.form = {
        ...this.form,
        databaseAlias,
        databaseType,
      };
    },
    onCancel() {
      this.visible = false;
    },
    async onConfirm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.loading = true;
            await companyApi.addCompany(this.form);
            this.$message.success('操作成功');
            this.onCancel();
            this.$emit('confirm', { ...this.form });
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form-item {
    margin-bottom: 18px !important;
  }

  .el-input__suffix {
    right: 0;
  }
}

.demo-form {
  border: solid 1px #eff0f5;
}

.demo {
  //border: solid 0.5px #eff0f5;
  //width: 100%;
  //margin: 0 auto;
}

//.app-dialog-content {
//  border: solid 1px gold;
//}
</style>
