<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="keyword" placeholder="请输入隐患名称" />
      <button class="search_btn" @click="handleSearch">搜索</button>
    </view>

    <view class="wrapper">
      <u-list @scrolltolower="scrolltolower" class="listContent">
        <view v-for="(item, idx) in tableList" :key="item.id" style="position: relative">
          <myCard
            :item="item"
            :index="idx + 1"
            :btnList="getBtnList(item)"
            :columns="cardColumns"
            :title="item.title"
            :status="getStatusLabel(item.status)"
            @goDetail="goDetail"
            @edit="handleEdit(item)"
            @handleFix="handleFix(item)"
            @handleVerify="handleVerify(item)"
            @handleDelete="handleDelete(item)"
          />
        </view>
        <view style="width: 100%; height: 40rpx"></view>
        <view style="margin-top: 20vh" v-if="tableList.length == 0">
          <u-empty iconSize="150" textSize="32" text="暂无数据" />
        </view>
      </u-list>
    </view>

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

    <hazardDialog ref="hazardDialogRef" @reload="reloadList" />
  </view>
</template>

<script>
import myCard from '@/components/myCard.vue';
import hazardDialog from './hazardDialog.vue';
import { getList, remove, checkAcceptor, checkRectifier } from '@/api/hazardManagement/index.js';

export default {
  components: { myCard, hazardDialog },
  data() {
    return {
      keyword: '',
      tableList: [],
      page: 1,
      size: 10,
      isEnd: false,
      userInfo: {},
      cardColumns: [
        [{ prop: 'code', label: '隐患编号', className: 'perce100' }],
        [{ prop: 'deviceName', label: '设备名称', className: 'perce50' }, { prop: 'areaName', label: '区域', className: 'perce50' }],
        [{ prop: 'foundTime', label: '发现时间', className: 'perce100' }],
        [{ prop: 'fixUserName', label: '整改责任人', className: 'perce100' }],
        [{ prop: 'fixDeadline', label: '计划整改时限', className: 'perce100' }],
        [{ label: '操作', prop: 'action', type: 'action', className: 'perce100' }]
      ],
      statusOptions: [
        { value: 0, label: '待确认' },
        { value: 1, label: '待整改' },
        { value: 2, label: '整改中' },
        { value: 3, label: '待验收' },
        { value: 4, label: '已验收' },
        { value: 'CLOSED', label: '已关闭' }
      ]
    };
  },
  computed: {
    navTitle() { return '隐患管理'; }
  },
  created() {
    this.userInfo = uni.getStorageSync('userInfo') || {};
    this.getList();
  },
  methods: {
    back() { uni.navigateBack(); },

    // 按钮列表（根据状态动态生成）
    getBtnList(item) {
      const btns = [];
      if (this.canFix(item)) {
        btns.push({ name: '整改', apiName: 'handleFix', btnType: 'primary', judge: [{ fn: () => true }] });
      }
      if (this.canVerify(item)) {
        btns.push({ name: '验收', apiName: 'handleVerify', btnType: 'success', judge: [{ fn: () => true }] });
      }
      if (this.canEdit(item)) {
        btns.push({ name: '编辑', apiName: 'edit', btnType: 'primary', judge: [{ fn: () => true }] });
      }
      if (this.canDelete(item)) {
        btns.push({ name: '删除', apiName: 'handleDelete', btnType: 'danger', judge: [{ fn: () => true }] });
      }
      return btns;
    },

    canEdit(row) { return [0].includes(row.status); },
    canDelete(row) { return [0].includes(row.status); },
    canFix(row) { return [0, 1, 2].includes(row.status); },
    canVerify(row) { return [3].includes(row.status); },

    getStatusLabel(status) {
      const item = this.statusOptions.find(opt => opt.value == status);
      return item ? item.label : status;
    },

    // 列表操作
    goDetail(item) {
      this.$refs.hazardDialogRef.open('view', item);
    },
    handleAdd() {
      this.$refs.hazardDialogRef.open('add');
    },
    handleEdit(item) {
      this.$refs.hazardDialogRef.open('edit', item);
    },
    async handleFix(item) {
      try {
        const data = await checkRectifier(item.id);
        if (!data.isRectifier) {
          uni.showToast({ title: '您不是整改责任人', icon: 'none' });
          return;
        }
        this.$refs.hazardDialogRef.open('fix', item, 'fix');
      } catch (e) {
        console.error(e);
      }
    },
    async handleVerify(item) {
      try {
        const data = await checkAcceptor(item.id);
        if (!data.isAcceptor) {
          uni.showToast({ title: '您不是验收人', icon: 'none' });
          return;
        }
        this.$refs.hazardDialogRef.open('verify', item, 'verify');
      } catch (e) {
        console.error(e);
      }
    },
    async handleDelete(item) {
      const res = await uni.showModal({
        title: '提示',
        content: `确认删除隐患「${item.title}」吗？`
      });
      if (res.confirm) {
        try {
          await remove([item.id]);
          uni.showToast({ title: '删除成功', icon: 'success' });
          this.reloadList();
        } catch (e) {
          console.error(e);
        }
      }
    },

    // 数据加载
    reloadList() {
      this.page = 1;
      this.isEnd = false;
      this.getList();
    },
    handleSearch() {
      this.page = 1;
      this.isEnd = false;
      this.getList();
    },
    async getList() {
      if (this.isEnd) return;
      uni.showLoading({ title: '加载中' });
      try {
        const params = {
          pageNum: this.page,
          size: this.size,
          title: this.keyword || undefined
        };
        const res = await getList(params);
        const list = res.list || [];
        if (this.page === 1) this.tableList = list;
        else this.tableList.push(...list);
        this.isEnd = list.length < this.size || this.tableList.length >= res.count;
        this.page += 1;
      } catch (e) {
        console.error(e);
      } finally {
        uni.hideLoading();
      }
    },
    scrolltolower() {
      if (!this.isEnd) this.getList();
    }
  }
};
</script>

<style lang="scss" scoped>
	@import "../common-style.scss";

.top-wrapper {
  background: #fff;
  padding: 20rpx 32rpx;
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid #eee;
  .search-input {
    flex: 1;
    height: 70rpx;
    border: 2rpx solid #e9edf2;
    border-radius: 48rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    background: #fafafa;
  }
  .search_btn {
    width: 140rpx;
    height: 70rpx;
    line-height: 70rpx;
    background: $theme-color;
    font-size: 28rpx;
    color: #fff;
    margin-left: 20rpx;
    border-radius: 48rpx;
    text-align: center;
  }
}

</style>