<template>
  <div class="guns-layout">
    <div class="guns-layout-content">
      <div class="guns-layout">
        <div
          class="guns-layout-content-header"
          style="height: auto; padding-top: 8px; font-weight: normal; padding-bottom: 16px"
          :class="{ 'border-bottom': editType == 'detail' }"
        >
          <span class="back-btn" @click="back">
            <left-outlined class="back-btn-icon" />
            返回
          </span>
          <div style="width: 887px; margin-top: 12px; margin-left: -40px">
            <a-steps :current="current" v-if="editType == 'add'">
              <a-step title="基本信息"></a-step>
              <a-step title="功能选择" />
              <a-step title="数据源" />
              <a-step title="完成" />
            </a-steps>
            <span v-else class="tenantName">
              {{ tenantData?.tenantName }}
            </span>
          </div>
          <a-space :size="16">
            <span v-if="editType == 'add'"></span>
            <a-button type="primary" class="border-radius" v-if="editType == 'edit'" @click="save">保存</a-button>
            <a-button class="border-radius" v-if="editType == 'edit'" @click="back">取消</a-button>
            <a-button type="primary" class="border-radius" v-if="editType == 'detail'" @click="editClick">编辑</a-button>
          </a-space>
        </div>
        <div class="guns-layout-content-application" style="overflow-y: auto">
          <div class="tenant-add" v-if="editType != 'detail'">
            <a-spin :spinning="loading" :delay="100">
              <a-form ref="formRef" :model="tenantData" :rules="rules" :labelCol="{ style: { width: '142px' } }">
                <template v-if="current == 0 || editType == 'edit'">
                  <div class="base-info">基本信息</div>
                  <a-form-item label="租户logo:" name="tenantLogo">
                    <a-upload
                      name="file"
                      :multiple="false"
                      v-model:file-list="iconList"
                      :default-file-list="iconList"
                      :maxCount="1"
                      :action="icon.fileUploadUrl"
                      list-type="picture-card"
                      :headers="icon.headers"
                      :before-upload="beforeUpload"
                      accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
                      @preview="handlePreviewPhoto"
                      @download="downloadPhoto"
                      @change="handleFileChange"
                      @remove="handleRemove"
                      :showUploadList="{
                        showDownloadIcon: true
                      }"
                    >
                      <div v-if="iconList.length == 0">
                        <plus-outlined style="font-size: 20px; color: #adb5b8" />
                        <div style="color: #adb5b8; font-size: 16px">上传logo</div>
                      </div>
                    </a-upload>
                  </a-form-item>
                  <a-form-item label="租户名称:" name="tenantName">
                    <a-input
                      v-model:value="tenantData.tenantName"
                      allow-clear
                      placeholder="请输入租户名称"
                      @change="tenantNameChange"
                      class="input-width"
                    />
                  </a-form-item>
                  <a-form-item label="租户编码:" name="tenantCode" v-if="editType == 'add'">
                    <a-space>
                      <a-input v-model:value="tenantData.tenantCode" allow-clear placeholder="请输入租户编码" class="input-width" />
                      <span class="tool">自动生成，可手动修改</span>
                    </a-space>
                  </a-form-item>
                  <a-form-item label="管理员邮箱:" name="email" v-if="editType == 'add'">
                    <a-space>
                      <a-input
                        v-model:value="tenantData.email"
                        autocomplete="new-password"
                        allow-clear
                        placeholder="请输入管理员邮箱"
                        class="input-width"
                      />
                      <span class="tool">此邮箱将作为租户超级管理员的账号</span>
                    </a-space>
                  </a-form-item>
                  <a-form-item label="管理员手机号:" name="safePhone">
                    <a-input v-model:value="tenantData.safePhone" allow-clear placeholder="请输入管理员手机号" class="input-width" />
                  </a-form-item>
                  <a-form-item label="密码:" name="password" v-if="editType == 'add'">
                    <a-input-password
                      v-model:value="tenantData.password"
                      autocomplete="new-password"
                      allow-clear
                      placeholder="请输入密码"
                      class="input-width"
                    />
                  </a-form-item>
                  <div class="base-info">公司信息</div>
                  <a-form-item label="公司名称:" name="companyName">
                    <a-input v-model:value="tenantData.companyName" allow-clear placeholder="请输入公司名称" class="input-width" />
                  </a-form-item>
                  <a-form-item label="公司地址:" name="companyAddress">
                    <a-input v-model:value="tenantData.companyAddress" allow-clear placeholder="请输入公司地址" class="input-width" />
                  </a-form-item>
                  <a-form-item label="统一社会信用代码:" name="companySocialCode">
                    <a-input
                      v-model:value="tenantData.companySocialCode"
                      allow-clear
                      placeholder="请输入统一社会信用代码"
                      class="input-width"
                    />
                  </a-form-item>
                </template>
                <template v-if="current == 1 || editType == 'edit'">
                  <div class="base-info">功能选择</div>
                  <a-form-item label="生效时间:" name="activeDate">
                    <a-date-picker
                      v-model:value="tenantData.activeDate"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="请输入生效时间"
                      class="input-width"
                    />
                  </a-form-item>
                  <a-form-item label="到期时间:" name="expireDate">
                    <a-space>
                      <a-date-picker
                        v-model:value="tenantData.expireDate"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请输入到期时间"
                        class="input-width"
                        :disabled="tenantData.permanentFlag == 'Y' ? true : false"
                      />
                      <vxe-checkbox
                        v-model="tenantData.permanentFlag"
                        @change="permanentFlagChange(true)"
                        checked-value="Y"
                        unchecked-value="N"
                      >
                        无期限
                      </vxe-checkbox>
                    </a-space>
                  </a-form-item>
                  <a-form-item label="租户状态:" name="statusFlag">
                    <a-radio-group v-model:value="tenantData.statusFlag">
                      <a-radio :value="1">启用</a-radio>
                      <a-radio :value="2">禁用</a-radio>
                      <a-radio :value="3" v-if="editType == 'edit'">准备删除</a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <div class="add-gn"><a-button type="primary" class="border-radius" @click="addPack">添加功能</a-button></div>
                  <a-form-item-rest>
                    <a-table
                      :dataSource="tenantData.tenantLinkList"
                      class="table"
                      :columns="columns"
                      :pagination="false"
                      bordered
                      size="small"
                    >
                      <template #bodyCell="{ column, record, index }">
                        <template v-if="column.dataIndex === 'index'">
                          {{ index + 1 }}
                        </template>
                        <template v-if="column.dataIndex === 'packageId'">
                          <a-select
                            v-model:value="record.packageId"
                            :bordered="false"
                            allowClear
                            size="small"
                            style="width: 100%"
                            placeholder="请选择功能包"
                          >
                            <a-select-option :value="item.packageId" v-for="item in useList" :key="item.packageId">{{
                              item.packageName
                            }}</a-select-option>
                          </a-select>
                        </template>
                        <template v-if="column.dataIndex === 'action'">
                          <icon-font
                            iconClass="icon-opt-shanchu"
                            font-size="24px"
                            title="删除"
                            color="#60666b"
                            @click="removePack(index)"
                          ></icon-font>
                        </template>
                      </template>
                    </a-table>
                  </a-form-item-rest>
                </template>
                <template v-if="current == 2">
                  <div class="base-info">数据源</div>
                  <a-form-item label="数据源类型:" name="dataMode" class="center-form">
                    <a-radio-group v-model:value="tenantData.dataMode" @change="dataModeChange">
                      <a-row :gutter="8">
                        <a-col :span="12">
                          <a-radio :value="1">
                            <div class="mode-t">租户ID隔离</div>
                            <div class="mode-d">
                              数据存储在同一个数据库中，通过租户ID对数据进行逻辑隔离，实现租户数据的独立访问与管便于数据管理和查询优化。
                            </div>
                          </a-radio>
                        </a-col>
                        <a-col :span="12">
                          <a-radio :value="2">
                            <div class="mode-t">数据库租户分离</div>
                            <div class="mode-d">
                              将租户数据分配到不同的数据库中，实现租户数据的物理隔离，满足多租户环境下的数据独立性需求。
                            </div>
                          </a-radio>
                        </a-col>
                      </a-row>
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item label="数据源选择:" name="dataSourceType" v-if="tenantData?.dataMode == 2">
                    <a-radio-group v-model:value="tenantData.dataSourceType" @change="dataSourceTypeChange">
                      <a-radio :value="1">当前数据源</a-radio>
                      <a-radio :value="2">其他数据源</a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <template v-if="tenantData?.dataSourceType == 2">
                    <a-form-item label="数据源类型:" name="jdbcClass">
                      <div class="data-list">
                        <div
                          :class="['data-item', { 'data-item-active': tenantData?.jdbcClass == item.key }]"
                          @click="databaseClick(item)"
                          v-for="item in databaseList"
                          :key="item.key"
                        >
                          <img src="@/assets/database/mysql.svg" alt="" v-if="item.name == 'mysql'" />
                          <img src="@/assets/database/postgresql.svg" alt="" v-if="item.name == 'PostgreSql'" />
                          <img src="@/assets/database/sqlserver.svg" alt="" v-if="item.name == 'SqlServer'" />
                          <img src="@/assets/database/oracle.svg" alt="" v-if="item.name == 'Oracle'" />
                          <img src="@/assets/database/dameng.svg" alt="" v-if="item.name == '达梦'" />
                          <img src="@/assets/database/hangao.svg" alt="" v-if="item.name == '瀚高'" />
                          <div class="data-item-title">{{ item.name }}</div>
                          <img src="@/assets/database/right.svg" alt="" v-if="tenantData?.jdbcClass == item.key" class="right-img" />
                        </div>
                      </div>
                    </a-form-item>
                    <a-form-item label="JDBC账号:" name="jdbcAccount">
                      <a-input v-model:value="tenantData.jdbcAccount" placeholder="请输入JDBC账号" allow-clear autocomplete="off" />
                    </a-form-item>
                    <a-form-item label="JDBC密码:" name="jdbcPassword">
                      <a-input v-model:value="tenantData.jdbcPassword" placeholder="请输入JDBC密码" allow-clear autocomplete="off" />
                    </a-form-item>
                    <a-form-item label="JDBC URL:" name="jdbcUrl">
                      <a-textarea :rows="4" v-model:value="tenantData.jdbcUrl" placeholder="请输入URL" allow-clear autocomplete="off" />
                    </a-form-item>
                  </template>
                </template>
                <template v-if="current == 3">
                  <div class="finish">
                    <img src="@/assets/images/loading.svg" alt="" />
                    <div class="finish-s">状态：租户正在初始化，请耐心等待...</div>
                    <div class="finish-d">如果您使用“数据库租户分离”方式，初始化过程可能需要几分钟时间，具体取决于数据量和网络状况。</div>
                    <a-button type="primary" ghost class="border-radius" @click="back">查看状态</a-button>
                  </div>
                </template>
                <div class="next-step" :style="{ width: current == 2 ? '100%' : 'calc(142px + 420px)' }" v-if="editType == 'add'">
                  <a-space>
                    <a-button class="border-radius grey" type="link" v-if="[1, 2].includes(current)" @click="preClick">上一步</a-button>
                    <a-button type="primary" class="border-radius" @click="nextClick" v-if="current != 3">{{
                      current == 2 ? '完成' : '下一步'
                    }}</a-button>
                  </a-space>
                </div>
              </a-form>
            </a-spin>
          </div>
          <a-form ref="formRef" :model="tenantData" class="detail-form" v-else :labelCol="{ style: { width: '142px' } }">
            <a-row style="width: 100%; height: 100%">
              <a-col :span="12" style="border-right: 1.5px solid #c5cfd166; padding: 0 32px 0 10px">
                <div class="base-info">基本信息</div>
                <a-form-item label="租户logo:" name="tenantLogo">
                  <a-upload
                    name="file"
                    :multiple="false"
                    v-model:file-list="iconList"
                    :default-file-list="iconList"
                    :maxCount="1"
                    :action="icon.fileUploadUrl"
                    list-type="picture-card"
                    :headers="icon.headers"
                    :before-upload="beforeUpload"
                    accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
                    @preview="handlePreviewPhoto"
                    @download="downloadPhoto"
                    @change="handleFileChange"
                    @remove="handleRemove"
                    disabled
                    :showUploadList="{
                      showDownloadIcon: true
                    }"
                  >
                    <div v-if="iconList.length == 0">
                      <plus-outlined style="font-size: 20px; color: #adb5b8" />
                      <div style="color: #adb5b8; font-size: 16px">上传logo</div>
                    </div>
                  </a-upload>
                </a-form-item>
                <a-form-item label="租户名称:">
                  {{ tenantData?.tenantName }}
                </a-form-item>
                <a-form-item label="租户编码:">
                  {{ tenantData?.tenantCode }}
                </a-form-item>
                <a-form-item label="管理员邮箱:">
                  {{ tenantData?.email }}
                </a-form-item>
                <a-form-item label="管理员手机号:">
                  {{ tenantData?.safePhone }}
                </a-form-item>
                <div class="base-info">公司信息</div>
                <a-form-item label="公司名称:">
                  {{ tenantData?.companyName || '暂无' }}
                </a-form-item>
                <a-form-item label="公司地址:">
                  {{ tenantData?.companyAddress || '暂无' }}
                </a-form-item>
                <a-form-item label="统一社会信用代码:">
                  {{ tenantData?.companySocialCode || '暂无' }}
                </a-form-item>
                <div class="base-info">其他信息</div>
                <a-form-item label="租户用户数:">
                  {{ tenantData?.tenantUserCount || 0 }}
                </a-form-item>
                <a-form-item label="租户下公司数量:">
                  {{ tenantData?.tenantOrgCount || 0 }}
                </a-form-item>
                <a-form-item label="创建时间:">
                  {{ tenantData?.createTime }}
                </a-form-item>
                <a-form-item label="上次更新时间:">
                  {{ tenantData?.updateTime || tenantData?.createTime }}
                </a-form-item>
              </a-col>
              <a-col :span="12" style="padding: 0 10px 0 32px">
                <div class="base-info">数据源</div>
                <a-form-item label="数据源类型:">
                  <span v-if="tenantData?.dataMode == 1">租户ID隔离</span>
                  <span v-if="tenantData?.dataMode == 2">数据库租户分离</span>
                </a-form-item>
                <a-form-item label="数据源类型:"> mysql </a-form-item>
                <a-form-item label="JDBC账号:">
                  {{ tenantData?.jdbcAccount }}
                </a-form-item>
                <a-form-item label="JDBC密码:">
                  <a-space align="center">
                    {{ !showPwd ? '******' : tenantData?.jdbcPassword }}
                    <eye-invisible-outlined v-if="showPwd" @click="showPwd = !showPwd" />
                    <eye-outlined v-else @click="showPwd = !showPwd" />
                  </a-space>
                </a-form-item>
                <a-form-item label="JDB URL:">
                  {{ tenantData?.jdbcUrl }}
                </a-form-item>
                <div class="base-info">功能选择</div>
                <a-form-item label="租户生效时间:">
                  {{ tenantData?.activeDate }}
                </a-form-item>
                <a-form-item label="租户到期时间:">
                  {{ tenantData?.expireDate }}
                </a-form-item>
                <a-form-item label="租户状态:">
                  <a-radio-group v-model:value="tenantData.statusFlag">
                    <a-radio :value="1" v-if="tenantData.statusFlag == 1">启用</a-radio>
                    <a-radio :value="2" v-if="tenantData.statusFlag == 2">禁用</a-radio>
                    <a-radio :value="3" v-if="tenantData.statusFlag == 3">准备删除</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="功能绑定:">
                  <a-table
                    :dataSource="tenantData.tenantLinkList"
                    :columns="columns?.filter(item => item.dataIndex != 'action')"
                    :pagination="false"
                    bordered
                    size="small"
                  >
                    <template #bodyCell="{ column, record, index }">
                      <template v-if="column.dataIndex === 'index'">
                        {{ index + 1 }}
                      </template>
                      <template v-if="column.dataIndex === 'packageId'">
                        <a-select
                          v-model:value="record.packageId"
                          :bordered="false"
                          allowClear
                          disabled
                          size="small"
                          :showArrow="false"
                          style="width: 100%"
                          placeholder="请选择功能包"
                        >
                          <a-select-option :value="item.packageId" v-for="item in useList" :key="item.packageId">{{
                            item.packageName
                          }}</a-select-option>
                        </a-select>
                      </template>
                      <template v-if="column.dataIndex === 'action'">
                        <icon-font
                          iconClass="icon-opt-shanchu"
                          font-size="24px"
                          title="删除"
                          color="#60666b"
                          @click="removePack(index)"
                        ></icon-font>
                      </template>
                    </template>
                  </a-table>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
    </div>

    <!-- 图标预览弹框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted, reactive } from 'vue';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';
import { message, Upload } from 'ant-design-vue/es';
import { TenantApi } from './api/TenantApi';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();

const editType = ref('add');

const tenantId = ref('');

const current = ref(0);

const formRef = ref(null);

const tenantData = ref({
  statusFlag: 1,
  tenantLinkList: [],
  dataMode: 1,
  permanentFlag: 'N',
  activeDate: dayjs().format('YYYY-MM-DD') + ' 00:00:00'
});

const rules = reactive({
  tenantLogo: [{ required: true, message: '请上传租户logo', type: 'string', trigger: 'blur' }],
  tenantName: [{ required: true, message: '请输入租户名称', type: 'string', trigger: 'blur' }],
  tenantCode: [{ required: true, message: '请输入租户编码', type: 'string', trigger: 'blur' }],
  email: [{ required: true, message: '请输入管理员邮箱', type: 'string', trigger: 'blur' }],
  safePhone: [{ required: true, message: '请输入管理员手机号', type: 'string', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', type: 'string', trigger: 'blur' }],
  activeDate: [{ required: true, message: '请输入生效时间', type: 'string', trigger: 'blur' }],
  expireDate: [{ required: true, message: '请输入到期时间', type: 'string', trigger: 'blur' }],
  statusFlag: [{ required: true, message: '请选择租户状态', type: 'number', trigger: 'blur' }],
  dataMode: [{ required: true, message: '请选择数据隔离方式', type: 'number', trigger: 'blur' }],
  dataSourceType: [{ required: true, message: '请选择数据源', type: 'number', trigger: 'blur' }],
  jdbcClass: [{ required: true, message: '请选择数据类型', type: 'string', trigger: 'blur' }],
  jdbcAccount: [{ required: true, message: '请输入JDBC账号', type: 'string', trigger: 'blur' }],
  jdbcPassword: [{ required: true, message: '请输入JDBC密码', type: 'string', trigger: 'blur' }],
  jdbcUrl: [{ required: true, message: '请输入JDBC URL', type: 'string', trigger: 'blur' }]
});

const columns = ref([
  {
    title: '序号',
    width: 60,
    dataIndex: 'index',
    align: 'center'
  },
  {
    title: '功能包',
    dataIndex: 'packageId'
  },
  {
    title: '操作',
    width: 60,
    dataIndex: 'action'
  }
]);

const iconList = ref([]);

// 是否展示图片预览
const previewVisible = ref(false);
// 图片地址
const previewImage = ref(null);

// 图标上传预览地址
const icon = reactive({
  // 上传文件的url
  fileUploadUrl: `${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`,
  filePreviewUrl: `${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`,
  // 上传文件时候要带header
  headers: {
    Authorization: getToken()
  }
});

const useList = ref([]);

const showPwd = ref(false);

// 数据库列表
const databaseList = ref([
  {
    key: 'com.mysql.cj.jdbc.Driver',
    name: 'mysql',
    title:
      'jdbc:mysql://127.0.0.1:3306/guns?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true'
  }
  //   {
  //     key: 'org.postgresql.Driver',
  //     name: 'PostgreSql',
  //     title: 'jdbc:postgresql://127.0.0.1:5432/guns'
  //   },
  //   {
  //     key: 'net.sourceforge.jtds.jdbc.Driver',
  //     name: 'SqlServer',
  //     title: 'jdbc:jtds:sqlserver://127.0.0.1:1433;DatabaseName=guns'
  //   },
  //   {
  //     key: 'oracle.jdbc.OracleDriver',
  //     name: 'Oracle',
  //     title: 'jdbc:oracle:thin:@127.0.0.1:1521:ORCLCDB'
  //   },
  //   {
  //     key: 'dm.jdbc.driver.DmDriver',
  //     name: '达梦',
  //     title:
  //       'jdbc:dm://127.0.0.1:5236?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8'
  //   },
  //   {
  //     key: 'com.highgo.jdbc.Driver',
  //     name: '瀚高',
  //     title: 'jdbc:highgo://127.0.0.1:5866/highgo'
  //   }
]);

const loading = ref(false);

onMounted(() => {
  const { type, id } = route.query;
  editType.value = type;
  tenantId.value = id;

  if (type != 'add' && !id) return back();

  generateTenantCode();
  getUseList();
  getDetail();
});

const back = () => {
  router.push('/tenant/manage');
};

// 生成一个租户编码
const generateTenantCode = async () => {
  if (editType.value == 'add') {
    tenantData.value.tenantCode = await TenantApi.generateTenantCode();
  }
};

// 获取功能包列表
const getUseList = () => {
  TenantApi.tenantPackageList().then(res => {
    useList.value = res.data;
  });
};

const getDetail = async () => {
  if (editType.value == 'add') return;
  const res = await TenantApi.detail({ tenantId: tenantId.value });
  tenantData.value = Object.assign({}, res);
  permanentFlagChange();
  if (res?.tenantLogo) {
    FileApi.getAntdVInfo({ fileId: res.tenantLogo }).then(res => {
      res.uid = res.tenantLogo;
      iconList.value = [res];
    });
  }
};

//上传之前的回调
const beforeUpload = file => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/tif' ||
    file.type === 'image/jfif' ||
    file.type === 'image/webp' ||
    file.type === 'image/pjp' ||
    file.type === 'image/apng' ||
    file.type === 'image/pjpeg' ||
    file.type === 'image/avif' ||
    file.type === 'image/ico' ||
    file.type === 'image/tiff' ||
    file.type === 'image/bmp' ||
    file.type === 'image/xbm' ||
    file.type === 'image/jxl' ||
    file.type === 'image/svgz' ||
    file.type === 'image/gif' ||
    file.type === 'image/svg';
  if (!isJpgOrPng) {
    message.error('只能上传图片!');
    return Upload.LIST_IGNORE; //阻止列表展现
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
  }
  return isJpgOrPng && isLt5M;
};

// 上传成功
const handleFileChange = info => {
  if (info.file.status === 'done') {
    tenantData.value.tenantLogo = info.file.response.data.fileId;
    message.success(`${info.file.name} 图片上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 图片上传失败`);
  }
};

// 点击预览图片
const handlePreviewPhoto = async file => {
  previewImage.value = file.url || file.preview || file.thumbUrl;
  previewVisible.value = true;
};

//下载图片
const downloadPhoto = file => {
  let id = file.response ? file.response.data.fileId : file.uid;
  FileApi.download({ token: getToken(), fileId: id });
};

const handleRemove = file => {
  tenantData.value.tenantLogo = null;
  return true;
};

// 租户名称改变
const tenantNameChange = () => {
  tenantData.value.companyName = tenantData.value.tenantName;
};

const preClick = () => {
  current.value--;
};

const nextClick = async () => {
  if (current.value != 3) {
    await formRef.value.validate();
  }
  if (current.value == 0) {
    const res = await TenantApi.checkTenantCode({ tenantCode: tenantData.value.tenantCode });
    if (res) {
      return message.warning('租户编码已存在，请重新输入！');
    }
  } else if (current.value == 1) {
    if (tenantData.value.tenantLinkList.length == 0) return message.warning('功能不能为空！');
    if (!tenantData.value.tenantLinkList.find(item => item.packageId)) return message.warning('功能包不能为空！');
  } else if (current.value == 2) {
    if (tenantData.value?.dataMode == 2 && tenantData.value?.dataSourceType == 2) {
      loading.value = true;
      const urlRes = await TenantApi.validateUrlStatus({
        jdbcAccount: tenantData.value.jdbcAccount,
        jdbcClass: tenantData.value.jdbcClass,
        jdbcPassword: tenantData.value.jdbcPassword,
        jdbcUrl: tenantData.value.jdbcUrl
      });
      loading.value = false;
      if (!urlRes.data) {
        return message.warning('数据库连接失败，请重新输入!');
      }
    }
    loading.value = true;
    const res = await TenantApi.add(tenantData.value);
    loading.value = false;
    if (res.code != '00000') {
      return message.error(res.message);
    } else {
      message.success(res.message);
    }
  }
  current.value++;
};

const dataModeChange = () => {
  if (!tenantData.value?.dataSourceType) {
    tenantData.value.dataSourceType = 1;
  }
};

const permanentFlagChange = flag => {
  rules.expireDate[0].required = tenantData.value.permanentFlag == 'Y' ? false : true;
  if (flag) tenantData.value.expireDate = null;
};

const addPack = () => {
  tenantData.value.tenantLinkList.push({
    packageId: null
  });
};

const removePack = index => {
  tenantData.value.tenantLinkList.splice(index, 1);
};

const databaseClick = item => {
  tenantData.value.jdbcClass = item.key;
  tenantData.value.jdbcUrl = item.title;
};

const dataSourceTypeChange = () => {
  tenantData.value.jdbcClass = tenantData.value.dataSourceType == 1 ? null : databaseList.value[0].key;
  tenantData.value.jdbcUrl = tenantData.value.dataSourceType == 1 ? null : databaseList.value[0].title;
};

const save = async () => {
  if (editType.value == 'edit') {
    await formRef.value.validate();
    if (tenantData.value.tenantLinkList.length == 0) return message.warning('功能不能为空！');
    if (!tenantData.value.tenantLinkList.find(item => item.packageId)) return message.warning('功能包不能为空！');
    TenantApi.edit(tenantData.value).then(res => {
      message.success(res.message);
      back();
    });
  }
};

const editClick = () => {
  editType.value = 'edit';
};
</script>

<style scoped lang="less">
.guns-layout-content {
  padding: 12px 16px;
}
.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
  cursor: pointer;

  .back-btn-icon {
    font-size: 16px;
    color: #828b9a;
  }
}

.border-bottom {
  border-bottom: 1.5px solid rgba(197, 207, 209, 0.4);
}
.tenant-add {
  width: 807px;
  margin: 0 auto;
  position: relative;
}
:deep(.ant-upload.ant-upload-select-picture-card) {
  background-color: #fff;
  border: 1.5px solid var(--border-color-base);
  border-radius: 4px;
}
.input-width {
  width: 420px;
}
.base-info {
  width: 142px;
  color: #0c45ac;
  font-size: 16px;
  font-style: normal;
  font-weight: 500;
  line-height: normal;
  position: relative;
  padding-left: 13px;
  margin-bottom: 16px;

  &::before {
    position: absolute;
    content: '';
    left: 0;
    top: 5px;
    width: 3px;
    height: 14px;
    background-color: #0f56d7;
  }
}

.tool {
  color: #adb5b8;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}

.next-step {
  width: calc(142px + 420px);
  text-align: right;
}
.grey {
  color: #898e91;
}
.add-gn {
  width: 142px;
  text-align: right;
  margin-bottom: 16px;

  :deep(.ant-btn) {
    padding: 8px !important;
    height: 30px !important;
    line-height: 10px !important;
  }
}
.table {
  width: 500px;
  margin-left: 62px;
  margin-bottom: 16px;

  :deep(.ant-table-container) {
    --border-color-split: #c5cfd166;
  }
}

.mode-t {
  color: #60666b;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}
.mode-d {
  color: #adb5b8;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}
.center-form {
  align-items: center;
  .ant-radio-wrapper {
    padding: 8px 12px;
    border-radius: 4px;
    border: 1px solid rgba(197, 207, 209, 0.6);
  }
}
.data-list {
  display: flex;
  gap: 16px;

  .data-item {
    display: flex;
    flex-direction: column;
    width: 82px;
    height: 82px;
    padding: 8px 12px;
    justify-content: center;
    align-items: center;
    gap: 4px;
    flex-shrink: 0;
    border-radius: 6px;
    border: 1.5px solid rgba(197, 207, 209, 0.6);
    cursor: pointer;
    position: relative;
    overflow: hidden;

    img {
      width: 36px;
      height: 36px;
    }

    .data-item-title {
      color: #60666b;
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }

    .right-img {
      width: 24px;
      height: 20px;
      position: absolute;
      top: -1px;
      right: -1px;
    }

    &:hover {
      border-color: #188efc;
    }
  }
  .data-item-active {
    border-color: #188efc;
  }
}

.finish {
  position: absolute;
  top: 20%;
  left: 0;
  width: 100%;
  margin-top: -54px;
  text-align: center;

  .finish-s {
    color: #60666b;
    text-align: center;
    font-size: 20px;
    font-style: normal;
    font-weight: 700;
    line-height: normal;
    margin-bottom: 8px;
    margin-top: 8px;
  }
  .finish-d {
    color: #898e91;
    text-align: center;
    font-size: 16px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    margin-bottom: 16px;
  }
}
.tenantName {
  color: #515b67;
  font-size: 18px;
  font-style: normal;
  font-weight: 700;
  line-height: normal;
}

.detail-form {
  width: 100%;

  :deep(.ant-form-item-label) {
    text-align: left;

    label {
      color: #60666b;
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }
  }

  :deep(.ant-form-item-control-input-content) {
    color: #60666b;
    font-size: 16px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    word-wrap: break-word;
    overflow-wrap: break-word;
  }

  :deep(.ant-form-item) {
    padding-left: 8px;
    margin-bottom: 16px;
  }

  :deep(.ant-select-selector) {
    padding: 0 !important;
    color: #60666b;
    font-size: 16px;
  }
  :deep(.ant-table-thead > tr > th) {
    color: #60666b;
    font-size: 16px;
    font-weight: normal;
  }
  :deep(.ant-table-cell) {
    color: #60666b;
    font-size: 16px;
  }
}
</style>
