<template>
  <view class="page-container">
    <!-- 顶部固定区域 -->
    <up-sticky>
      <view class="header-wrap">
        <!-- 第一行：养护单位、工单进度、日期范围选择器 -->
        <view class="top-select-row">
          <up-select
            v-model:current="workerCompanyId"
            :options="deptOptions"
            :showOptionsLabel="true"
            @select="handleFilterChange"
            border="surround"
            placeholder="养护单位"
            class="select-item company-select"
          />
          <up-select
            v-model:current="status"
            :options="statusOptions"
            :showOptionsLabel="true"
            @select="handleFilterChange"
            border="surround"
            placeholder="工单进度"
            class="select-item status-select"
          />
          <!-- 替换为 neo-datetime-pro 日期范围选择器 -->
          <view class="date-picker-box select-item date-picker-full">
            <neo-datetime-pro
              v-model="dateRange"
              type="daterange"
              :clearable="false"
              placeholder="请选择日期范围"
              @confirm="handleDateConfirm"
              :max-date="maxDate"
              @popup-show="handlePopupShow"
              @popup-hide="handlePopupHide"
            />
          </view>
        </view>

        <!-- 第二行：原有 位置下拉 + 搜索框 保持不变 -->
        <view class="search-header">
          <view class="select-wrap common-text-color">
            <up-select
              v-model:current="selectedSortValue"
              :options="sortOptions"
              :showOptionsLabel="true"
              @select="handleSortChange"
              border="surround"
              :style="{ flex: 1 }"
            />
          </view>
          <view class="search-input-wrap">
            <up-search
              v-model="searchValue"
              placeholder="请输入关键字"
              @search="handleSearch"
              bg-color="#f5f5f5"
              :clearabled="false"
              :show-action="true"
              actionText="搜索"
              :animation="true"
              @custom="handleSearch"
            />
          </view>
        </view>
      </view>
    </up-sticky>

   <!-- 新增：筛选结果统计栏（黄色背景） -->
<view class="total-tip-wrap" v-if="total > 0">
  <view class="total-tip">
    共筛选出 {{ total }} 条记录
  </view>
</view>

    <!-- 列表容器 -->
    <z-paging
      ref="pagingRef"
      v-model="orderList"
      @query="queryList"
      :auto-show-system-loading="true"
    >
      <template #empty>
        <empty-view />
      </template>

      <view class="common-card-list">
        <up-card
          :border="false"
          :foot-border-top="false"
          v-for="(item, index) in orderList"
          @click="handleDetail(item)"
          :key="item.id || index"
          :show-head="false"
          class="order-card"
        >
          <template #body>
            <view class="card-body">
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">工单编号：</view>
                <view class="u-line-1 u-body-value">{{ item.orderNo || '-' }}</view>
              </view>
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">工单位置：</view>
                <view class="u-line-1 u-body-value">{{ item.lonLatAddress || '-' }}</view>
              </view>
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">问题类型：</view>
                <view class="u-line-1 u-body-value">{{ item.orderName || '未填写' }}</view>
              </view>
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">情况描述：</view>
                <view class="u-line-1 u-body-value">{{ item.remark || '无' }}</view>
              </view>

              <!-- 紧急程度 + 工单详情小按钮 同行布局 -->
              <view class="u-body-item u-flex common-justify-between common-item-center">
                <view class="u-body-item-title">
                  紧急程度：{{ uni.$dict.getDictLabel('workorder_pressing_type', item.pressingType) || '-' }}
                </view>
                <!-- 改为 mini 迷你按钮，自适应内容宽度 -->
                <up-button type="primary" size="mini" class="detail-btn" >工单详情</up-button>
              </view>

              <view class="u-body-item u-flex">
                <view class="u-body-item-title">工单状态：</view>
                <view class="u-line-1 u-body-value">{{ buzStatusMap[item.buzStatus] || '-' }}</view>
              </view>
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">提交时间：</view>
                <view class="u-line-1 u-body-value">{{ item.createTime ? timeFormat(item.createTime, 'yyyy-mm-dd hh:MM:ss') : '-' }}</view>
              </view>
            </view>
          </template>
        </up-card>
      </view>
    </z-paging>

    <!-- 回退原因弹窗 -->
    <up-modal
      :show="rejectModalShow"
      title="回退原因"
      :closeOnClickOverlay="false"
      :showConfirmButton="true"
      :showCancelButton="true"
      @cancel="handleRejectModalCancel"
      @confirm="confirmReject"
    >
      <view class="reject-modal-content">
        <up-textarea
          v-model.trim="rejectReason"
          placeholder="请输入回退原因（必填）"
          rows="6"
          :count="200"
          maxlength="200"
          class="reject-textarea"
        />
        <view class="upload-wrap mt-20">
          <view class="upload-title">上传图片（选填）</view>
          <up-upload
            :file-list="rejectImgs.rawImgList.value || []"
            @after-read="rejectImgs.uploadImgs"
            @delete="rejectImgs.deleteImg"
            multiple
            width="70"
            height="70"
            :max-count="rejectImgs.uploadConfig.maxCount"
            :upload-text="rejectImgs.uploadText"
            :size-type="rejectImgs.uploadConfig.sizeType"
          />
        </view>
      </view>
    </up-modal>

    <!-- 验收弹窗 -->
    <up-modal
      :show="acceptModalShow"
      title="验收"
      :closeOnClickOverlay="false"
      :showConfirmButton="true"
      :showCancelButton="true"
      @cancel="handleAcceptModalCancel"
      @confirm="handleAcceptModalConfirm"
    >
      <view class="accept-modal-content">
        <view class="radio-group-wrap">
          <up-radio-group v-model="acceptRadioValue">
            <up-radio name="0" label="通过"></up-radio>
            <up-radio name="1" label="不通过"></up-radio>
          </up-radio-group>
        </view>
        <view class="textarea-wrap mt-30">
          <up-textarea
            v-model.trim="acceptReason"
            placeholder="请输入验收原因（必填，最多200字）"
            :required="true"
            maxlength="200"
            rows="5"
            count
          />
        </view>
        <view class="upload-wrap mt-20">
          <view class="upload-title">上传验收图片（选填）</view>
          <up-upload
            :file-list="acceptImgs.rawImgList.value || []"
            @after-read="acceptImgs.uploadImgs"
            @delete="acceptImgs.deleteImg"
            multiple
            width="70"
            height="70"
            :max-count="acceptImgs.uploadConfig.maxCount"
            :upload-text="acceptImgs.uploadText"
            :size-type="acceptImgs.uploadConfig.sizeType"
          />
        </view>
      </view>
    </up-modal>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { timeFormat } from '@/uni_modules/uview-plus';
// 接口引入
import { workorderPage } from '@/api/regional-order-manage/regional-order-manage'
import { getAllCompanyList } from '@/api/common'
import { useUserStore } from '@/pinia/user';
import { nextStepMap, buzStatusMap } from '@/common/utils/common'
import { useUploadImgs } from '@/common/utils/useUploadImgs'

// 全局状态
const userStore = useUserStore();
const USER_ROLES = userStore.userInfo?.roles || [];

// 新增：总条数
const total = ref(0);
  const queryType = ref(0);
// 日期范围
const dateRange = ref([]);
const maxDate = ref('');
const isDatePickerOpen = ref(false);
let beginTime = ''
let endTime = ''

// 缓存上一页参数
let cacheCompanyId = ''
let cacheCompanyName = ''

// 筛选条件
const workerCompanyId = ref('');
const deptOptions = ref([{ name: '全部', id: '' }]);

const status = ref('');
const statusOptions = ref([
  { name: '全部', id: '' },
  { name: '进行中', id: '1' },
  { name: '已完成', id: '2' }
]);

const selectedSortValue = ref(1);
const sortOptions = ref([
  { name: '位置', id: 1 },
  { name: '名称', id: 2 },
  { name: '描述', id: 3 },
  { name: '编号', id: 4 },
]);
const searchValue = ref('');


// 分页
const pagingRef = ref(null);
const orderList = ref([]);

const isAi = computed(() => {
  const roles = USER_ROLES || [];
  return !roles.includes('AI_dispatcher');
});

// 弹窗
const rejectModalShow = ref(false);
const rejectReason = ref('');
const currentRejectItem = ref(null);
const rejectImgs = useUploadImgs({
  maxCount: 3, uploadText: '选择回退图片', sizeType: ['compressed'], formRef: null, fieldName: 'rejectImgs'
})

const acceptModalShow = ref(false);
const acceptRadioValue = ref('0');
const acceptReason = ref('');
const currentAcceptItem = ref(null);
const acceptImgs = useUploadImgs({
  maxCount: 3, uploadText: '选择验收图片', sizeType: ['compressed'], formRef: null, fieldName: 'acceptImgs'
})

// 公共方法
const showToast = (title, icon = 'none', duration = 2000) => {
  uni.showToast({ title, icon, duration });
};

const pagingHandle = (method, ...args) => {
  const paging = pagingRef.value;
  if (paging && typeof paging[method] === 'function') {
    paging[method](...args);
  }
};

// ========== 已新增：type(位置排序)、searchContent(搜索内容) ==========
const getQueryParams = (pageNo, pageSize) => {
  return {
    queryType: queryType.value,
    workerCompanyId: workerCompanyId.value,
    status: status.value,
    beginTime,
    endTime,
    type: selectedSortValue.value,      // 位置/排序类型
    searchContent: searchValue.value,   // 搜索关键字
    pageNo,
    pageSize
  };
};

const navToOrderPage = (path, query = {}, events = {}) => {
  const queryStr = Object.entries(query)
    .map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`)
    .join('&');
  const url = `${path}${queryStr ? '?' + queryStr : ''}`;
  if (Object.keys(events).length) {
    uni.navigateTo({ url, events });
  } else {
    uni.redirectTo({ url });
  }
};

const refreshOrderList = () => pagingHandle('reload');

// 日期选择器
const handlePopupShow = () => {
  isDatePickerOpen.value = true;
};
const handlePopupHide = () => {
  isDatePickerOpen.value = false;
};
const handleDateConfirm = (val) => {
  dateRange.value = val;
  beginTime = val[0] || '';
  endTime = val[1] || '';
  refreshOrderList();
};

/**
 * 获取养护单位列表
 */
const getCompanyData = async () => {
  try {
    const res = await getAllCompanyList();
    const list = Array.isArray(res) ? res : (res?.list || []);
    const tempList = [{ name: '全部', id: '' }];
    list.forEach(item => {
      tempList.push({
        name: item.companyName || item.name,
        id: item.companyId || item.id
      });
    });

    // 合并临时传入项，保证名称一定存在
    if (cacheCompanyId && cacheCompanyName) {
      const hasExist = tempList.some(item => item.id === cacheCompanyId);
      if (!hasExist) {
        tempList.push({
          id: cacheCompanyId,
          name: cacheCompanyName
        });
      }
    }

    deptOptions.value = tempList;

    // 赋值选中ID，nextTick 确保DOM更新
    if (cacheCompanyId) {
      await nextTick();
      workerCompanyId.value = cacheCompanyId;
    }
  } catch (err) {
    console.error('加载养护单位失败：', err);
    showToast('养护单位加载失败');
  }
};

// 列表查询
const queryList = async (pageNo, pageSize) => {
  try {
    const params = getQueryParams(pageNo, pageSize);
    const res = await workorderPage(params);
    // 赋值总条数
    total.value = res?.total || 0;
    pagingHandle('complete', res?.list || [], res?.total || 0);
  } catch (error) {
    console.error('加载工单失败：', error);
    pagingHandle('complete', false);
    showToast('加载失败，请重试');
  }
};

// 筛选事件
const handleFilterChange = () => refreshOrderList();
const handleSortChange = (val) => {
  selectedSortValue.value = val.id;
  searchValue.value = '';
  refreshOrderList();
};
const handleSearch = (val) => {
  searchValue.value = val;
  refreshOrderList();
};
const handleDetail = (item) => {
  uni.navigateTo({
    url: `/pages-sub/problem/regional-order-manage/list-detail?id=${item.id}&processInstanceId=${item.processInstanceId}`
  })
};

// 弹窗事件
const handleRejectModalCancel = () => {
  rejectModalShow.value = false;
  rejectReason.value = '';
  rejectImgs.clearImgs();
};
const confirmReject = async () => {
  const reason = rejectReason.value.trim();
  if (!reason) return showToast('请填写回退原因');
  showToast('操作成功', 'success');
  handleRejectModalCancel();
  refreshOrderList();
};
const handleAcceptModalCancel = () => {
  acceptModalShow.value = false;
  acceptReason.value = '';
  acceptRadioValue.value = '0';
  acceptImgs.clearImgs();
};
const handleAcceptModalConfirm = async () => {
  const reason = acceptReason.value.trim();
  if (!reason) return showToast('请填写验收原因');
  showToast('提交成功', 'success');
  handleAcceptModalCancel();
  refreshOrderList();
};

// 生命周期
onLoad((options) => {
  // 接收上一页参数
  cacheCompanyId = options?.companyId || ''
  cacheCompanyName = options?.companyName || ''
  console.log('options.queryType:'+options.queryType)
    queryType.value= options.queryType == 0? 1:0
    console.log('options.queryType:'+queryType.value)
  // 初始化最大日期
  maxDate.value = timeFormat(new Date(), 'yyyy-mm-dd');

  // 时间范围
  const routeBegin = options?.beginTime || '';
  const routeEnd = options?.endTime || '';
  if (routeBegin && routeEnd) {
    dateRange.value = [routeBegin, routeEnd];
    beginTime = routeBegin;
    endTime = routeEnd;
  }
});

// 改用 onMounted，只执行一次，避免 onShow 重复刷新覆盖
onMounted(async () => {
  await getCompanyData();
  refreshOrderList();
});
</script>

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

.header-wrap {
  background-color: #fff;
  padding: 10rpx;
  box-sizing: border-box;
}

/* 新增外层占位 + 吸顶容器 */
.total-tip-wrap {
  height: auto;
  /* 占位高度和实际标签一致，防止列表突然上移 */
  .total-tip {
    position: fixed;
    top: calc(var(--status-bar-height) + 100rpx); /* 对应顶部sticky高度，自行微调 */
    left: 0;
    right: 0;
    z-index: 99; /* 高于列表，防止被遮挡 */
    background: #e4dc8e;
    color: #333;
    font-size: 26rpx;
    padding: 14rpx 20rpx;
    text-align: center;
  }
}

/* 列表顶部留出吸顶栏高度，避免内容被遮挡 */
.common-card-list {
  /* 原有样式保留，追加顶部内边距 */
  padding: calc(var(--status-bar-height) + 100rpx + 44rpx) 0 30rpx;
  box-sizing: border-box;
}


/* 第一行筛选布局 */
.top-select-row {
  display: flex;
  gap: 15rpx;
  margin-bottom: 15rpx;
  .select-item {
    :deep(.u-select__content .u-select__text) {
      margin-right: 2px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis; /* 补充省略号 */
    }
    :deep(.u-select),
    :deep(.neo-datetime-pro) {
      width: 100%;
      font-size: 28rpx;
      box-sizing: border-box;
    }
  }
  /* 养护单位 固定宽，不被内容撑开 */
  .company-select {
    flex: 0 0 140rpx;
    width: 140rpx;
  }
  /* 工单进度 固定宽，不被内容撑开 */
  .status-select {
    flex: 0 0 120rpx;
    width: 120rpx;
  }
  .date-picker-full {
    flex: 1;
  }
}

/* 第二行：排序 + 搜索 */
.search-header {
  display: flex;
  align-items: center;
  box-sizing: border-box;
  .select-wrap {
    width: 120rpx;
    margin-right: 20rpx;
    :deep(.u-select), :deep(.u-input__placeholder) {
      width: 100%;
      font-size: 28rpx;
    }
  }
  .search-input-wrap {
    flex: 1;
  }
}

.common-card-list {
  padding: calc(var(--status-bar-height) + 160rpx) 0 30rpx;
  box-sizing: border-box;
}

.order-card {
  margin: 0 20rpx 20rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

/* 工单详情按钮 贴最右侧 */
.detail-btn {
  width: auto !important;
  padding: 0 16rpx !important;
  margin-left: auto;
}

.reject-modal-content, .accept-modal-content {
  width: 100%;
  box-sizing: border-box;
  padding: 10rpx 0;
}

.upload-wrap {
  .upload-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
  }
}

.radio-group-wrap {
  display: flex;
  align-items: center;
  gap: 40rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.textarea-wrap {
  width: 100%;
}

.mt-20 { margin-top: 20rpx; }
.mt-30 { margin-top: 30rpx; }
</style>