<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="租户名称" prop="companyName">
              <el-input v-model="queryParams.companyName" placeholder="请输入租户名称" clearable style="width: 240px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合作组织" prop="tenantOrganization">
              <el-select v-model="queryParams.tenantOrganization" placeholder="请选择合作组织" clearable style="width: 240px">
                <el-option v-for="item in organizationList" :key="item.id" :label="item.organizationName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-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 type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:tenant:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:tenant:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete($event)"
              v-hasPermi="['system:tenant:remove']">
              删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="租户编号" align="center" prop="tenantId" />
        <el-table-column label="租户名称" align="center" prop="companyName" />
        <el-table-column label="合作组织" align="center" prop="organizationName" />
        <el-table-column label="联系人" align="center" prop="contactUserName" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="用户数" align="center" prop="userNumber" />
        <el-table-column label="课件数" align="center" prop="caseNumber" />
        <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="300" label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <!--  icon="Edit" -->
              <el-button link type="primary" style="font-size: 12px;" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:tenant:edit']">修改</el-button>
            </el-tooltip>
            <el-tooltip content="课件查看" placement="top">
              <!-- icon="Refresh" -->
              <el-button link type="primary" style="font-size: 12px;" @click="handleViewCase(scope.row)"
                v-hasPermi="['system:tenant:view']">课件查看</el-button>
            </el-tooltip>
            <el-tooltip content="同步套餐" placement="top">
              <!-- icon="Refresh" -->
              <el-button link type="primary" style="font-size: 12px;" @click="handleSyncTenantPackage($event, scope.row)"
                v-hasPermi="['system:tenant:edit']">同步套餐</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <!-- icon="Delete" -->
              <el-button link type="primary" style="font-size: 12px;" @click="handleDelete($event, scope.row)"
                v-hasPermi="['system:tenant:remove']">删除</el-button>
            </el-tooltip>
            <el-tooltip content="查看地址" placement="top">
              <!--  icon="View" -->
              <el-button link type="primary" style="font-size: 12px;" @click="viewUrl(scope.$index)"
                v-hasPermi="['system:tenant:viewUrl']">查看地址</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="550px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="80px" style="padding: 15px 30px;">
        <el-form-item label="租户名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入租户名称" maxlength="30"
            @input="(e) => (form.companyName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, ''))" />
        </el-form-item>
        <el-form-item label="合作组织" prop="tenantOrganization">
          <el-select v-model="form.tenantOrganization" placeholder="请选择合作组织" clearable style="width: 100%"
            @change="onOrganizationChange">
            <el-option v-for="item in organizationList" :key="item.id" :label="item.organizationName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUserName">
          <el-input v-model="form.contactUserName" placeholder="请输入联系人" @input="(e) => (form.contactUserName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, ''))"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>
        <el-form-item label="租户套餐" prop="packageId">
          <el-select v-model="form.packageId" :disabled="!!form.tenantId" 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-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="注册" prop="register">
          <el-radio-group v-model="form.register">
            <el-radio v-for="dict in sys_register_status" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核" prop="caseReview">
          <el-radio-group v-model="form.caseReview">
            <el-radio v-for="dict in sys_tenant_review_comment" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="点评" prop="caseComment">
          <el-radio-group v-model="form.caseComment">
            <el-radio v-for="dict in sys_tenant_review_comment" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="评分" prop="caseCommentScore" v-if="form.caseComment == '0'">
          <el-radio-group v-model="form.caseCommentScore">
            <el-radio v-for="dict in sys_tenant_review_comment" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="点评分配" prop="caseCommentDistribution" v-if="form.caseComment == '0'">
          <el-radio-group v-model="form.caseCommentDistribution">
            <el-radio v-for="dict in comment_allocation" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="授权登录" prop="authorizedLogin">
          <el-checkbox-group v-model="form.authorizedLogin">
            <el-checkbox v-for="dict in sys_register_type" :key="dict.value" :label="dict.value" :disabled="dict.value == '0'">
              {{ dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="水印" prop="waterMarkText">
          <el-input v-model="form.waterMarkText" placeholder="请输入水印" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <el-form-item label="项目相关协议" prop="agreementFileList" required>
        <el-upload class="agreement-upload-wrap" v-model:file-list="form.agreementFileList" :headers="upload.headers" :action="upload.url" :limit="2"
          :on-remove="handleRemove" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
          :before-upload="checkFileType" accept=".pdf, .doc, .docx" :on-error="handleFileError">
          <el-button type="primary">上传协议</el-button>
        </el-upload>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" :disabled="upload.isUploading" type="primary" @click="submitForm">确
            定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改租户对话框 -->

    <!-- 查看地址 -->
    <el-dialog :title="viewUrldialog.title" v-model="viewUrldialog.visible" width="800px" append-to-body>
      <div class="view_url">
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">租户名称：</el-col>
          <el-col :span="18" style="margin-top: 15px;">{{ tenantList[viewUrlIndex].companyName }}</el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">学会管理端地址：</el-col>
          <el-col :span="18" class="text_right" v-show="tenantList[viewUrlIndex].pcAccessPath">
            <div>{{ tenantList[viewUrlIndex].pcAccessPath || '' }}</div>
            <el-icon class="text_right_icon" @click="openUrl(tenantList[viewUrlIndex].pcAccessPath)">
              <Connection />
            </el-icon>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">用户端地址：</el-col>
          <el-col :span="18" class="text_right" v-show="tenantList[viewUrlIndex].appAccessPath">
            <div>{{ tenantList[viewUrlIndex].appAccessPath || '' }}</div>
            <el-icon class="text_right_icon" @click="openUrl(tenantList[viewUrlIndex].appAccessPath)">
              <Connection />
            </el-icon>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="hideViewUrlDialog">确 定</el-button>
          <el-button @click="hideViewUrlDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看地址 -->

    <!-- 课件查看 -->
    <view-case ref="viewRef" :tenantId="viewTenantId" @ok="dynamicClearEvent"></view-case>
    <!-- 课件查看 -->
  </div>
</template>

<script setup name="Tenant" lang="ts">
import { copyText } from 'vue3-clipboard'

import { listTenant, getTenant, delTenant, addTenant, updateTenant, changeTenantStatus, syncTenantPackage, listOrganization } from '@/api/system/tenant';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { TenantForm, TenantQuery, TenantVO, UploadFileVO } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';

import type { UploadFiles, UploadUserFile } from 'element-plus'
import { globalHeaders } from '@/utils/request';
import ViewCase from './viewCase.vue'

import { dynamicClear, dynamicTenant } from "@/api/system/tenant";
import { TenantOrganizationVO } from '@/api/business/tenantOrganization/types';

const viewRef = ref<InstanceType<typeof ViewCase>>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, sys_register_status, sys_register_type, sys_tenant_review_comment, comment_allocation }
  = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_register_status', 'sys_register_type', 'sys_tenant_review_comment', 'comment_allocation'));
const router = useRouter();
const organizationId = ref<string>()

const tenantList = ref<TenantVO[]>([]);
const packageList = ref<TenantPkgVO[]>([]);
const organizationList = ref<TenantOrganizationVO[]>([]);
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 viewUrlIndex = ref(-1)
const viewTenantId = ref(<string>'')

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

const upload = reactive<ImportOption>({
  open: false,
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/resource/oss/upload"
})

//添加或修改租户对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const viewUrldialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  contactUserName: '',
  contactPhone: '',
  companyName: '',
  remark: '',
  waterMarkText: '',
  packageId: '',
  status: '0',
  organizationName: '',
  tenantOrganization: '',
  register: '0',
  pcAccessPath: '',
  appAccessPath: '',
  authorizedLogin: ['0'],
  agreementFileList: [],
  caseReview: '0',
  caseComment: '0',
  caseCommentScore: '0',
  caseCommentDistribution: '0',
}
const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: '',
    contactUserName: '',
    contactPhone: '',
    companyName: '',
    tenantOrganization: ''
  },
  rules: {
    id: [{ required: true, message: "id不能为空", trigger: "blur" }],
    tenantId: [{ required: true, message: "租户编号不能为空", trigger: "blur" }],
    contactUserName: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
    contactPhone: [{ required: true, message: "联系电话不能为空", trigger: "blur" },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    companyName: [{ required: true, message: "租户名称不能为空", trigger: "blur" }],
    tenantOrganization: [{ required: true, message: "合作组织不能为空", trigger: "blur" }],
    // agreementFileList: [{ required: true, message: "项目相关协议不能为空", trigger: "blur" }]
  }
});

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

/** 查询所有租户套餐 */
const getTenantPackage = async () => {
  const res = await selectTenantPackage()
  packageList.value = res.data;
}

/** 获取合作组织下拉列表 */
const getOrganizationList = async () => {
  const res = await listOrganization();
  organizationList.value = res.data
}

/** 查询租户列表 */
const getList = async () => {
  //清空上传文件列表
  loading.value = true;
  const res = await listTenant(queryParams.value);
  tenantList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

// 租户套餐状态修改
const handleStatusChange = async (row: TenantVO) => {
  let 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 openUrl = (url: string) => {
  if (url) {
    copyText(url, undefined, (error: any) => {
      if (error) {
        ElMessage.error('复制失败！');
      } else {
        ElMessage.success('复制成功！');
      }
    });


  }
}

const onOrganizationChange = (value: string) => {
  let temp = organizationList.value.filter(item => item.id == value)
  if (temp && temp.length > 0) {
    form.value.organizationName = temp[0].organizationName
  }
}

const hideViewUrlDialog = () => {
  viewUrldialog.visible = false
}

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 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 = async () => {
  reset();
  await getTenantPackage();
  await getOrganizationList();
  dialog.visible = true;
  dialog.title = "添加租户";
  if(organizationId.value){
    form.value.tenantOrganization = organizationId.value
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantVO) => {
  reset();
  await getTenantPackage();
  await getOrganizationList();

  const _id = row?.id || ids.value[0];
  const res = await getTenant(_id);
  let temp = res.data
  if (temp.authorizedLogin) {
    temp.authorizedLogin = (temp.authorizedLogin as String).split(',')
  } else {
    temp.authorizedLogin = ['0']
  }

  if (!temp.agreementFileList) {
    temp.agreementFileList = []
  }
  Object.assign(form.value, temp)
  dialog.visible = true;
  dialog.title = "修改租户";
}

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!form.value.agreementFileList || form.value.agreementFileList.length == 0) {
        proxy?.$modal.msgError('请上传项目协议')
        return
      } else {
        let tempArr: Array<UploadFileVO> = []
        form.value.agreementFileList.forEach(element => {
          if (element.response) {
            let tempVO = element.response as any
            tempArr.push({
              name: tempVO.data.name,
              url: tempVO.data.url,
              ossId: tempVO.data.ossId
            })
          } else {
            tempArr.push({
              name: element.name,
              url: element.url,
              ossId: element.ossId
            })
          }
        });
        form.value.agreementFileList = tempArr
      }

      buttonLoading.value = true;
      let temp = JSON.parse(JSON.stringify(form.value))
      temp.authorizedLogin = temp.authorizedLogin.toString()
      if (temp.id) {
        await updateTenant(temp).finally(() => buttonLoading.value = false);
      } else {
        await addTenant(temp).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (event:any, row?: TenantVO) => {
  let target = event.target;
  if(target.nodeName == "SPAN"){
   target = event.target.parentNode;
  }
  target.blur();

  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 dynamicClearEvent = async () => {
  await dynamicClear();
}

/** 查看课件 */
const handleViewCase = async (row: TenantVO) => {
  viewTenantId.value = row?.tenantId
  await dynamicTenant(row?.tenantId)
  viewRef.value?.show();
}

/** 同步租户套餐按钮操作 */
const handleSyncTenantPackage = async (event:any, row: TenantVO) => {
  let target = event.target;
  if(target.nodeName == "SPAN"){
   target = event.target.parentNode;
  }
  target.blur();

  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 viewUrl = (index: any) => {
  viewUrlIndex.value = index
  viewUrldialog.title = '学会管理端及用户端地址查看'
  viewUrldialog.visible = true
}

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

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
}

const handleRemove = (file: UploadFile, uploadFiles: UploadFiles) => {
  proxy?.$modal.msgSuccess("文件删除成功");
}
const handleFileError = () => {
  upload.isUploading = false
};
const checkFileType = (file?: any) => {
  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.'));
  console.log(fileType, 'fileType');
  let arr = ['.pdf', '.doc', '.docx']
  if (arr.indexOf(fileType) == -1) {
    proxy?.$modal.msgError('上传文件格式错误');
    return false;
  }
  upload.isUploading = true
  // if (fileType != ('.pdf' || '.MP4' || '.doc' || '.docx' || '.pdf' || '.jpg' || '.ppt' || '.word')) {
  //   proxy?.$modal.msgError('上传文件格式错误');
  //   return false;
  // }
};

const handleFileSuccess = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {
  console.log('上传成功:response===', response)
  console.log('上传成功:file===', file)
  upload.isUploading = false;
  if (form.value.agreementFileList) {
    form.value.agreementFileList = form.value.agreementFileList.filter((item:any) => !item?.response?.code || item?.response?.code == '200')
  }
  if (response.code == '200') {
    proxy?.$modal.msgSuccess('文件上传成功')
  } else {
    proxy?.$modal.msgError(response.msg || '文件上传失败，请重试')
  }
}


onMounted(() => {
  getOrganizationList();
  getList();
  organizationId.value = router.currentRoute.value.query.organizationId || ''
  if(organizationId.value){
    handleAdd()
  }
  //合作组织点击新增关联租户，id已经传过来，后续逻辑未实现
})
</script>
<style lang="scss" scoped>
.view_url {
  box-sizing: border-box;
  padding: 15px 30px;

  .text_left {
    font-size: 16px;
    font-weight: 600;
    color: black;
    margin-top: 15px;
  }

  .text_right {
    margin-top: 15px;
    color: blue;
    text-decoration: underline;
    display: flex;

    .text_right_icon {
      margin-left: 10px;
    }
  }

}
.agreement-upload-wrap{
  width:100%;
}
</style>
