<template>
  <div class="registration-list page-container">
    <van-nav-bar
      title="登记列表"
      left-text=""
      fixed
      placeholder
      @click-left="onBack"
    />

    <van-pull-refresh
      v-model="refreshing"
      class="list-wrapper"
      @refresh="onRefresh"
    >
     <template #loading><div style="height:0"/></template>
      <van-list
        v-model="loading"
        :finished="finished"
        :loading-text="refreshing ? '' : '加载中...'"
        finished-text="没有更多了"
        @load="loadData"
      >
        <div v-for="item in list" :key="item.id" class="card-item">
          <div class="card-header">
            <div class="card-title">
              <div class="name">{{ item.customerName }}</div>
              <div class="time">{{ item.registerTime }}</div>
            </div>
            <van-tag :type="getStatusType(item.status)" class="status-tag">
              {{ item.status }}
            </van-tag>
          </div>

          <div class="card-body">
            <div class="info-row">
              <span class="label">联系方式</span>
              <span class="value">{{ item.contact || '-' }}</span>
            </div>
            <template v-if="isLocked(item)">
              <div class="info-row">
                <span class="label">服务类型</span>
                <span class="value">{{ item.serviceType || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">电源类型</span>
                <span class="value">{{ item.powerType || '-' }}</span>
              </div>
              <div class="info-row">
                <span class="label">备注</span>
                <span class="value">{{ item.note || '-' }}</span>
              </div>
            </template>
            <template v-else>
              <van-field
                v-model.trim="item.serviceType"
                label="服务类型"
                placeholder="请选择服务类型"
                input-align="right"
                is-link
                border
                class="editable-field"
                @click="openPicker(item, 'serviceType')"
              />
              <van-field
                v-model.trim="item.powerType"
                label="电源类型"
                placeholder="请选择电源类型"
                input-align="right"
                is-link
                border
                class="editable-field"
                @click="openPicker(item, 'powerType')"
              />
              <van-field
                v-model.trim="item.note"
                type="textarea"
                label="备注"
                placeholder="请输入备注"
                autosize
                border
                class="editable-field"
              />
            </template>
          </div>

          <div class="card-actions" v-if="!isLocked(item)">
            <van-button
              type="primary"
              size="small"
              round
              class="submit-btn"
              @click="submitItem(item)"
            >
              登记完成
            </van-button>
          </div>
        </div>

        <van-empty v-if="!loading && list.length === 0" description="暂无登记记录" />
      </van-list>
    </van-pull-refresh>

    <van-popup v-model="showPicker" position="bottom" round>
      <van-picker
        show-toolbar
        :columns="pickerColumns"
        @confirm="onPickerConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { getRegistrations, updateRegistration } from '@/api/registration'
import { Toast,Dialog } from 'vant';


export default {
  name: 'RegistrationList',
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: true,
      showPicker: false,
      pickerColumns: [],
      currentItem: null,
      currentField: '',
      serviceOptions: ['安装', '维修', '咨询'],
      powerOptions: ['市电', '锂电', '其他']
    }
  },
  methods: {
    onBack() {
      if (window.history.length > 1) {
        this.$router.back()
      } else {
        this.$router.push('/')
      }
    },
    async loadData() {
      try {
        const data = await getRegistrations()
        this.list = data
        setTimeout(()=>{
          this.finished = true
        },500)
      } catch (error) {
        this.$toast.fail('加载失败')
        console.error(error)
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    async onRefresh() {
      this.finished = false
      this.list = []
      await this.loadData()
    },
    getStatusType(status) {
      const map = {
        '已登记': 'success',
        '待登记': 'primary',
        '处理中': 'primary',
        '已完成': 'success',
        '已取消': 'default'
      }
      return map[status] || 'warning'
    },
    isLocked(item = {}) {
      return item.status === '已登记'
    },
    async submitItem(item) {
      try {
        const confirmed = await Dialog.confirm({
          title: '确认提交',
          message: '提交后将锁定该记录，是否继续？'
        }).then(() => true).catch(() => false)
        if (!confirmed) return

        Toast.loading()
        item.status = '已登记'
        const success = await updateRegistration(item.id, item)
        Toast.clear()
        if (success) {
          this.$toast.success('提交成功')
        } else {
          this.$toast.fail('提交失败')
        }
      } catch (error) {
        this.$toast.fail('提交失败')
        console.error(error)
      }
    },
    openPicker(item, field) {
      if (this.isLocked(item)) return
      this.currentItem = item
      this.currentField = field
      this.pickerColumns = field === 'serviceType' ? this.serviceOptions : this.powerOptions
      this.showPicker = true
    },
    onPickerConfirm(value) {
      if (this.isLocked(this.currentItem)) {
        this.showPicker = false
        return
      }
      if (this.currentItem && this.currentField) {
        this.$set(this.currentItem, this.currentField, value)
      }
      this.showPicker = false
    }
  }
}
</script>

<style scoped>
.registration-list {
  background: #f7f8fa;
  min-height: 100vh;
  padding-top: 16px;
  padding-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.list-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 12px;
  box-sizing: border-box;
}

.card-item {
  margin-top: 12px;
  padding: 14px 14px 10px;
  border-radius: 14px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  background: #fff;
}

.card-item:first-of-type {
  margin-top: 0;
}

.card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
}

.card-title {
  flex: 1;
}

.name {
  font-size: 16px;
  font-weight: 700;
  color: #303133;
  line-height: 1.3;
}

.time {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.status-tag {
  border-radius: 12px;
  padding: 3px 12px;
  font-size: 12px;
}

.card-body {
  margin-top: 12px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
  display: grid;
  gap: 6px;
}

.card-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  padding: 0 18px;
  width: 100%;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #303133;
}

.label {
  color: #909399;
}

.value {
  max-width: 70%;
  text-align: right;
  word-break: break-all;
}
.info-row{
  padding: 6px 0;
}
:deep(.editable-field){
  padding: 6px 0;
}

:deep(.editable-field .van-field__control) {
  font-size: 14px;
  color: #303133;
  padding: 0 !important;
}

:deep(.editable-field .van-field__control--textarea) {
  min-height: 80px;
  line-height: 1.6;
  padding: 10px 12px !important;
  background: #f2f3f5;
  border: 1px solid #e6e8eb;
  border-radius: 10px;
}

:deep(.editable-field .van-field__body) {
  align-items: flex-start;
}

:deep(.editable-field .van-field__control::placeholder) {
  color: #c0c4cc;
}

:deep(.editable-field .van-field__label) {
  color: #909399;
}

:deep(.editable-field .van-field__right-icon) {
  color: #c0c4cc;
}
</style>
