<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <!--店铺名称、负责人、联系人、推广人、店铺类型、地址、签约状态 -->
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="店铺名称:" prop="storeName" label-width="100px">
              <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="负责人:" prop="personName" label-width="100px">
              <el-input v-model="queryParams.personName" placeholder="请输入负责人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系人:" prop="contactUserName" label-width="100px">
              <el-input v-model="queryParams.contactUserName" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="推广人" prop="companyName">
              <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="企业名称:" prop="companyName" label-width="100px">
              <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="店铺类型:" prop="companyName" label-width="100px">
              <el-select v-model="queryParams.companyType" placeholder="请选择店铺类型" style="width: 100%" clearable>
                <el-option v-for="(item, index) in enterpriseList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="地址:" prop="address" label-width="100px">
              <el-input v-model="queryParams.address" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="签约状态:" prop="signStatus" label-width="100px">
              <el-select v-model="queryParams.signStatus" placeholder="请选择签约状态" clearable>
                <el-option v-for="(item, index) in signList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['system:tenant:query']">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button v-if="userId === 1" type="success" plain icon="Refresh" @click="handleSyncTenantDict">同步租户字典</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="tenantList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column label="企业名称" align="center" prop="companyName" />
        <el-table-column label="企业地址" align="center" prop="address" />
        <el-table-column label="负责人" align="center" prop="personName" />
        <el-table-column label="负责人联系电话" align="center" prop="personPhone">
          <template #default="scope">
            {{ getPhon(scope.row.personPhone) }}
          </template>
        </el-table-column>
        <el-table-column label="邀请人" align="center" prop="inviteUserName" />

        <!-- <el-table-column label="联系人" align="center" prop="contactUserName" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="身份证号" align="center" prop="idCard" />
        <el-table-column label="银行卡号" align="center" prop="bankCard" />
        <el-table-column label="社会信用代码" align="center" prop="licenseNumber" min-width="100" />
        <el-table-column label="营业执照" align="center" prop="businessLicense" />
        <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
         <el-table-column label="签约状态" align="center" prop="signStatus">
          <template #default="scope">
            {{ signList.filter((item) => item.value == scope.row.signStatus)[0]?.label }}
          </template>
        </el-table-column>
        <el-table-column label="租户状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column width="180" label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button v-hasPermi="['system:tenant:seach']" link type="primary" @click="funseach(scope.row, true)">
                <el-icon><Search /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="封禁记录" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" icon="User" @click="showTenantBannedInfoModal(scope.row, true)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="同步套餐" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" icon="Refresh" @click="handleSyncTenantPackage(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:tenant:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:current="queryParams.current" v-model:size="queryParams.size" :total="total" @pagination="getList" />
    </el-card>
    <!--租户封禁记录-->
    <el-dialog title="店铺封禁信息" v-model="tenantBannedInfoModalVisible" width="900px" append-to-body>
      <el-table v-loading="tenantBannedInfoTableLoading" :data="tenantBannedInfo.data" border empty-text="暂无数据">
        <!--        <el-table-column label="手机号" prop="phone" width="150">
          <template v-slot="scope">
            {{ userBannedInfo.record.nickname }}
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="nickname" width="150">
          <template v-slot="scope">
            {{ userBannedInfo.record.nickname }}
          </template>
        </el-table-column>-->
        <el-table-column label="封禁原因" prop="reason">
          <template v-slot="scope">
            {{ getEmulistLabelById(scope.row.reason, tenantForbiddenReasonMap) }}
          </template>
        </el-table-column>
        <el-table-column label="封禁次数" prop="times">
          <template v-slot="scope">
            {{ scope.row.times }}
          </template>
        </el-table-column>
        <el-table-column label="封禁时长" prop="unit">
          <template v-slot="scope">
            {{ scope.row.duration }}
            {{ getEmulistLabelById(scope.row.unit, tenantForbiddenUnitMap) }}
          </template>
        </el-table-column>
        <el-table-column label="封禁开始-结束时间" prop="startTime">
          <template v-slot="scope"> {{ scope.row.startTime }} - {{ scope.row.endTime }} </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="tenantBannedInfo.total"
        :total="tenantBannedInfo.total"
        v-model:page="bannedDataParams.current"
        v-model:limit="bannedDataParams.size"
        @pagination="
          () => {
            showTenantBannedInfoModal(tenantBannedInfo.record);
          }
        "
      />
    </el-dialog>
    <!-- 添加或修改租户对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules">
        <!-- 基本信息组 -->
        <div class="form-group">
          <h3 class="group-title">店铺信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="店铺名称:" prop="storeName">
                <el-input v-model="form.storeName" placeholder="请输入店铺名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业名称:" prop="companyName">
                <el-input v-model="form.companyName" placeholder="请输入企业名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码:" prop="licenseNumber">
                <el-input v-model="form.licenseNumber" placeholder="请输入统一社会信用代码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业类型:" prop="companyType">
                <el-select v-model="form.companyType" placeholder="请选择企业类型" style="width: 100%" clearable>
                  <el-option v-for="(item, index) in enterpriseList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经营类型:" prop="businessTypesjson">
                <el-select v-model="businessTypesjson" placeholder="请选择经营类型（可多选）" multiple collapse-tags style="width: 100%" clearable>
                  <el-option v-for="(item, index) in manageList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业地址:" prop="address">
                <el-input v-model="form.address" placeholder="请输入企业地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照附件:" prop="attachment">
                <oss-image-upload v-model="form.attachment" :limit="1"> </oss-image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="推广图片:" prop="promoteList">
                <oss-image-upload v-model="form.promoteList" :limit="1"> </oss-image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="相关资质及附件:" prop="related">
                <oss-image-upload v-model="form.related" :limit="1"> </oss-image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照号:" prop="businessLicense">
                <el-input v-model="form.businessLicense" placeholder="请输入营业执照号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照有效期:" prop="expireTime">
                <el-date-picker
                  v-model="form.expireTime"
                  clearable
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择营业执照有效期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="绑定域名:" prop="domain">
                <el-input v-model="form.domain" placeholder="请输入绑定域名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业简介:" prop="intro">
                <el-input v-model="form.intro" type="textarea" placeholder="请输入企业简介" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">人员信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="企业负责人:" prop="personName">
                <el-input v-model="form.personName" type="text" placeholder="请输入企业负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业负责人电话:" prop="personPhone">
                <el-input v-model="form.personPhone" type="text" placeholder="请输入企业负责人电话" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="负责人证件类型:" prop="idCardType">
                <el-select v-model="form.idCardType" placeholder="请选择负责人证件类型" style="width: 100%" clearable>
                  <el-option v-for="(item, index) in certificateList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责人证件信息:" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入负责人证件信息" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="证件信息:" prop="certificate">
                <oss-image-upload v-model="form.certificate" :limit="2"> </oss-image-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">收款账号信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="银行卡类型:" prop="bankType">
                <el-select v-model="form.bankType" placeholder="请选择银行卡类型" style="width: 100%" clearable>
                  <el-option v-for="(item, index) in bankList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户行全称:" prop="bankName">
                <el-input v-model="form.bankName" placeholder="请输入开户行全称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户卡账号:" prop="bankCard">
                <el-input v-model="form.bankCard" placeholder="请输入银行卡号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="绑定银行卡的手机号:" prop="bankPhone">
                <el-input v-model="form.bankPhone" type="text" placeholder="请输入绑定银行卡的手机号" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">用户信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="用户名:" prop="username">
                <el-input v-model="form.username" placeholder="请输入系统用户名" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用户密码:" prop="password">
                <el-input v-model="form.password" type="password" placeholder="请输入系统用户密码" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人:" prop="contactUserName">
                <el-input v-model="form.contactUserName" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话:" prop="contactPhone">
                <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租户套餐:" prop="packageId">
                <el-select v-model="form.packageId" placeholder="请选择租户套餐" clearable style="width: 100%">
                  <el-option v-for="item in packageList" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邀请人:" prop="inviteUserId">
                <el-select
                  v-model="form.inviteUserId"
                  placeholder="请选择邀请人"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getUserListByName"
                  :loading="userSelectLoading"
                  clearable
                  style="width: 100%"
                >
                  <el-option v-for="item in userSelectOption" :key="item.id" :label="item.nickname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注:" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">签约信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="签约日期" prop="signDate">
                <el-date-picker v-model="form.signDate" type="datetime" clearable value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择签约日期" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分成比例" prop="splitRatio">
                <!-- <el-input v-model="form.splitRatio" type="text" placeholder="请输入分成比例" /> -->
                <el-select v-model="form.splitRatio" placeholder="请选择分成比例">
                  <el-option v-for="item in fnall" :key="item.id" :label="item.templateName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约人" prop="signer" align="left">
                <el-input v-model="form.signer" placeholder="请输入签约人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同年限" prop="contractYear" align="left">
                <el-input v-model="form.contractYear" placeholder="请输入合同年限" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约附件" prop="contractAttachment" align="left">
                <oss-image-upload v-model="form.contractAttachment" :limit="1"> </oss-image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约状态" prop="signStatus" align="left" v-if="form.id">
                <el-select v-model="form.signStatus" placeholder="请选择签约状态" clearable>
                  <el-option v-for="(item, index) in signList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-model="sexDialog.visible" :title="sexDialog.title" width="1200px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules">
        <!-- 基本信息组 -->
        <div class="form-group">
          <h3 class="group-title">店铺信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="店铺名称:" prop="storeName">
                {{ tenantForm.storeName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业名称:" prop="companyName">
                {{ tenantForm.companyName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码:" prop="licenseNumber">
                {{ tenantForm.licenseNumber }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业类型:" prop="companyType">
                {{ enterprisefun(tenantForm.companyType) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经营类型:" prop="businessTypes">
                {{ managefun(tenantForm.businessTypes) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业地址:" prop="address">
                {{ tenantForm.address }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照附件:" prop="attachment">
                <el-image style="width: 100px; height: 100px" :src="tenantForm.attachment" fit="cover" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="推广图片:" prop="promoteList">
                <el-image style="width: 100px; height: 100px" :src="tenantForm.promoteList" fit="cover" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="相关资质及附件:" prop="related">
                <el-image style="width: 100px; height: 100px" :src="tenantForm.related" fit="cover" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照号:" prop="businessLicense">
                {{ tenantForm.businessLicense }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照有效期:" prop="expireTime">
                {{ tenantForm.expireTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="绑定域名:" prop="domain">
                {{ tenantForm.domain }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业简介:" prop="intro">
                {{ tenantForm.intro }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">人员信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="企业负责人:" prop="personName">
                {{ tenantForm.personName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业负责人电话:" prop="personPhone">
                {{ tenantForm.personPhone }}
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="负责人证件类型:" prop="idCardType">
                {{ certificatefun(tenantForm.idCardType) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责人证件信息:" prop="idCard">
                {{ tenantForm.idCard }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="证件信息:" prop="certificate">
                <div v-for="fit in tenantForm.certificate?.split(',')" :key="fit" class="block">
                  <el-image style="width: 100px; height: 100px" :src="fit" :fit="fit" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">收款账号信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="银行卡类型:" prop="bankType">
                {{ bankfun(tenantForm.bankType) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户行全称:" prop="bankName">
                {{ tenantForm.bankName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户卡账号:" prop="bankCard">
                {{ tenantForm.bankCard }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="绑定银行卡的手机号:" prop="bankPhone">
                {{ tenantForm.bankPhone }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">用户信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="用户名:" prop="username">
                {{ tenantForm.username }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用户密码:" prop="password">
                {{ tenantForm.password }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人:" prop="contactUserName">
                {{ tenantForm.contactUserName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话:" prop="contactPhone">
                {{ tenantForm.contactPhone }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租户套餐:" prop="packageId">
                {{ packagefun(tenantForm.packageId) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邀请人:" prop="inviteUserName">
                {{ tenantForm.inviteUserName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注:" prop="remark">
                {{ tenantForm.remark }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="form-group">
          <h3 class="group-title">签约信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="签约日期:" prop="signDate">
                {{ tenantForm.signDate }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分成比例:" prop="splitRatio">
                {{ tenantForm.templateName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约人:" prop="signer" align="left">
                {{ tenantForm.signer }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同年限:" prop="contractYear" align="left"> {{ tenantForm.contractYear }}年 </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约附件:" prop="contractAttachment" align="left">
                <el-image style="width: 100px; height: 100px" :src="tenantForm.contractAttachment" fit="cover" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约状态:" prop="signStatus" align="left">
                {{ signfun(tenantForm.signStatus) }}
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup name="Tenant" lang="ts">
import {
  getlistDivide,
  listTenant,
  getTenant,
  delTenant,
  addTenant,
  updateTenant,
  changeTenantStatus,
  syncTenantPackage,
  syncTenantDict,
  getTenantBannelList
} from '@/api/system/tenant';

import { listUmsMember } from '@/api/ums/member';
import { getDictionaryByKey } from '@/utils/dict';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { useUserStore } from '@/store/modules/user';
import { TenantForm, TenantQuery, TenantVO, TenantModal, enterpriseType } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/resource/oss/upload'); // 上传文件服务器地址
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantList = ref<TenantVO[]>([]);
const packageList = ref<TenantPkgVO[]>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const tenantBannedInfoModalVisible = ref(false);
const tenantBannedInfoTableLoading = ref(false);
const bannedDataParams = ref({
  current: 1,
  size: 10
});

const userSelectLoading = ref(false);
const userSelectOption = ref([]);
const userSelectfun = (query: string) => {};
// 用户封禁记录
const tenantBannedInfo = ref<TenantModal>({
  total: 0,
  data: [],
  record: {}
});

const tenantForbiddenUnitMap = ref([]);
const tenantForbiddenReasonMap = ref([]);

const queryFormRef = ref<ElFormInstance>();
const tenantFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const sexDialog = ref<DialogOption>({
  visible: false,
  title: ''
});
//详情数据
const tenantForm = ref<TenantForm>();
const funseach = (data) => {
  getTenantPackage();
  sexDialog.value.visible = true;
  tenantForm.value = data;
};
// 解析JSON格式字符串为数组
const parseJsonString = (data) => {
  // 1. 非字符串类型直接返回空数组
  if (typeof data !== 'string') {
    console.error('输入不是字符串类型:', data);
    return [];
  }

  try {
    // 2. 尝试JSON解析
    const parsedData = JSON.parse(data);
    // 3. 验证解析结果是否为数组
    if (Array.isArray(parsedData)) {
      return parsedData;
    } else {
      console.error('解析结果不是数组:', parsedData);
      return [];
    }
  } catch (error) {
    return [];
  }
};
const managefun = (data: any) => {
  const dataArray = data.split(',');
  console.log(typeof dataArray);
  let finds = '';
  dataArray.forEach((item) => {
    const matchedItem = manageList.value.find((option: any) => option.value === item);
    finds += matchedItem ? matchedItem.label + ',' : '';
  });
  return finds;
};
const certificatefun = (data: any) => {
  return certificateList.value.find((item) => item.value === data)?.label;
};
const enterprisefun = (data: any) => {
  return enterpriseList.value.find((item) => item.value === data)?.label;
};
const bankfun = (data: any) => {
  return bankList.value.find((item) => item.value === data)?.label;
};
const signfun = (data: any) => {
  return signList.value.find((item) => item.value === data)?.label;
};
const enterpriseList = ref([]); // 企业类型
const manageList = ref([]); // 经营类型
const certificateList = ref([]); // 证件类型
const bankList = ref([]); // 银行类型
const signList = ref([]); // 签约状态
const getByKey = async () => {
  const value1 = await getDictionaryByKey('sys_enterprise_type');
  enterpriseList.value = value1;
  const orderStatusresulttype = await getDictionaryByKey('sys_manage_type');
  manageList.value = orderStatusresulttype;
  const orderStatusreasontype = await getDictionaryByKey('sys_certificate_type');
  certificateList.value = orderStatusreasontype;
  const orderStatusaimobject = await getDictionaryByKey('sys_bank_type');
  bankList.value = orderStatusaimobject;
  const orderStatusstatus = await getDictionaryByKey('sys_sign_status');
  signList.value = orderStatusstatus;
};
const businessTypesjson = ref([]); //经营类型
const fnall = ref([]);
const accountCountFun = async () => {
  const res = await getlistDivide();
  fnall.value = res.data;
};
const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  storeName: '', //店铺名称
  contactUserName: '', //联系人
  contactPhone: '', //联系电话
  username: '', //用户名
  password: '', //用户密码
  companyName: '', //企业名称
  licenseNumber: '', //统一社会信用代码
  domain: '', //绑定域名
  address: '', //企业地址
  intro: '', //企业简介
  remark: '', //备注
  packageId: '', //租户套餐
  expireTime: '', //营业执照有效期,
  accountCount: 0,
  status: '0', //是否启用状态
  businessLicense: '', //营业执照号
  idCard: '', //负责人证件信息/身份证号
  bankCard: '', //开户卡账号
  bankType: '', //开户行类型
  bankName: '', //开户行名称
  bankPhone: '', //开户行预留手机号
  inviteUserId: '', //邀请人
  companyType: '', //企业类型
  businessTypes: '', //经营类型

  idCardType: '', //负责人证件类型
  personName: '', //负责人姓名
  personPhone: '', //负责人电话
  signDate: '', //签约日期
  splitRatio: '', //分成比例
  signer: '', //签约人
  contractYear: '', //合同年限
  signStatus: '1', //签约状态
  contractAttachment: '', //签约附件
  attachment: '', //营业执照附件
  promoteList: '', //推广附件
  related: '', //相关资质及附件
  certificate: '', //身份证附件
  type: 0
};

const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageSize: 10,
    pageNum: 1,
    current: 1,
    size: 10,
    type: 0,
    tenantId: null,
    personName: null, //负责人姓名
    storeName: null, //店铺名称
    contactUserName: null, //联系人
    companyName: null, //企业名称
    companyType: null, //企业类型
    address: null, //地址
    signStatus: null //签约状态
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    tenantId: [{ required: true, message: '租户编号不能为空', trigger: 'blur' }],
    bankPhone: [{ required: true, message: '开户行预留手机号不能为空', trigger: 'blur' }],
    contactUserName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    contractAttachment: [{ required: true, message: '签约附件不能为空', trigger: 'blur' }],
    attachment: [{ required: true, message: '营业执照附件不能为空', trigger: 'blur' }],
    signDate: [{ required: true, message: '签约日期不能为空', trigger: 'blur' }],
    certificate: [{ required: true, message: '身份证附件不能为空', trigger: 'blur' }],
    promoteList: [{ required: true, message: '推广附件不能为空', trigger: 'blur' }],
    packageId: [{ required: true, message: '套餐编号不能为空', trigger: 'blur' }],
    related: [{ required: true, message: '相关资质及附件不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
    personName: [{ required: true, message: '负责人姓名不能为空', trigger: 'blur' }],
    personPhone: [{ required: true, message: '负责人电话不能为空', trigger: 'blur' }],
    signer: [{ required: true, message: '签约人不能为空', trigger: 'blur' }],
    licenseNumber: [{ required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }],
    companyType: [{ required: true, message: '企业类型不能为空', trigger: 'blur' }],
    businessTypes: [{ required: true, message: '经营类型不能为空', trigger: 'blur' }],
    address: [{ required: true, message: '企业地址不能为空', trigger: 'blur' }],
    contractYear: [{ required: true, message: '合同年限不能为空', trigger: 'blur' }],
    splitRatio: [{ required: true, message: '分成比例不能为空', trigger: 'blur' }],
    businessLicense: [{ required: true, message: '营业执照号不能为空', trigger: 'blur' }],
    expireTime: [{ required: true, message: '到期时间不能为空', trigger: 'blur' }],
    idCardType: [{ required: true, message: '身份证类型不能为空', trigger: 'blur' }],
    idCard: [{ required: true, message: '身份证不能为空', trigger: 'blur' }],
    bankCard: [{ required: true, message: '银行卡不能为空', trigger: 'blur' }],
    bankType: [{ required: true, message: '银行类型不能为空', trigger: 'blur' }],
    bankName: [{ required: true, message: '开户行名称不能为空', trigger: 'blur' }],
    username: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ]
  }
});

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

/** 查询所有租户套餐 */
const getTenantPackage = async () => {
  const res = await selectTenantPackage();
  packageList.value = res.data;
};
const packagefun = (data) => {
  console.log(packageList.value);
  return packageList.value.find((item) => item.packageId === data)?.packageName;
};
// 查询人员列表
const getUserListByName = (params: string) => {
  if (params) {
    userSelectLoading.value = true;
    const query = { current: 1, size: 200, nickname: params };
    const pageReq = { current: 1, size: 200 };
    listUmsMember(query, pageReq).then((response) => {
      const { records = [] } = response.data || {};
      userSelectOption.value = records || [];
      userSelectLoading.value = false;
    });
  } else {
    userSelectOption.value = [];
    userSelectLoading.value = false;
  }
};

/** 查询租户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenant(queryParams.value);
  tenantList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

// 租户套餐状态修改
const handleStatusChange = async (row: TenantVO) => {
  const text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.companyName + '"租户吗？');
    await changeTenantStatus(row.id, row.tenantId, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};
// 展示账户封禁记录弹框
const showTenantBannedInfoModal = (record, isFirst) => {
  const { id } = tenantBannedInfo.record || {};
  const reqParams = {
    ...bannedDataParams.value,
    memberId: record.id ? record.id : id
  };
  tenantBannedInfoTableLoading.value = true;
  if (isFirst) {
    // 获取枚举
    getBannedReasonEmu();
  }
  getTenantBannelList(reqParams)
    .then((response) => {
      const { records = [], total = 0 } = response.data || {};
      if (isFirst) {
        tenantBannedInfoModalVisible.value = true;
      }
      tenantBannedInfo.value = {
        total: total,
        data: records || [],
        record: record
      };
      tenantBannedInfoTableLoading.value = false;
    })
    .catch(() => {
      tenantBannedInfoTableLoading.value = false;
    });
};

const getBannedReasonEmu = async () => {
  const reasonMap1 = await proxy?.getDictionaryByKey('ums_forbidden_unit');
  const reasonMap2 = await proxy?.getDictionaryByKey('sys_tenant_forbidden_reason');
  tenantForbiddenUnitMap.value = reasonMap1;
  tenantForbiddenReasonMap.value = reasonMap2;
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  tenantFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.current = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection: TenantVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getTenantPackage();
  dialog.visible = true;
  dialog.title = '新增店铺';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantVO) => {
  reset();
  await getTenantPackage();
  const _id = row?.id || ids.value[0];
  const res = await getTenant(_id);
  businessTypesjson.value = res.data.businessTypes?.split(',');
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改租户';
};

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTenant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        form.value.businessTypes = businessTypesjson.value.join(',');
        await addTenant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除租户编号为"' + _ids + '"的数据项？');
  loading.value = true;
  await delTenant(_ids).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 同步租户套餐按钮操作 */
const handleSyncTenantPackage = async (row: TenantVO) => {
  try {
    await proxy?.$modal.confirm('是否确认同步租户套餐租户编号为"' + row.tenantId + '"的数据项？');
    loading.value = true;
    await syncTenantPackage(row.tenantId, row.packageId);
    await getList();
    proxy?.$modal.msgSuccess('同步成功');
  } catch {
    return;
  } finally {
    loading.value = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/tenant/export',
    {
      ...queryParams.value
    },
    `tenant_${new Date().getTime()}.xlsx`
  );
};

/**同步租户字典*/
const handleSyncTenantDict = async () => {
  await proxy?.$modal.confirm('确认要同步所有租户字典吗？');
  const res = await syncTenantDict();
  proxy?.$modal.msgSuccess(res.msg);
};

onMounted(() => {
  accountCountFun();
  getByKey();
  getList();
});
</script>
<style scoped lang="scss">
.form-group {
  margin-bottom: 24px;
}

.group-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #1f2937;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}
.upload__tip {
  background: url('./d.png') no-repeat;
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
}
::v-deep {
  #searc {
    .el-form-item--default .el-form-item__label {
      width: 100px;
    }
  }
  .el-form-item__content {
    width: 240px;
  }
  .el-form-item--default .el-form-item__label {
    width: 150px;
  }
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
  }
  .el-upload-list {
    width: 320px;
    .el-upload-list__item {
      width: 100px;
      height: 100px;
    }
  }
}
</style>
