<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title">物资清单</div>
    </div>
    <div class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <el-button
            type="primary"
            class="search-table-container--button"
            :icon="Plus"
            @click="handleAddSupply"
            v-if="emergencySupplyPermissions"
            >添加物资
          </el-button>
          <el-button
            type="primary"
            class="search-table-container--button"
            v-if="emergencySupplyPermissions"
            @click="handleInventory"
          >
            <template #icon>
              <SvgIcon iconName="inventory-check" />
            </template>
            发起盘点
          </el-button>
          <BasicSearch
            :searchConfig="SUPPLY_LIST_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #emergencyType>
              <el-select v-model="searchData.emergencyType" placeholder="请选择应急事件类型" filterable>
                <el-option
                  v-for="item in emergencyEventDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
            <template #supplyType>
              <el-select v-model="searchData.supplyType" placeholder="请选择物资类型" filterable>
                <el-option
                  v-for="item in emergencySupplyDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
            <template #park>
              <el-select v-model="searchData.park" placeholder="请选择园区">
                <el-option
                  v-for="item in parkDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
          </BasicSearch>
        </header>
        <BasicTable :tableData="tableData" :tableConfig="tableConfig">
          <template #emergencyType="scope">
            <span>{{ getEmergencyEvent(scope.row.emergencyType) }}</span>
          </template>
          <template #supplyType="scope">
            <span>{{ getEmergencySupply(scope.row.supplyType) }}</span>
          </template>
          <template #park="scope">
            <span>{{ getPark(scope.row.park) }}</span>
          </template>
          <template #location="scope">
            <span>{{ getLocation(scope.row.location) }}</span>
          </template>
          <template #status="scope">
            <span :style="{ color: scope.row.status === EMERGENCY_SUPPLY_STATUS.DAMAGED ? 'red' : '' }">
              {{ getEmergencyStatus(scope.row.status) }}
            </span>
          </template>
          <template #remark="scope">
            <div class="remark--div">
              <el-tooltip
                :content="scope.row.remark"
                placement="top"
                effect="light"
                :popper-class="['custom-tooltip', scope.row.remark.length > 10 ? '' : 'custom-tooltip--opacity0']"
              >
                <span>{{ scope.row.remark }}</span>
              </el-tooltip>
            </div>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton text="查看" @click="handleViewDetail(scope.row.id)"/>
              <ActionButton text="编辑" v-if="emergencySupplyPermissions" @click="handleEditSupply(scope.row.id)" />
              <ActionButton
                text="删除"
                v-if="emergencySupplyPermissions"
                :popconfirm="{
                  title: '确定删除？',
                }"
                @confirm="handleDeleteSupply(scope.row.id)"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
  </div>
  <InventoryTask ref="inventoryTaskRef" />
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, reactive, onMounted } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  // @ts-ignore
  import SvgIcon from '@/components/SvgIcon/SvgIcon.vue';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import InventoryTask from './src/components/InventoryTask.vue';
  import {
    SUPPLY_LIST_SEARCH_CONFIG,
    SUPPLY_LIST_TABLE_COLUMNS,
    SUPPLY_LIST_TABLE_OPTIONS,
    SUPPLY_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    SUPPLY_LIST_TABLE_MAX_HEIGHT_PERMISSION,
  } from './src/config';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { useEmergencySuppliesHook } from './src/hook';
  import type { EmergencySupplyListQuery, EmergencySupplyListResponse } from '@/types/emergency-supplier';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { getEmergencySupplyList, deleteEmergencySupplyList } from '@/api/emergency-supplier';
  import { EMERGENCY_PERMISSIONS } from '@/views/emergency/src/constant';
  import { EMERGENCY_SUPPLY_STATUS } from './src/constant';

  const router = useRouter();
  const {
    emergencyEventDice,
    getEmergencyEventDict,
    getEmergencyEvent,
    emergencySupplyDice,
    getEmergencySupplyDict,
    getEmergencySupply,
    getEmergencyStatus,
    parkDice,
    getParkDict,
    getPark,
    getLocationDict,
    getLocation,
  } = useEmergencySuppliesHook();
  const { permissions } = useUserInfoHook();
  const { tableConfig, pagination } = useTableConfig(SUPPLY_LIST_TABLE_COLUMNS, SUPPLY_LIST_TABLE_OPTIONS);
  const emergencySupplyPermissions = ref<Boolean>(false);
  let emergencySupplyListQuery: QueryPageRequest<EmergencySupplyListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const tableData = ref<EmergencySupplyListResponse[]>([]);
  const searchData = reactive({
    emergencyType: null,
    supplyType: null,
    supplyName: null,
    park: null,
    location: null,
    keeperName: null,
    status: null,
  });
  const handleSearch = () => {
    emergencySupplyListQuery.queryParam = {};
    if (searchData.emergencyType) {
      emergencySupplyListQuery.queryParam.emergencyType = searchData.emergencyType;
    }
    if (searchData.supplyType) {
      emergencySupplyListQuery.queryParam.supplyType = searchData.supplyType;
    }
    if (searchData.supplyName) {
      emergencySupplyListQuery.queryParam.supplyName = searchData.supplyName;
    }
    if (searchData.park) {
      emergencySupplyListQuery.queryParam.park = searchData.park;
    }
    if (searchData.location) {
      emergencySupplyListQuery.queryParam.location = searchData.location;
    }
    if (searchData.keeperName) {
      emergencySupplyListQuery.queryParam.keeperName = searchData.keeperName;
    }
    if (searchData.status !== null) {
      emergencySupplyListQuery.queryParam.status = searchData.status;
    }
    getTableData();
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getEmergencySupplyList(emergencySupplyListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };

  const handleDeleteSupply = async (id: number) => {
    await deleteEmergencySupplyList(id);
    await getTableData();
    ElMessage.success('删除成功');
  };

  const inventoryTaskRef = ref<InstanceType<typeof InventoryTask>>();
  const handleInventory = () => {
    inventoryTaskRef.value?.openDialog();
  };

  const defaultRouterName = 'emergency-list-info';
  const handleAddSupply = () => {
    router.push({
      name: defaultRouterName,
      query: {
        type: 'add',
      },
    });
  };
  const handleEditSupply = (id: number) => {
    router.push({
      name: defaultRouterName,
      query: {
        id,
      },
    });
  };
  const handleViewDetail = (id:number) => {
    router.push({
      name: 'emergency-list-detail',
      params:{
        id
      }
    })
  }

  onMounted(() => {
    getEmergencyEventDict();
    getEmergencySupplyDict();
    getParkDict();
    getLocationDict('all');
    getTableData();
    emergencySupplyPermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.SUPPLY_LIST),
    );
    tableConfig.maxHeight = emergencySupplyPermissions.value
      ? SUPPLY_LIST_TABLE_MAX_HEIGHT_PERMISSION
      : SUPPLY_LIST_TABLE_MAX_HEIGHT_DEFAULT;
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use './src/styles/page-common.scss' as *;
</style>
