<template>
  <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
    <a-row :gutter="20">
      <a-col :span="12">
        <a-form-item label="租户名称:" name="tenantName">
          <a-input v-model:value="form.tenantName" allow-clear placeholder="请输入租户名称" @change="tenantNameChange" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="租户编码:" name="tenantCode">
          <a-input v-model:value="form.tenantCode" allow-clear placeholder="请输入租户编码" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item name="email">
          <template #label>
            <span style="margin-right: 10px">邮箱:</span>
            <a-tooltip>
              <template #title>邮箱用在租户的超级管理员登录，作为账号</template>
              <question-circle-outlined />
            </a-tooltip>
          </template>
          <a-input v-model:value="form.email" allow-clear placeholder="请输入邮箱" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="电话:" name="safePhone">
          <a-input v-model:value="form.safePhone" allow-clear placeholder="请输入电话" />
        </a-form-item>
      </a-col>
      <a-col :span="12" v-if="!props.isUpdate">
        <a-form-item name="password">
          <template #label>
            <span style="margin-right: 10px">管理员密码:</span>
            <a-tooltip>
              <template #title>邮箱用在租户的超级管理员登录，作为密码</template>
              <question-circle-outlined />
            </a-tooltip>
          </template>
          <a-input-password v-model:value="form.password" allow-clear placeholder="请输入管理员密码" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="租户logo:" name="iconList">
          <a-upload
            name="file"
            :multiple="false"
            v-model:file-list="form.iconList"
            :default-file-list="form.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="info => handleFileChange(info, 'iconList')"
            :showUploadList="{
              showDownloadIcon: true
            }"
          >
            <plus-outlined style="font-size: 28px; font-weight: 200" v-if="form.iconList.length == 0" />
          </a-upload>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="租户生效时间:" name="activeDate">
          <a-date-picker
            v-model:value="form.activeDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择租户生效时间"
            style="width: 100%"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="到期时间:" name="expireDate">
          <a-date-picker
            v-model:value="form.expireDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到期时间"
            style="width: 100%"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="状态:" name="statusFlag">
          <a-radio-group v-model:value="form.statusFlag">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <div class="company">开通功能</div>
      </a-col>
      <a-col :span="24">
        <div style="margin-bottom: 10px"><a-button type="primary" class="border-radius" @click="addUse">+ 添加功能</a-button></div>
        <vxe-table
          border
          style="margin-bottom: 20px"
          show-overflow
          :data="form.tenantLinkList"
          :row-config="{ useKey: true }"
          :column-config="{ resizable: true }"
          max-height="600"
          ref="xTableRef"
        >
          <vxe-column type="seq" width="60" title="序号" align="center"></vxe-column>
          <vxe-column field="packageId" title="功能包" align="center">
            <template #default="{ row }">
              <a-select v-model:value="row.packageId" style="width: 100%; border-radius: 4px; text-align: left" placeholder="请选择功能包">
                <a-select-option :value="item.packageId" v-for="item in useList" :key="item.packageId">{{
                  item.packageName
                }}</a-select-option>
              </a-select>
            </template>
          </vxe-column>
          <vxe-column field="serviceEndTime" title="到期时间" width="200" align="center">
            <template #default="{ row }">
              <a-date-picker
                v-model:value="row.serviceEndTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择到期时间"
                style="width: 100%; border-radius: 4px"
              />
            </template>
          </vxe-column>
          <vxe-column field="trialFlag" title="是否试用" width="100" align="center">
            <template #default="{ row }">
              <vxe-switch v-model="row.trialFlag" open-value="Y" close-value="N"></vxe-switch>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="100" align="center">
            <template #default="{ row }">
              <icon-font iconClass="icon-opt-shanchu" font-size="24px" title="删除" color="#60666b" @click="remove(row)"></icon-font>
            </template>
          </vxe-column>
        </vxe-table>
      </a-col>
      <a-col :span="24">
        <div class="company">公司信息</div>
      </a-col>
      <a-col :span="12">
        <a-form-item label="公司名称:" name="companyName">
          <a-input v-model:value="form.companyName" allow-clear placeholder="请输入公司名称" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="统一社会信用代码:" name="companySocialCode">
          <a-input v-model:value="form.companySocialCode" allow-clear placeholder="请输入统一社会信用代码" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="公司地址:" name="companyAddress">
          <a-input v-model:value="form.companyAddress" allow-clear placeholder="请输入公司地址" />
        </a-form-item>
      </a-col>
    </a-row>

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

<script setup name="TenantForm">
import { onMounted, reactive, ref } 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 { VXETable } from 'vxe-table';

const props = defineProps({
  // 表单数据
  form: Object,
  isUpdate: {
    type: Boolean,
    default: false
  }
});

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

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

// 功能包列表
const useList = ref([]);

// 验证规则
const rules = reactive({
  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' }],
  statusFlag: [{ required: true, message: '请选择状态', type: 'number', trigger: 'change' }],
  iconList: [{ required: true, message: '请上传租户logo', type: 'array', trigger: 'blur' }],
  activeDate: [{ required: true, message: '请选择租户生效时间', type: 'string', trigger: 'change' }],
  expireDate: [{ required: true, message: '请选择到期时间', type: 'string', trigger: 'change' }]
});

onMounted(() => {
  getUseList();
});

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

//上传之前的回调
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, list) => {
  if (info.file.status === 'done') {
    // 设置临时fileList的值
    props.form[list] = [info.file];
    // 将文件属性名和文件编码存入数组中
    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 tenantNameChange = () => {
  props.form.companyName = props.form.tenantName;
};

// 添加功能包
const addUse = () => {
  let obj = {
    trialFlag: 'N',
    packageId: null,
    serviceEndTime: ''
  };
  props.form.tenantLinkList.push(obj);
};

// 删除机构
const remove = async row => {
  // 删除当前行
  const type = await VXETable.modal.confirm('您确定要删除该数据?');
  if (type === 'confirm') {
    const $table = xTableRef.value;
    $table.remove(row);
  }
  const res = xTableRef.value.getTableData().tableData;
  props.form.tenantLinkList = res;
};
</script>

<style scoped lang="less">
.company {
  border-left: 4px solid var(--primary-color);
  padding-left: 10px;
  margin-bottom: 20px;
}
</style>
