<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="county" label-width="100px">
              <AddressSelector v-model="queryParams.county" clearable />
            </el-form-item>
            <el-form-item label="代理人姓名:" prop="personName" label-width="100px">
              <el-input v-model="queryParams.contactUserName" placeholder="请输入代理人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="代理人电话:" prop="contactPhone" label-width="100px">
              <el-input v-model="queryParams.contactPhone" placeholder="请输入代理人电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="签约日期" prop="signTime" label-width="100px">
              <el-date-picker
                v-model="queryParams.signTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="签约状态:" prop="signStatus" label-width="100px">
              <el-select v-model="queryParams.signStatus" placeholder="请选择签约状态" clearable :style="{ width: '240px' }">
                <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="['account:agent:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['account:agent:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['account:agent: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="county">
          <template #default="scope">
            {{ JSON.parse(scope.row.county).join('、') }}
          </template>
        </el-table-column>
        <el-table-column label="代理机构" align="center" prop="agencyName" />
        <el-table-column label="代理人姓名" align="center" prop="contactUserName" />
        <el-table-column label="签约日期" align="center" prop="signDate" />
        <el-table-column label="负责人联系电话" align="center" prop="contactPhone">
          <template #default="scope">
            {{ getPhon(scope.row.contactPhone) }}
          </template>
        </el-table-column>
        <el-table-column label="签约状态" align="center" prop="signStatus">
          <template #default="scope">
            {{ signfun(scope.row.signStatus) }}
          </template>
        </el-table-column>

        <el-table-column label="有效期" align="center" prop="agencyYear">
          <template #default="scope"> {{ scope.row.agencyYear }}年 </template>
        </el-table-column>
        <el-table-column label="保证金" align="center" prop="depositAmount">
          <template #default="scope"> {{ scope.row.depositAmount }}万 </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="['account:agent: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="['account:agent:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="同步套餐" placement="top">
              <el-button v-hasPermi="['account:agent:edit']" link type="primary" icon="Refresh" @click="handleSyncTenantPackage(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['account:agent: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 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="agencyName">
                <el-input v-model="form.agencyName" placeholder="请输入代理机构名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属区县:" prop="county">
                <AddressSelector v-model="form.county" />
              </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="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="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="birthday">

                <el-date-picker v-model="form.birthday" type="date" clearable value-format="YYYY-MM-DD HH:mm:ss" 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="payeeName">
                <el-input v-model="form.payeeName" type="text" placeholder="请输入收款方名称" />
              </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="emergencyContact">
                <el-input v-model="form.emergencyContact" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话:" prop="emergencyContactPhone">
                <el-input v-model="form.emergencyContactPhone" 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-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="date" 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="depositAmount" align="left">
                <el-input v-model="form.depositAmount" placeholder="请输入保证金金额(万)" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代理年限" prop="agencyYear" align="left">
                <el-input v-model="form.agencyYear" placeholder="请输入代理年限" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约状态" prop="signStatus" align="left">
                <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-col :span="8">
              <el-form-item label="协议附件" prop="agreement" align="left">
                <oss-image-upload v-model="form.agreement" :limit="1"> </oss-image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="其他附件" prop="otherAttachment" align="left">
                <oss-image-upload v-model="form.otherAttachment" :limit="1"> </oss-image-upload>
              </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="agencyName">
                {{ tenantForm.agencyName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属区县:" prop="county">
                {{ JSON.parse(tenantForm.county).join('、') }}
              </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="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="idCardType">
                {{ certificateList[tenantForm.idCardType].label }}
              </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="birthday">
                <!-- <el-date-picker v-model="form.birthday" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择出生年月">
                </el-date-picker> -->
                {{ tenantForm.birthday }}
              </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="payeeName">
                {{ tenantForm.payeeName }}
              </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="emergencyContact">
                {{ tenantForm.emergencyContact }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话:" prop="emergencyContactPhone">
                {{ tenantForm.emergencyContactPhone }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租户套餐:" prop="packageId">
                {{ packageList.filter((item) => item.packageId == tenantForm.packageId)[0]?.packageName }}
              </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">
                {{ fnall.filter((item) => item.id == tenantForm.splitRatio)[0]?.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="depositAmount" align="left"> {{ tenantForm.depositAmount }}万 </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代理年限" prop="agencyYear" align="left"> {{ tenantForm.agencyYear }}年 </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签约状态" prop="signStatus" align="left">
                {{ signList[tenantForm.signStatus]?.label }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="协议附件" prop="agreement" align="left">
                <el-image style="width: 100px; height: 100px" :src="tenantForm.agreement" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="其他附件" prop="otherAttachment" align="left">
                <el-image style="width: 100px; height: 100px" :src="tenantForm.otherAttachment" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </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 AddressSelector from '@/views/components/AddressSelector/index.vue';
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 } from '@/api/agent/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<TenantForm[]>([]);
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 userSelectLoading = ref(false);
const userSelectOption = ref([]);
const userSelectfun = (query: string) => {};

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;
};
const signfun = (data: any) => {
  return signList.value.find((item) => item.value === data)?.label;
};

const certificateList = ref([]); // 证件类型
const bankList = ref([]); // 银行类型
const signList = ref([]); // 签约状态
const getByKey = async () => {
  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 fnall = ref([]);
const accountCountFun = async () => {
  const res = await getlistDivide();
  fnall.value = res.data;
};
const initFormData: TenantForm = {
  id: undefined,
  // 代理机构名称
  agencyName: '',
  // 所属区县
  county: '',
  // 详细地址
  address: '',
  // 负责人姓名
  contactUserName: '',
  // 负责人联系电话
  contactPhone: '',
  // 负责人证件类型
  idCardType: '',
  // 证件信息
  idCard: '',
  // 证件图片
  certificate: '',
  // 出生年月
  birthday: '',
  // 代理人资质
  qualification: '',
  // 收款方名称
  payeeName: '',
  // 开户行名称
  bankName: '',
  // 银行卡账号
  bankCard: '',
  // 绑定银行卡的手机号
  bankPhone: '',
  // 用户名
  username: '',
  // 用户密码
  password: '',
  // 代理人套餐
  packageId: '',
  // 紧急联系人
  emergencyContact: '',
  // 联系人电话
  emergencyContactPhone: '',
  // 签约日期
  signDate: '',
  // 甲方签约人
  signer: '',
  // 保证金金额
  depositAmount: '',
  // 代理年限
  agencyYear: '',
  // 利润分成模板
  splitRatio: '',
  // 协议附件
  agreement: '',
  // 其他附件
  otherAttachment: '',
  // 签约状态
  signStatus: '0',
  type: 1
};

const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageSize: 10,
    pageNum: 1,
    current: 1,
    size: 10,
    type: 1,
    county: null, //区域
    contactUserName: null, //负责人
    contactPhone: null, //负责人电话
    signTime: null, //签约时间
    signStatus: null //签约状态
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    tenantId: [{ required: true, message: '租户编号不能为空', trigger: 'blur' }],
    // 代理机构名称
    agencyName: [{ required: true, message: '代理机构名称不能为空', trigger: 'blur' }],
    // 所属区县
    county: [{ required: true, message: '所属区县不能为空', trigger: 'blur' }],
    // 详细地址
    address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
    // 负责人姓名
    contactUserName: [{ required: true, message: '负责人姓名不能为空', trigger: 'blur' }],
    // 负责人联系电话
    contactPhone: [{ required: true, message: '负责人联系电话不能为空', trigger: 'blur' }],
    // 负责人证件类型
    idCardType: [{ required: true, message: '负责人证件类型不能为空', trigger: 'blur' }],
    // 证件信息
    idCard: [{ required: true, message: '证件信息不能为空', trigger: 'blur' }],
    // 证件图片
    certificate: [{ required: true, message: '证件图片不能为空', trigger: 'blur' }],
    // 出生年月
    birthday: [{ required: true, message: '出生年月不能为空', trigger: 'blur' }],
    // 代理人资质
    qualification: [{ required: true, message: '代理人资质不能为空', trigger: 'blur' }],
    // 收款方名称
    payeeName: [{ required: true, message: '收款方名称不能为空', trigger: 'blur' }],
    // 开户行名称
    bankName: [{ required: true, message: '开户行名称不能为空', trigger: 'blur' }],
    // 银行卡账号
    bankCard: [{ required: true, message: '银行卡账号不能为空', trigger: 'blur' }],
    // 绑定银行卡的手机号
    bankPhone: [{ required: true, message: '绑定银行卡的手机号不能为空', trigger: 'blur' }],
    // 代理人套餐
    packageId: [{ required: true, message: '代理人套餐不能为空', trigger: 'blur' }],
    // 紧急联系人
    emergencyContact: [{ required: true, message: '紧急联系人不能为空', trigger: 'blur' }],
    // 联系人电话
    emergencyContactPhone: [{ required: true, message: '联系人电话不能为空', trigger: 'blur' }],
    // 签约日期
    signDate: [{ required: true, message: '签约日期不能为空', trigger: 'blur' }],
    // 甲方签约人
    signer: [{ required: true, message: '甲方签约人不能为空', trigger: 'blur' }],
    // 保证金金额
    depositAmount: [{ required: true, message: '保证金金额不能为空', trigger: 'blur' }],
    // 代理年限
    agencyYear: [{ required: true, message: '代理年限不能为空', trigger: 'blur' }],
    // 利润分成模板
    splitRatio: [{ required: true, message: '利润分成模板不能为空', trigger: 'blur' }],
    // 协议附件
    agreement: [{ required: true, message: '协议附件不能为空', trigger: 'blur' }],
    // 其他附件
    otherAttachment: [{ required: true, message: '其他附件不能为空', trigger: 'blur' }],
    // 签约状态
    signStatus: [{ 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: any) => {
  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 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: any[]) => {
  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?: any) => {
  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?: any) => {
  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: any) => {
  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 {
  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper {
    width: 240px;
  }
  #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>
