<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed
      statusBar
      left-icon="back"
      :title="navTitle"
      @clickLeft="back"
    />

    <!-- 搜索区域 -->
    <view class="top-wrapper">
      <input class="search-input" v-model="searchName" placeholder="演练名称" />
      <!--      <view class="dept-btn" @click="showDeptPicker">
        <text>{{ deptName || '主管部门' }}</text>
        <text class="arrow">▾</text>
      </view> -->
      <button class="search_btn" @click="handleSearch">搜索</button>
    </view>

    <!-- 列表 -->
    <view class="wrapper">
      <u-list @scrolltolower="scrolltolower" class="listContent">
        <view
          v-for="(item, idx) in listData"
          :key="item.id"
          style="position: relative"
        >
          <myCard
            :item="item"
            :index="idx + 1"
            :btnList="getBtnList(item)"
            :columns="cardColumns"
            :title="item.name"
            :status="getStatusLabel(item.status)"
            @goDetail="goDetail"
            @handleReport="handleReport(item)"
            @handleAcceptance="handleAcceptance(item)"
          />
        </view>
        <view style="width: 100%; height: 40rpx"></view>
        <view style="margin-top: 20vh" v-if="!loading && listData.length == 0">
          <u-empty iconSize="150" textSize="32" text="暂无数据" />
        </view>
        <view v-if="loading" class="load-more">加载中...</view>
        <view v-if="isEnd && listData.length > 0" class="load-more"
          >没有更多了</view
        >
      </u-list>
    </view>

    <!-- 新增按钮 -->
    <!-- <view class="add" @click="handleAdd">
      <u-icon name="plus" color="#fff"></u-icon>
    </view> -->

    <!-- 弹窗 -->
    <workOrderDialog ref="dialogRef" @reload="reloadList" />
    <workOrderReportDialog ref="reportRef" @reload="reloadList" />
    <workOrderReportAcceptanceDialog ref="acceptanceRef" @reload="reloadList" />

    <!-- 部门选择器 -->
    <ba-tree-picker
      ref="treePicker"
      key="dept"
      :multiple="false"
      @select-change="onDeptConfirm"
      title="选择部门"
      :localdata="deptList"
      valueKey="id"
      textKey="name"
    />

    <u-toast ref="uToast" />
  </view>
</template>

<script>
import myCard from "@/components/myCard.vue";
import workOrderDialog from "./workOrderDialog.vue";
import workOrderReportDialog from "./workOrderReportDialog.vue";
import workOrderReportAcceptanceDialog from "./workOrderReportAcceptanceDialog.vue";
import { getList } from "@/api/emergencyDrill/workOrder.js";
import dictMixns from "@/mixins/dictMixins";

export default {
  mixins: [dictMixns],

  components: {
    myCard,
    workOrderDialog,
    workOrderReportDialog,
    workOrderReportAcceptanceDialog,
  },
  data() {
    return {
      searchName: "",
      deptId: null,
      deptName: "主管部门",
      deptList: [],
      listData: [],
      page: 1,
      size: 10,
      isEnd: false,
      loading: false,
      cardColumns: [
        [{ prop: "code", label: "编码", className: "perce100" }],
        [
          {
            prop: "drillType",
            label: "演练类型",
            className: "perce50",
            formatter: (row) => {
              return (
                this.getDictValue("应急演练类型", row.drillType)
              );
            },
          },
        ],
        [
          {
            prop: "superviseDeptName",
            label: "主管部门",
            className: "perce100",
          },
        ],
        [{ prop: "planLocation", label: "演练地点", className: "perce100" }],
        [
          {
            prop: "emergencyPlanName",
            label: "应急预案",
            className: "perce100",
          },
        ],
        [
          {
            label: "操作",
            prop: "action",
            type: "action",
            className: "perce100",
          },
        ],
      ],
    };
  },
  computed: {
    navTitle() {
      return "应急演练工单";
    },
  },
  onLoad() {
    this.getList();
    this.requestDict('应急演练类型')
  },
  methods: {
    // 部门选择
    showDeptPicker() {
      this.$refs.treePicker._show();
    },
    onDeptConfirm(data) {
      const id = data[0];
      this.deptId = id;
      // 查找部门名称
      const findDept = (list) => {
        for (const item of list) {
          if (item.id === id) return item.name;
          if (item.children && item.children.length > 0) {
            const found = findDept(item.children);
            if (found) return found;
          }
        }
        return null;
      };
      this.deptName = findDept(this.deptList) || "主管部门";
      this.page = 1;
      this.isEnd = false;
      this.getList();
    },

    // 状态标签
    getStatusLabel(status) {
      const map = {
        0: "待演练",
        1: "待验收",
        2: "已完成",
      };
      return map[status] || status;
    },

    // 按钮列表
    getBtnList(item) {
      const btns = [];
      // 报工（待演练状态）
      if (item.status == 0) {
        btns.push({
          name: "报工",
          apiName: "handleReport",
          btnType: "primary",
          judge: [{ fn: () => true }],
        });
      }
      // 验收（待验收状态）
      if (item.status == 1) {
        btns.push({
          name: "验收",
          apiName: "handleAcceptance",
          btnType: "success",
          judge: [{ fn: () => true }],
        });
      }

      return btns;
    },

    // 列表操作
    goDetail(item) {
      this.$refs.dialogRef.open(item, "view");
    },
    handleAdd() {
      // 需要先选择演练计划，简化处理：打开弹窗后选择
      this.$refs.dialogRef.open(null, "add");
    },
    handleReport(item) {
      this.$refs.reportRef.open(item);
    },
    handleAcceptance(item) {
      this.$refs.acceptanceRef.open(item);
    },

    // 搜索
    handleSearch() {
      this.page = 1;
      this.isEnd = false;
      this.getList();
    },

    // 刷新列表
    reloadList() {
      this.page = 1;
      this.isEnd = false;
      this.getList();
    },

    // 加载数据
    async getList() {
      if (this.loading || this.isEnd) return;
      this.loading = true;
      try {
        const params = {
          pageNum: this.page,
          size: this.size,
          name: this.searchName || undefined,
        };
        const res = await getList(params);
        const list = res.list || [];
        if (this.page === 1) {
          this.listData = list;
        } else {
          this.listData = this.listData.concat(list);
        }
        this.isEnd =
          list.length < this.size || this.listData.length >= res.count;
        this.page += 1;
      } catch (e) {
        console.error("加载失败", e);
        this.$refs.uToast.show({ type: "error", message: "加载失败，请重试" });
      } finally {
        this.loading = false;
      }
    },

    scrolltolower() {
      if (!this.isEnd && !this.loading) {
        this.getList();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.mainBox {
  background-color: #f3f8fb;
  min-height: 100vh;
}

.top-wrapper {
  background: #fff;
  padding: 16rpx 24rpx;
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid #eee;
  gap: 12rpx;

  .search-input {
    flex: 1;
    height: 64rpx;
    border: 2rpx solid #e9edf2;
    border-radius: 48rpx;
    padding: 0 24rpx;
    font-size: 26rpx;
    background: #fafafa;
    min-width: 0;
  }

  .dept-btn {
    display: flex;
    align-items: center;
    height: 64rpx;
    padding: 0 20rpx;
    background: #e8edf4;
    border-radius: 48rpx;
    color: #2979ff;
    font-size: 24rpx;
    flex-shrink: 0;
    gap: 4rpx;
    .arrow {
      font-size: 18rpx;
    }
  }

  .search_btn {
    height: 64rpx;
    padding: 0 28rpx;
    background: $theme-color;
    font-size: 26rpx;
    color: #fff;
    border-radius: 48rpx;
    text-align: center;
    line-height: 64rpx;
    flex-shrink: 0;
  }
}

.wrapper {
  padding: 16rpx 24rpx;
}

.add {
  position: fixed;
  bottom: 100rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: $theme-color;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
  z-index: 999;
}

.load-more {
  text-align: center;
  font-size: 26rpx;
  color: #aaa;
  padding: 20rpx 0 40rpx;
}
</style>
