<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="personName" label-width="100px">
              <el-input v-model="queryParams.personName" placeholder="请输入负责人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="团长手机号:" prop="personPhone" label-width="100px">
              <el-input v-model="queryParams.personPhone" placeholder="请输入团长手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态:" prop="personPhone" label-width="100px">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="停用" value="1" />
                <el-option label="正常" value="0" />
              </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="personName" />
        <el-table-column label="聘任时间" align="center" prop="joinTime" />
        <el-table-column label="状态" align="center" prop="status">
          <template v-slot="scope">
            {{ scope.row.status === 0 ? '正常' : '停用' }}
          </template>
        </el-table-column>
        <el-table-column label="电话" align="center" prop="personPhone" />
        <el-table-column label="联系地址" align="center" prop="address"> </el-table-column>

        <el-table-column width="580" 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:edit']" link type="primary" @click="handleUpdate(scope.row)"> 修改</el-button>
            </el-tooltip>
            <!-- <el-tooltip content="提交" placement="top">
              <el-button v-hasPermi="['system:tenant:submit']" link type="primary" @click="handleTl(scope.row)"> 提交 </el-button>
            </el-tooltip> -->
            <!--  <el-tooltip content="审核" placement="top">
              <el-button v-hasPermi="['system:tenant:review']" link type="primary" @click="handleSh(scope.row)"> 审核 </el-button>
            </el-tooltip>
            <el-tooltip content="确认审核" placement="top">
              <el-button v-hasPermi="['system:tenant:confirm']" link type="primary" @click="handleSubmit(scope.row)"> 确认审核 </el-button>
            </el-tooltip>
            <el-tooltip content="切换租户状态" placement="top">
              <el-button v-hasPermi="['system:tenant:status']" link type="primary" @click="handleStatusChange(scope.row)"> 切换租户状态 </el-button>
            </el-tooltip> -->
            <el-tooltip content="同步套餐" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" @click="handleSyncTenantPackage(scope.row)"> 同步套餐 </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:tenant:remove']" link type="primary" @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="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="address">
                <el-input v-model="form.address" 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="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="joinTime">
                <el-date-picker v-model="form.joinTime" 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="certificate">
                <oss-image-upload v-model="form.certificate" :limit="2"> </oss-image-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="其它附件:" prop="otherAttachment">
                <oss-image-upload v-model="form.otherAttachment" :limit="1"> </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="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="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="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
              </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,
  getTenant,
  delTenant,
  addTenantdarren,
  updateTenantdarren,
  changeTenantStatus,
  syncTenantPackage,
  syncTenantDict,
  getTenantBannelList,
  getTenantSub,
  auditTenant,
  listTenantgetByReference,
  auditSubmit
} 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;
};

const handleTl = async (row) => {
  try {
    await ElMessageBox.confirm('确定要执行提交操作吗？', '确认提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // 用户确认后执行操作
    const res = await getTenantSub(row.tenantId);
    // 根据返回结果处理
    if (res.code == 200) {
      ElMessage.success('操作成功');
      // 这里可以添加刷新列表等操作
      getList();
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (error) {
    // 用户取消操作
    console.log('用户取消了操作');
  }
};
const handleSubmit = async (row) => {
  try {
    await ElMessageBox.confirm('确认审核通过的签约', '确认提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // 用户确认后执行操作
    const res = await auditSubmit(row.tenantId);
    // 根据返回结果处理
    if (res.code == 200) {
      ElMessage.success('操作成功');
      // 这里可以添加刷新列表等操作
      getList();
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (error) {
    // 用户取消操作
    console.log('用户取消了操作');
  }
};

const certificateList = ref([]); // 证件类型
const getByKey = async () => {
  const orderStatusreasontype = await getDictionaryByKey('sys_certificate_type');
  certificateList.value = orderStatusreasontype;
};
const businessTypesjson = ref([]); //经营类型
const fnall = ref([]);
const accountCountFun = async () => {
  const res = await getlistDivide();
  fnall.value = res.data;
};
const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  type: 2,
  personPhone: '', //团长电话
  address: '', //企业地址
  idCard: '', //负责人证件信息/身份证号
  certificate: '', //身份证附件
  password: '', //用户密码
  packageId: '', //租户套餐
  remark: '', //备注
  username: '', //用户名
  contractYear: '', //合同年限
  joinTime: '', //任聘时间
  idCardType: '', //团长证件类型
  personName: '', //团长姓名
  otherAttachment: '' //其他附件
};

const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    current: 1,
    size: 10,
    tenantId: null,
    personName: null, //负责人姓名
    personPhone: null, //负责人电话
    status: null //状态
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    tenantId: [{ required: true, message: '租户编号不能为空', trigger: 'blur' }],
    personPhone: [{ required: true, message: '团长电话不能为空', trigger: 'blur' }],
    address: [{ required: true, message: '企业地址不能为空', trigger: 'blur' }],
    idCard: [{ required: true, message: '负责人证件信息/身份证号不能为空', trigger: 'blur' }],
    certificate: [{ required: true, message: '身份证附件不能为空', trigger: 'blur' }],
    packageId: [{ required: true, message: '租户套餐不能为空', trigger: 'blur' }],
    // remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    contractYear: [{ required: true, message: '合同年限不能为空', trigger: 'blur' }],
    // joinTime: [{ required: true, message: '加入时间不能为空', trigger: 'blur' }],
    idCardType: [{ required: true, message: '证件类型不能为空', trigger: 'blur' }],
    personName: [{ 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(2);
  packageList.value = res.data;
};
const packagefun = (data) => {
  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 listTenantgetByReference(queryParams.value);
  tenantList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

// 租户套餐状态修改
const handleStatusChange = async (row: TenantVO) => {
  // 0启用 1停用
  const text = row.status === '0' ? '停用' : '启用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.companyName + '"租户吗？');
    await changeTenantStatus(row.id, row.tenantId, row.status == '0' ? '1' : '0');
    proxy?.$modal.msgSuccess(text + '成功');
    getList(); // 刷新列表
  } catch {
    getList(); // 刷新列表
  }
};
// 展示账户封禁记录弹框
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 handleSh = (row) => {
  ElMessageBox.confirm('请选择审核结果', '审核确认', {
    confirmButtonText: '通过',
    cancelButtonText: '不通过',
    distinguishCancelAndClose: true,
    type: 'warning'
  })
    .then(() => {
      // 点击"通过"按钮
      return auditTenant({
        tenantId: row.tenantId,
        isPass: true
      });
    })
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success('审核通过');
        getList(); // 刷新列表
      } else {
        ElMessage.error(res.msg || '审核失败');
      }
    })
    .catch((action) => {
      if (action === 'cancel') {
        // 点击"不通过"按钮才弹出输入框
        ElMessageBox.prompt('请输入不通过原因', '审核不通过', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          inputPattern: /^[\s\S]+$/,
          inputErrorMessage: '必须填写不通过原因',
          type: 'error'
        })
          .then(({ value }) => {
            return auditTenant({
              tenantId: row.tenantId,
              isPass: false, // 不通过
              failureReason: value
            });
          })
          .then((res) => {
            if (res.code === 200) {
              ElMessage.success('操作成功');
              getList(); // 刷新列表
            } else {
              ElMessage.error(res.msg || '操作失败');
            }
          });
      }
    });
};
// 取消按钮
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);
  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 updateTenantdarren(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenantdarren(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>
