<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="组织名称" prop="organizationName">
            <el-input v-model="queryParams.organizationName" placeholder="请输入组织名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="组织分类" prop="organizationType">
            <el-select v-model="queryParams.organizationType" placeholder="请选择组织分类" clearable style="width: 240px">
              <el-option v-for="dict in business_organization_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </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>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:tenantOrganization:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['business:tenantOrganization:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['business:tenantOrganization:remove']">删除</el-button>
          </el-col> -->
        </el-row>
      </template>

      <!-- <el-table v-loading="loading" :data="tenantOrganizationList" @selection-change="handleSelectionChange"> -->
      <el-table v-loading="loading" :data="tenantOrganizationList" :cellStyle="cellStyle">
        <el-table-column label="组织名称" align="center" prop="organizationName" />
        <el-table-column label="组织分类" align="center" prop="organizationType" :formatter="organizationTypeFormat" />
        <el-table-column label="所在地" align="center">
          <template #default="scope">
            {{ scope.row.provinceName + (scope.row.cityName ? ('/' + scope.row.cityName) : '') }}
          </template>
        </el-table-column>
        <el-table-column label="关联租户数" align="center" prop="tenantNumber" />
        <el-table-column label="课件数" align="center" prop="caseNumber" />
        <el-table-column label="状态" align="center" prop="status" :formatter="controlStatusFormat" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleStatus(scope.row)"
              v-hasPermi="['business:tenantOrganization:edit']"
              >{{ scope.row.status == '0' ? '禁用' : '启用' }}</el-button
            >
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['business:tenantOrganization:edit']">学会信息管理</el-button>
            <el-button link type="primary" @click="createTenant(scope.row)" v-hasPermi="['business:tenantOrganization:add']">新增关联租户</el-button>
            <el-button link type="primary" @click="handleDelete($event, scope.row)" v-hasPermi="['business:tenantOrganization:remove']"
              >删除</el-button
            >
          </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="800px" append-to-body>
      <el-form ref="tenantOrganizationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="组织名称" prop="organizationName" style="width: 60%;">
          <el-input
            v-model="form.organizationName"
            placeholder="请输入组织名称"
            maxlength="50"
            @input="(e) => (form.organizationName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, ''))"
          />
        </el-form-item>
        <el-form-item label="组织分类" prop="organizationType">
          <el-radio-group v-model="form.organizationType">
            <el-radio v-for="dict in business_organization_type" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所在地" prop="location">
          <el-select v-model="form.provinceCode" placeholder="请选择省" style="width: 210px;margin-right: 8px;" @change="handleProvinceSelect">
            <el-option v-for="item in regionData" :label="item.label" :value="item.value" />
          </el-select>
          <el-select
            v-model="form.cityCode"
            placeholder="请选择市"
            :disabled="!form.provinceCode || cityList.length == 0"
            style="width: 210px;"
            @change="handleCitySelect"
          >
            <el-option v-for="item in cityList" :label="item.label" :value="item.value" />
          </el-select>
          <!-- <el-select v-model="address.area" placeholder="请选择区" style="width: 210px;"
            :disabled="!address.province || !address.city || areaList.length == 0" @change="handleAreaSelect">
            <el-option v-for="item in areaList" :label="item.label" :value="item.value" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in business_enable_status" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="组织logo" prop="organizationLogo">
          <el-upload
            class="upload-demo"
            drag
            :headers="upload.headers"
            v-model:file-list="form.organizationLogo"
            :action="upload.url"
            :limit="1"
            :on-success="handleFileSuccess"
            accept=".png"
            :before-upload="checkFileType"
            :on-error="handleFileError"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">支持扩展名：.png</div>
          </el-upload>
        </el-form-item>
      </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="TenantOrganization" lang="ts">
import { listTenantOrganization, getTenantOrganization, delTenantOrganization, addTenantOrganization, updateTenantOrganization } from '@/api/business/tenantOrganization';
import { TenantOrganizationVO, TenantOrganizationQuery, TenantOrganizationForm, AreaList } from '@/api/business/tenantOrganization/types';
import { TableColumnCtx, UploadFiles, UploadUserFile } from 'element-plus';
import { regionData, codeToText } from 'element-china-area-data';
import { ComputedRef } from 'vue';
import { globalHeaders } from '@/utils/request';
import { fa } from 'element-plus/es/locale';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { business_organization_type, business_enable_status } = toRefs<any>(proxy?.useDict('business_organization_type', 'business_enable_status'));
const router = useRouter();

const tenantOrganizationList = 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 queryFormRef = ref<ElFormInstance>();
const tenantOrganizationFormRef = ref<ElFormInstance>();

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

const initFormData: TenantOrganizationForm = {
  id: undefined,
  organizationName: undefined,
  organizationType: '0',
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  organizationLogo: [],
  status: '0',
}
const data = reactive<PageData<TenantOrganizationForm, TenantOrganizationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    organizationName: undefined,
    organizationType: undefined,
  },
  rules: {
    organizationName: [
      { required: true, message: "组织名称不能为空", trigger: "blur" }
    ],
    organizationLogo: [
      { required: true, message: "组织名称logo不能为空", trigger: "blur" }
    ]
  }
});

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

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

const isComplete = ref(false)

//切换省份函数
const handleProvinceSelect = () => {
  form.value.cityCode = ''
  form.value.cityName = ''
  form.value.provinceName = codeToText[form.value.provinceCode]
  isComplete.value = false

}
//切换城市函数
const handleCitySelect = () => {
  form.value.cityName = codeToText[form.value.cityCode]
  isComplete.value = areaList.value.length == 0 ? true : false

}
//切换地区函数
// const handleAreaSelect = () => {
//   isComplete.value = true
// }
//二级城市列表
const cityList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!form.value.provinceCode) { return [] }
  let temp = regionData.find((item: any) => {
    return item.value == form.value.provinceCode
  })
  return temp?.children ? temp?.children : []
})
// 三级地区列表
const areaList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!form.value.provinceCode || !form.value.cityCode) { return [] }
  if (cityList.value.length == 0) {
    return []
  } else {
    let temp = cityList.value.find((item: any) => {
      return item.value == form.value.cityCode
    })
    if (temp) {
      return temp.children ? temp.children : []
    } else {
      return []
    }
  }
})

//列表控制状态
const controlStatusFormat = (row: TenantOrganizationVO, column: TableColumnCtx<TenantOrganizationVO>) => {
  if (row.status == '0') {
    return '启用'
  } else if (row.status == '1') {
    return '禁用'
  } else {
    return '未知'
  }
}

//列表控制状态
const organizationTypeFormat = (row: TenantOrganizationVO, column: TableColumnCtx<TenantOrganizationVO>) => {
  if (row.status == '0') {
    return '学会'
  } else if (row.status == '1') {
    return '协会'
  } else if (row.status == '2') {
    return '基金会'
  } else {
    return '学会'
  }
}

//批量导入-用户状态 文字颜色
const cellStyle = ({ row, column }) => {
  let controlStatusStyle
  switch (row.status) {
    case '0':
      controlStatusStyle = { 'color': '#67c23a' }
      break;
    case '1':
      controlStatusStyle = { 'color': '#f00' }
      break;
    default:
      controlStatusStyle = { 'color': '#000' }
      break;
  }
  if (column.label == '状态') {
    return controlStatusStyle
  }
}

/** 查询合作组织列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenantOrganization(queryParams.value);
  tenantOrganizationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加合作组织";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantOrganizationVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getTenantOrganization(_id);
  let temp = res.data
  if (!temp.organizationLogo) {
    temp.organizationLogo = []
  }
  Object.assign(form.value, temp);
  dialog.visible = true;
  dialog.title = "修改合作组织";
}

const createTenant = (row?: TenantOrganizationVO) => {
  router.push({ path: '/tenant/tenant', query: { organizationId: row?.id } });
}

/** 启用/禁用按钮操作 */
const handleStatus = async (row: TenantOrganizationVO) => {
  if (row.status == '1') {
    row.status = '0'
  } else {
    row.status = '1'
  }
  await updateTenantOrganization(row)
  await getList();
}

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

const checkFileType = (file?: any) => {
  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.'));
  let arr = ['.png']
  if (arr.indexOf(fileType) == -1) {
    proxy?.$modal.msgError('上传文件格式错误');
    return false;
  }
  upload.isUploading = true
};

/** 文件上传失败 */
const handleFileError = () => {
  upload.isUploading = false
}


/** 提交按钮 */
const submitForm = () => {

  tenantOrganizationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.organizationLogo && form.value.organizationLogo.length > 0) {
        let temp = form.value.organizationLogo[0] as any
        let tempFile = {
          ossId: temp.ossId?temp.ossId:temp.response.data.ossId,
          name: temp.name?temp.name:temp.response.data.name,
          url: temp.url?temp.url:temp.response.data.url
        }
        form.value.organizationLogo = [tempFile]
      }
      if (form.value.id) {
        await updateTenantOrganization(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addTenantOrganization(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (event: any, row?: TenantOrganizationVO) => {
  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 + '"的数据项？').finally(() => loading.value = false);
  await delTenantOrganization(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

onMounted(() => {
  getList();
});
</script>
