<template>
  <div class="box">
    <div class="search-form">
      <QueryForm :ai-options="aiOptions" :manual-options="manualOptions" :location-options="locationOptions"
        @on-search="handleSearch" @on-reset="handleReset" />
      <div class="button-group">
        <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
      </div>
    </div>
    <div class="table-list">
      <div v-if="showActionBar" class="action-bar">
        <span class="num-text">已选{{ chooseNum }}项</span>
        <el-button :class="isActiveCancelHide ? 'btn-active' : 'btn-normal'"
          @click="handleCancelHideAll">全部生效</el-button>
        <el-button :class="isActiveHide ? 'btn-active' : 'btn-normal'" @click="handleHideAll">全部失效</el-button>
        <el-button :class="isActiveDelete ? 'btn-active' : 'btn-normal'" @click="handleDeleteAll">删除</el-button>
        <span class="close-btn" @click="handleSelectNone"></span>
      </div>
      <AlertTable ref="alertTableRef" class="table-bar" :is-show-tab="true" :table-data="tableData"
        :on-detail="handleDetail" :on-edit="handleEdit" :on-show="handleShow" :on-delete="handleDelete"
        @update:selection="handlePop" />
    </div>
    <div class="pagination-box">
      <Pagination v-model:page="query.pageNumber" v-model:size="query.pageSize" :total="total"
        @update:page="handlePageChange" @update:size="handleSizeChange" />
    </div>
    <DetailDialog v-if="isDetailDialogShow" :description="detailDescription" :image-paths="detailPictures"
      :video-paths="detailVideos" @close="closeDetailDialog" />
    <AddDrawer v-if="isAddDrawer" @close="handleAddDrawerClose" />
    <EditDrawer v-if="isEditDrawer" :initial-data="rowData" @close="handleEditDrawerClose" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import QueryForm from '../common/QueryForm.vue';
import AlertTable from '../common/AlertTable.vue';
import DetailDialog from '../common/DetailDialog.vue';
import Pagination from '../common/Pagination.vue';
import AddDrawer from '../common/AddDrawer.vue';
import EditDrawer from '../common/EditDrawer.vue';
import { useIssueType } from '../../hooks/useIssueType';
import { useWorkLocation } from '../../hooks/useWorkLocation';
import {
  getShowTableData,
  updateShowTableData,
  deleteShowTableData
} from '@/api/datamanagement/alert-show'

const { aiOptions, manualOptions, getAIOptions, getManualOptions } = useIssueType();
const { locationOptions, getLocationOptions } = useWorkLocation();

const alertTableRef = ref<typeof AlertTable>();
const tableData = ref([]);
const showActionBar = ref(false);
const chooseNum = ref(0);
const chooseId = ref<number[]>([]);
// const cancelHideFlag = ref(true);   // true取消隐藏 / false全部隐藏
const isActiveHide = ref(false);
const isActiveCancelHide = ref(false);
const isActiveDelete = ref(false);
// 详情
const isDetailDialogShow = ref(false);
const detailDescription = ref('');
const detailPictures = ref<string[]>([]);
const detailVideos = ref<string[]>([]);
// 添加
const isAddDrawer = ref(false);
const isEditDrawer = ref(false);
const rowData = ref();        // 编辑时填充row的tableData
// 分页
const total = ref(0);

const query = ref({
  pageNumber: 1,
  pageSize: 10
});
// 查询
const handleSearch = (queryForm) => {
  query.value = queryForm;
  getTableData();
};
// 重置
const handleReset = (queryForm) => {
  query.value = queryForm;
  getTableData();
};

// 多选
const handlePop = (selection) => {
  chooseId.value = [];
  // cancelHideFlag.value = true;
  selection.forEach((item) => {
    if (chooseId.value.indexOf(item.id) === -1)
      chooseId.value.push(item.id);
    // 只要有一个item.isHide === false 说明多选的这些选项不是全都隐藏/失效，不用变成“取消隐藏”/全部生效
    // if (item.isHide === false) cancelHideFlag.value = false;
  });
  chooseNum.value = selection.length;
  showActionBar.value = chooseNum.value > 0 ? true : false;
};
// 取消多选
const handleSelectNone = () => {
  chooseId.value = [];
  chooseNum.value = 0;
  alertTableRef.value?.clearAll();
  showActionBar.value = false;
};

// 全部隐藏
const handleHideAll = () => {
  if (showActionBar.value) isActiveHide.value = !isActiveHide.value;
  const updateList = {
    id: chooseId.value,
    isHide: true,
  };
  updateShowTableData(updateList).then(() => {
    handleSelectNone();
    getTableData();
    ElMessage({
      message: '操作成功',
      type: 'success',
    });
    setTimeout(function () {
      isActiveHide.value = !isActiveHide.value;
    }, 1000);
  });
};

// 取消隐藏
const handleCancelHideAll = () => {
  if (showActionBar.value) isActiveCancelHide.value = !isActiveCancelHide.value;
  const updateList = {
    id: chooseId.value,
    isHide: false,
  };
  updateShowTableData(updateList).then(() => {
    handleSelectNone();
    getTableData();
    ElMessage({
      message: '操作成功',
      type: 'success',
    });
    setTimeout(function () {
      isActiveCancelHide.value = !isActiveCancelHide.value;
    }, 1000);
  });
};

// 批量删除
const handleDeleteAll = () => {
  if (showActionBar.value) isActiveDelete.value = !isActiveDelete.value;
  ElMessageBox.confirm(
    '删除之后，数据无法恢复',
    '请确认是否删除数据',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'deleteMessage',
      center: true
    }
  )
    .then(() => {
      deleteShowTableData(chooseId.value).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        getTableData();
        handleSelectNone();
        isActiveDelete.value = !isActiveDelete.value;
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
      isActiveDelete.value = !isActiveDelete.value;
    })
};

// 详情
const closeDetailDialog = () => {
  isDetailDialogShow.value = false;
};
const handleDetail = (row) => {
  isDetailDialogShow.value = true;
  detailDescription.value = row.description;
  detailPictures.value = row.pictures;
  detailVideos.value = row.videos;
};

// 添加
const handleAdd = () => {
  isAddDrawer.value = true;
}
// 编辑
const handleEdit = (row) => {
  isEditDrawer.value = true;
  rowData.value = { ...row };
};

const handleAddDrawerClose = () => {
  isAddDrawer.value = false;
  getTableData();
};

const handleEditDrawerClose = () => {
  isEditDrawer.value = false;
  getTableData();
};

// 单个显示hide=false/隐藏hide=true
const handleShow = (row) => {
  const tempHide = row.isHide === false ? true : false;
  const updateList = {
    id: [row.id],
    isHide: tempHide,
  };
  updateShowTableData(updateList).then(() => {
    getTableData();
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '删除之后，数据无法恢复',
    '请确认是否删除数据',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'deleteMessage',
      center: true
    }
  )
    .then(() => {
      deleteShowTableData([row.id]).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        getTableData();
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
};

// 换页，重新获取表格
const handlePageChange = (val) => {
  query.value.pageNumber = val;
  getTableData();
};
const handleSizeChange = (val) => {
  query.value.pageSize = val;
  getTableData();
};

const getTableData = () => {
  getShowTableData(query.value).then((res) => {
    console.log(res);
    tableData.value = res.records;
    total.value = res.totalRow;
  });
};

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

onBeforeMount(() => {
  getAIOptions();
  getManualOptions();
  getLocationOptions();
});
</script>

<style scoped lang="scss">
.box {
  display: flex;
  flex-direction: column;
}

.search-form {
  margin-bottom: 20px;
}

.table-list {
  height: calc(100vh - 350px);
  overflow-y: scroll;

  .action-bar {
    display: flex;
    align-items: center;
    position: absolute;
    min-width: calc(100vw - 266px);
    height: 50px;
    border-radius: 4px 4px 0px 0px;
    background-color: #DDEFFF;
    z-index: 10;

    .num-text {
      margin: 0 34px 0 25px;
      color: rgba(0, 0, 0, 0.85);
      font-weight: 500;
    }

    .btn-normal {
      color: #1890FF;
      background: transparent;
      border: 1px solid #1890FF;
      border-radius: 2px;
    }

    .btn-active {
      color: #FFFFFF;
      background-color: #1890FF;
    }

    .close-btn {
      margin-left: auto;
      margin-right: 20px;
    }

    .close-btn:before {
      content: '\2716';
      color: #000;
      cursor: pointer;
    }
  }

  .table-bar {
    position: relative;
  }
}

.pagination-box {
  height: 50px;
  margin-top: 10px;
}
</style>