<template>
  <div class="wrap">
    <van-nav-bar
      title="供应商时段电话"
      left-arrow
      @click-left="onNavBack"
      fixed
      placeholder
      class="nav-bar"
    />

    <div class="content">
      <!-- 审批状态提示条 -->
      <div v-if="inApproval" class="status-tip status-tip--pending">
        服务商-电话时段变更审核中
      </div>
      <div v-else-if="rejected" class="status-tip status-tip--danger">
        <div class="status-tip__title">审批被驳回</div>
        <div v-if="approvalRemark" class="status-tip__desc">{{ approvalRemark }}</div>
      </div>

      <!-- 空态 -->
      <div v-if="!phoneList.length" class="empty-wrap">
        <div class="empty-text">暂无分时段电话，点击新增时段电话</div>
      </div>

      <!-- 时段卡片列表 -->
      <div v-else class="card-list">
        <div v-for="(item, index) in phoneList" :key="index" class="time-card" @click="goEdit(index)">
          <div class="card-head">
            <span class="period">{{ item.startTime }} — {{ item.endTime }}</span>
            <div class="ops" @click.stop v-if="!inApproval">
              <span class="op-edit" @click="goEdit(index)">编辑</span>
              <span class="op-del" @click="deleteItem(index)">删除</span>
            </div>
          </div>
          <div class="divider"></div>
          <div class="phone-rows">
            <div v-for="phone in visiblePhones(item)" :key="phone.index" class="phone-row">
              <span class="phone-icon">☎</span>
              <span class="phone-num">{{ phone.num }}</span>
              <span v-if="phone.desc" class="tag">{{ phone.desc }}</span>
              <span v-if="phone.wx" class="tag tag-wx">微:{{ phone.wx }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="footer">
      <button v-if="!inApproval" class="btn btn-add" @click="goAdd">＋ 新增时段</button>
      <button
        class="btn btn-submit"
        :disabled="inApproval || !phoneList.length"
        @click="onSubmitClick"
      >
        {{ inApproval ? '审核中' : '提交审批' }}
      </button>
    </div>
  </div>
</template>

<script>
import { getSupplierPhoneList, submitSupplierPhoneApproval } from '@/api/supplierPhone'
import { myMixins } from '@/utils/myMixins'
import { Dialog, Toast } from 'vant'

const DRAFT_KEY_PREFIX = 'supplierTimePhoneDraft_'

function getSupplierIdFromToken() {
  const token = localStorage.getItem('token')
  if (!token) return null
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    return payload.supplierId || null
  } catch (e) {
    return null
  }
}

function getDraftKey(supplierId) {
  return `${DRAFT_KEY_PREFIX}${supplierId}`
}

export default {
  name: 'supplierTimePhone',
  mixins: [myMixins],
  data() {
    return {
      supplierId: null,
      supplierName: '',
      approvalId: null,
      approvalState: null,
      approvalStateName: '',
      inApproval: false,
      rejected: false,
      approvalRemark: '',
      phoneList: []
    }
  },
  mounted() {
    this.supplierId = this.$route.query.supplierId || getSupplierIdFromToken()
    if (!this.supplierId) {
      Toast('未获取到服务商信息')
      return
    }
    this.loadData()
  },
  methods: {
    async loadData() {
      Toast.loading({ message: '加载中...', forbidClick: true, duration: 0 })
      try {
        const result = await getSupplierPhoneList({ supplierId: this.supplierId })
        const res=result?.data || ''
        this.supplierName = res?.supplierName || ''
        this.approvalId = res?.approvalId || null
        this.approvalState = res?.approvalState || null
        this.approvalStateName = res?.approvalStateName || ''
        this.inApproval = !!res?.inApproval
        this.rejected = !!res?.rejected
        this.approvalRemark = res?.approvalRemark || ''

        const cached = this.getCachedDraft()
        if (cached && Array.isArray(cached.phoneList)) {
          this.phoneList = cached.phoneList
        } else {
          this.phoneList = res?.phoneList || []
          this.saveDraft()
        }
      } catch (e) {
        console.error(e)
      } finally {
        Toast.clear()
      }
    },
    visiblePhones(item) {
      const list = []
      for (let i = 1; i <= 3; i++) {
        const num = item['phone' + i]
        if (num) {
          list.push({
            index: i,
            num,
            desc: item['phone' + i + 'Desc'],
            wx: item['phone' + i + 'WechatId']
          })
        }
      }
      return list
    },
    getCachedDraft() {
      try {
        const raw = localStorage.getItem(getDraftKey(this.supplierId))
        return raw ? JSON.parse(raw) : null
      } catch (e) {
        return null
      }
    },
    saveDraft() {
      const draft = {
        approvalId: this.approvalId,
        approvalState: this.approvalState,
        phoneList: this.phoneList
      }
      localStorage.setItem(getDraftKey(this.supplierId), JSON.stringify(draft))
    },
    onNavBack() {
      localStorage.removeItem(getDraftKey(this.supplierId))
      this.goBack()
    },
    goAdd() {
      this.saveDraft()
      this.goPage('supplierTimePhoneEdit', { supplierId: this.supplierId, index: -1 })
    },
    goEdit(index) {
      this.saveDraft()
      this.goPage('supplierTimePhoneEdit', { supplierId: this.supplierId, index })
    },
    deleteItem(index) {
      Dialog.confirm({
        title: '提示',
        message: '确定删除该时段电话？'
      }).then(() => {
        this.phoneList.splice(index, 1)
        this.saveDraft()
      }).catch(() => {})
    },
    // 将 HH:mm 转换为分钟数，兼容中英文冒号
    timeToMinutes(timeStr) {
      if (!timeStr) return null
      const normalized = String(timeStr).trim().replace(/：/g, ':')
      const [h, m] = normalized.split(':').map(Number)
      if (isNaN(h) || isNaN(m)) return null
      return h * 60 + m
    },
    // 校验时间段：重叠、00:00 开始、23:59 结束、遗漏（允许 1 分钟误差）
    validateTimePeriods(list) {
      const periods = list.map(item => ({
        start: this.timeToMinutes(item.startTime),
        end: this.timeToMinutes(item.endTime)
      }))
      if (periods.some(p => p.start === null || p.end === null)) {
        return '存在格式不正确的时间段'
      }
      periods.sort((a, b) => a.start - b.start)
      if (periods[0].start !== 0) {
        return '时间段未从 00:00 开始！'
      }
      if (periods[periods.length - 1].end !== 23 * 60 + 59) {
        return '时间段未到 23:59 结束！'
      }
      for (let i = 1; i < periods.length; i++) {
        if (periods[i].start < periods[i - 1].end) {
          return '时间段重叠'
        }
        if (periods[i].start - periods[i - 1].end > 1) {
          return '时间段有遗漏'
        }
      }
      return null
    },
    async onSubmitClick() {
      if (this.inApproval) return
      if (!this.phoneList.length) {
        Toast('请先添加至少一个时段电话')
        return
      }
      if (!this.phoneList.every(item => item.phone1)) {
        Toast('每条时段电话1均必填')
        return
      }
      const timeError = this.validateTimePeriods(this.phoneList)
      if (timeError) {
        Toast(timeError)
        return
      }

      Toast.loading({ message: '提交中...', forbidClick: true, duration: 0 })
      try {
        await submitSupplierPhoneApproval({
          supplierId: this.supplierId,
          modifyReason: '',
          phoneList: this.phoneList
        })
        Toast.success('提交成功')
        localStorage.removeItem(getDraftKey(this.supplierId))
        this.loadData()
      } catch (e) {
        Toast(e?.message || '提交失败，请重试')
      } finally {
        Toast.clear()
      }
    }
  }
}
</script>

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

.wrap {
  @include wh(100%, 100%);
  box-sizing: border-box;
  background: #f4f5f7;
  display: flex;
  flex-direction: column;
}

::v-deep .nav-bar {
  .van-nav-bar {
    background: #2b6cff;
  }
  .van-nav-bar__title,
  .van-nav-bar__arrow {
    color: #fff;
  }
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.status-tip {
  border-radius: 10px;
  padding: 10px 12px;
  font-size: 13px;
  line-height: 1.5;
  margin-bottom: 12px;
  &--pending {
    background: #eef3ff;
    color: #2b6cff;
  }
  &--danger {
    background: #fff2f0;
    color: #ff4d4f;
  }
  &__title {
    font-weight: 600;
  }
  &__desc {
    margin-top: 4px;
    font-size: 12px;
  }
}

.empty-wrap {
  text-align: center;
  padding: 60px 0;
  .empty-text {
    font-size: 13px;
    color: #999;
  }
}

.card-list {
  .time-card {
    background: #fff;
    border-radius: 14px;
    padding: 12px 14px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  .card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .period {
    font-size: 15px;
    font-weight: 700;
    color: #1a1a1a;
    background: #eef3ff;
    padding: 4px 10px;
    border-radius: 8px;
  }
  .ops {
    font-size: 13px;
    color: #2b6cff;
    span {
      margin-left: 14px;
      cursor: pointer;
    }
    .op-del {
      color: #ff4d4f;
    }
  }
  .divider {
    height: 1px;
    background: #f0f0f0;
    margin: 10px 0;
  }
  .phone-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 5px 0;
    font-size: 13.5px;
  }
  .phone-icon {
    color: #2b6cff;
    font-size: 14px;
  }
  .phone-num {
    font-weight: 600;
    color: #1a1a1a;
    letter-spacing: 0.3px;
  }
  .tag {
    font-size: 11px;
    padding: 2px 7px;
    border-radius: 6px;
    background: #f2f3f5;
    color: #666;
  }
  .tag-wx {
    background: #e8f8ee;
    color: #1a8a4a;
  }
}

.footer {
  padding: 10px 12px;
  background: #fff;
  border-top: 1px solid #eee;
  flex-shrink: 0;
  display: flex;
  gap: 10px;
  .btn {
    flex: 1;
    height: 46px;
    border-radius: 12px;
    border: none;
    font-size: 15px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .btn-add {
    flex: 0 0 44%;
    background: #fff;
    color: #2b6cff;
    border: 1.5px solid #2b6cff;
  }
  .btn-submit {
    background: #2b6cff;
    color: #fff;
    &:disabled {
      background: #b9c8ee;
      cursor: not-allowed;
    }
  }
}
</style>
