<template>
  <div>
    <router-view></router-view>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-input v-model="searchSymbol" placeholder="请输入标识"></el-input>
      </el-col>
      <el-col :span="6">
        <el-input v-model="searchContact" placeholder="请输入联系人"></el-input>
      </el-col>
      <el-col :span="6">
        <el-input v-model="searchPhone" placeholder="请输入手机号"></el-input>
      </el-col>
      <el-col :span="6">
        <el-input v-model="searchName" placeholder="请输入名称"></el-input>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-2">
      <el-col :span="24">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button plain @click="dialogVisible=true">修改</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="primary" @click="handleReset">重置</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%" class="mt-2" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="symbol" label="租户标识" width="120"></el-table-column>
      <el-table-column prop="contact" label="联系人" width="120"></el-table-column>
      <el-table-column prop="phone" label="电话" width="120"></el-table-column>
      <el-table-column prop="name" label="租户名称" width="120"></el-table-column>
      <el-table-column prop="manager" label="管理员" width="120"></el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="Tips" width="500" :before-close="handleClose">
      <span>修改租户信息</span>
      <template #footer>
        <div>
          <el-form :model="formData">
            <el-form-item label="姓名">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model="formData.contact"></el-input>
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="formData.phone"></el-input>
            </el-form-item>
            <el-form-item label="管理员">
              <el-input v-model="formData.manager"></el-input>
            </el-form-item>
          </el-form>
        </div>

        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="editFinished">确认修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import tenantService from "../../services/tenantService.js";
import { onMounted, ref, defineComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'

interface Tenant {
  symbol: string;
  contact: string;
  phone: string;
  name: string;
  manager: string;
}

export default defineComponent({
  setup() {
    const searchSymbol = ref('');
    const searchContact = ref('');
    const searchPhone = ref('');
    const searchName = ref('');
    const tableData = ref<Tenant[]>([]);

    const selectedRows = ref<Tenant[]>([]);
    const formData = ref({
      symbol: '',
      contact: '',
      phone: '',
      name: '',
      manager: '',
    });

    const dialogVisible = ref(false);

    const handleClose = (done: () => void) => {
      done();
    };

    const fetchData = async () => {
      try {
        const data = await tenantService.getAll();
        tableData.value = data;
      } catch (error) {
        console.error("Error fetching organization:", error);
      }
    };

    const handleSelectionChange = (rows) => {
      selectedRows.value = rows;
      if (rows.length === 1) {
        formData.value = { ...rows[0] };
      } else {
        formData.value = {
          symbol: '',
          contact: '',
          phone: '',
          name: '',
          manager: '',
        };
      }
    };

    const editFinished = async () => {
      try {
        await tenantService.update(formData.value);
        ElMessageBox.alert('删除成功', '提示', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK',
          callback: (action: Action) => {
            ElMessage({
              type: 'info',
              message: `action: ${action}`,
            })
          },
        })
        dialogVisible.value = false;
        location.href="/tenantManagement";
        fetchData();
      } catch (error) {
        console.error("Error updating user:", error);
      }
    };

    const handleAdd = () => {
      location.href = '/addTenant';
    };


    const handleDelete = async () => {
      try{
        await tenantService.delete(formData.value);
        ElMessageBox.alert('删除成功', '提示', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK',
          callback: (action: Action) => {
            ElMessage({
              type: 'info',
              message: `action: ${action}`,
            })
          },
        })
        fetchData();
      }catch(error){

      }
    };



    const handleSearch = async () => {
      tableData.value =tableData.value.filter(
          (data) => {
            const isNameValid = searchName.value;
            const isSymbolValid =searchSymbol.value;
            const isPhoneValid = searchPhone.value;
            const isContactValid = searchContact.value;
            // search.value && search.value.

            return (!isNameValid || data.name.toLowerCase().includes(searchName.value.toLowerCase())) &&
                (!isPhoneValid || data.phone.toLowerCase().includes(searchPhone.value.toLowerCase()) )&&
                (!isSymbolValid || data.symbol.toLowerCase().includes(searchSymbol.value.toLowerCase()))&&
                (!isContactValid || data.contact.toLowerCase().includes(searchContact.value.toLowerCase()))
          }
      )
    };


    const handleReset=()=>{
      location.href = '/tenantManagement';
    };

    onMounted(() => {
      fetchData();
    });

    return {
      tableData,
      handleAdd,
      formData,
      dialogVisible,
      handleClose,
      selectedRows,
      handleSelectionChange,
      editFinished,
      handleDelete,
      searchPhone,
      searchSymbol,
      searchName,
      searchContact,
      handleSearch,
      handleReset

    };
  }
});
</script>

<style>
.mt-2 {
  margin-top: 20px;
}
</style>
