<template>
  <div class="app-container">
    <!--租户数据-->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="85px"
    >
      <el-form-item label="租户名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入租户名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input
          v-model="queryParams.contactName"
          placeholder="请输入联系人姓名"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="租户状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button v-if="userStore.isSuperAdmin === 1" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tenantList">
      <el-table-column label="租户LOGO" align="center" prop="logoUrl" width="100">
        <template #default="scope">
          <!--  :preview-src-list="[scope.row.logoUrl]" -->
          <el-image
            v-if="scope.row.logoUrl"
            :src="scope.row.logoUrl"
            class="logo-image"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="租户名称" align="center" prop="tenantName" />
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="联系人电话" align="center" prop="contactPhone" />
      <el-table-column label="服务到期时间" align="center" prop="expireTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最大项目数" align="center" prop="maxProject" />
      <el-table-column label="最大用户数" align="center" prop="maxUser" />
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="val => handleStatusChange(scope.row, $event)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handlePermission(scope.row)"
            >分配权限</el-button
          >
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total >= 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body>
      <el-form :model="form" :rules="rules" ref="tenantRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="租户名称" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="请输入租户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industry">
              <el-input v-model="form.industry" placeholder="请输入所属行业" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入联系地址" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大项目数" prop="maxProject">
              <el-input v-model="form.maxProject" placeholder="请输入最大项目数" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大用户数" prop="maxUser">
              <el-input v-model="form.maxUser" placeholder="请输入最大用户数" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务到期时间" prop="expireTime">
              <el-date-picker
                v-model="form.expireTime"
                type="datetime"
                placeholder="选择到期日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_status"
                  :key="dict.value"
                  :value="Number(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="租户LOGO" prop="logoUrl">
              <image-upload
                v-model="form.logoUrl"
                :action="'/oss/api/oss/upload'"
                :limit="1"
                :file-size="3"
                :file-type="['png', 'jpg', 'jpeg']"
                :is-show-tip="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tenant">
import {
  listTenant,
  delUser,
  getTenant,
  updateTenant,
  addTenant,
  changeTenantStatus
} from '@/api/system/tenant'
import useUserStore from '@/store/modules/user'
import ImageUpload from '@/components/ImageUpload/index.vue' //图片上传组件

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_status, sys_scope, sys_no_yes } = proxy.useDict('sys_status', 'sys_scope', 'sys_no_yes')

const tenantList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref('')
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    tenantName: undefined,
    contactName: undefined,
    contactPhone: undefined,
    status: undefined
  },
  rules: {
    tenantName: [{ required: true, message: '租户名称不能为空', trigger: 'blur' }],
    contactEmail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    contactPhone: [
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询租户列表 */
function getList() {
  loading.value = true
  listTenant(queryParams.value).then(response => {
    tenantList.value = response.data.records
    total.value = response.data.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value
  proxy.$modal
    .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delUser(userIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
/** 租户状态修改  */
function handleStatusChange(row, event) {
  let text = row.status === 0 ? '停用' : '启用'
  const tenantName = row.tenantName
  proxy.$modal
    .confirm(`确认要${text}"${tenantName}"租户吗?`)
    .then(() => changeTenantStatus({ tenantBizId: row.tenantBizId, status: row.status }))
    .then(() => proxy.$modal.msgSuccess(`${text}成功`))
    .catch(() => {
      // 操作取消时恢复原状态
      row.status = row.status === 0 ? 1 : 0
    })
}
/** 重置操作表单 */
function reset() {
  form.value = {
    tenantBizId: undefined,
    tenantName: undefined,
    logoUrl: undefined,
    contactName: undefined,
    contactPhone: undefined,
    contactEmail: undefined,
    industry: undefined,
    address: undefined,
    status: '0',
    expireTime: undefined,
    maxProject: undefined,
    maxUser: undefined
  }
  proxy.resetForm('tenantRef')
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加租户'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const tenantBizId = row.tenantBizId
  getTenant(tenantBizId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改用户'
  })
}

/** 分配权限 */
function handlePermission(row) {
  router.push(`/system/tenant/permission?tenantBizId=` + row.tenantBizId)
}

/** 新增或者修改租户提交按钮 */
function submitForm() {
  proxy.$refs['tenantRef'].validate(valid => {
    if (valid) {
      if (form.value.tenantBizId != undefined) {
        updateTenant(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          reset()
          getList()
        })
      } else {
        addTenant(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          reset()
          getList()
        })
      }
    }
  })
}

getList()
</script>
<style scoped lang="scss">
.logo-image {
  width: 70px;
  height: 70px;
  border-radius: 4px;
  object-fit: cover;
}
.avatarBox {
  display: flex;
  flex-direction: column;
  width: 100%;
  .avatar-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar-uploader:hover {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 40px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 50px;
  }

  .avatar {
    width: 80%;
    height: 80%;
    object-fit: contain;
  }

  .upload-progress {
    margin-top: 10px;
    width: 50%;
  }

  .progress-text {
    display: block;
    text-align: left;
    margin-top: 5px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  .el-upload__tip {
    margin-top: 10px;
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }
  .deleteIcon {
    color: #fff;
    font-size: 18px;
    cursor: pointer;
  }
  .avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s;
    border-radius: 6px;
  }
  .avatar-overlay:hover {
    opacity: 1;
  }
}
</style>
