<template>
  <view class="page-container">
    <view class="card switch-card">
      <view class="label"> 免车费（{{ isFree ? '生效中' : '未开启' }}） </view>
      <u-switch
        size="24"
        v-model="isFree"
        activeColor="#1ecbc3"
        @change="switchChange"
      ></u-switch>
    </view>

    <view class="card form-card" v-if="isFree">
      <u-cell-group :border="false">
        <u-cell
          title="服务项目"
          :value="formData.projectNames || '请选择'"
          isLink
          :border="true"
          @click="showProjectPicker = true"
        ></u-cell>

        <u-cell
          title="服务时间1"
          :value="formData.timeRange1 || '请选择'"
          isLink
          :border="true"
          @click="openTimePicker('timeRange1')"
        ></u-cell>

        <u-cell
          title="服务时间2"
          :value="formData.timeRange2 || '请选择'"
          isLink
          :border="true"
          @click="openTimePicker('timeRange2')"
        ></u-cell>

        <u-cell title="订单距离" :border="false">
          <view slot="value" class="input-slot">
            <u-input
              v-model="formData.minDistance"
              placeholder="请输入最高免除距离"
              border="none"
              inputAlign="right"
              type="number"
              fontSize="15px"
              placeholderStyle="font-size: 14px; color: #c0c4cc;"
              @blur="distanceChange"
            >
              <template slot="suffix">
                <text class="unit-text" v-if="formData.minDistance">km</text>
              </template>
            </u-input>
          </view>
        </u-cell>
      </u-cell-group>
    </view>

    <view class="tips-card" v-if="isFree">
      <view class="tips-title">温馨提示：</view>
      <view class="tips-content">
        1.此处设置的免车费订单距离是客户距离你的直线距离，直线距离的车行距离在地理位置特殊性上可能有一定误差，望大家设置距离时知晓。
      </view>
      <view class="tips-content">
        2.超出距离xxkm后，公司固定收取车费比例的10%管理费。
      </view>
    </view>

    <u-gap height="100"></u-gap>

    <view v-if="isFree" class="footer-bar">
      <u-button
        text="保存"
        color="#1ecbc3"
        shape="circle"
        customStyle="height: 48px; font-size: 16px;"
        @click="onSave"
      ></u-button>
    </view>

    <u-picker
      title="选择项目"
      :show="showProjectPicker"
      :columns="projectList"
      confirmColor="#1ecbc3"
      @confirm="confirmProject"
      @cancel="showProjectPicker = false"
    ></u-picker>

    <u-picker
      title="选择时间"
      :show="showTimePicker"
      :columns="timeColumns"
      confirmColor="#1ecbc3"
      @confirm="confirmTime"
      @cancel="showTimePicker = false"
    ></u-picker>
  </view>
</template>

<script>
import { getProjectByJsId } from '@/api/index'
import { freeFareGet, freeFareAdd, freeFareDisable } from '@/api/staff'
export default {
  data() {
    return {
      isFree: false, // 开关状态

      // 表单数据
      formData: {
        projectNames: '',
        projectId: '',
        timeRange1: '',
        timeRange2: '',
        minDistance: '',
      },

      // 弹窗控制
      showProjectPicker: false,
      showTimePicker: false,
      activeTimeField: '', // 当前正在编辑的时间字段名

      projectData: [],
      projectList: [[]],
      // 复杂时间选择器数据列
      timeColumns: [],
      openId: '',
    }
  },
  onLoad() {
    // 初始化时间选择器的数据
    this.initTimePickerData()
    this.openId = uni.getStorageSync('wx_copenid')
    if (this.openId) {
      // 详情
      this.getFreeFareRule(this.openId)
      // 获取技师服务项目
      this.getProject(this.openId)
    }
  },
  methods: {
    getFreeFareRule(openId) {
      freeFareGet({ openId })
        .then(res => {
          if (res.data.code === 200 && res.data.data) {
            this.formData = res.data.data
            this.isFree = this.formData.enable == '1' ? true : false
          } else {
            this.isFree = false
          }
        })
        .catch(err => {
          console.error('获取免车费规则失败:', err)
        })
    },
    getProject(id) {
      getProjectByJsId({ openId: id }).then(res => {
        if (res.data.code == 200) {
          this.projectData = res.data.data
          this.projectList = [res.data.data.map(item => item.cTitle)]
        }
      })
    },
    // 初始化 5 列时间数据
    initTimePickerData() {
      // 1. 生成小时 (00时 - 23时)
      const hours = []
      for (let i = 0; i < 24; i++) {
        hours.push((i < 10 ? '0' + i : i) + '时')
      }

      // 2. 生成分钟 (00分 - 59分)
      const minutes = []
      for (let i = 0; i < 60; i++) {
        minutes.push((i < 10 ? '0' + i : i) + '分')
      }

      // 3. 组装5列：[开始时, 开始分, '至', 结束时, 结束分]
      this.timeColumns = [
        hours,
        minutes,
        ['至'], // 中间分隔符列
        hours,
        minutes,
      ]
    },
    // 开关切换
    switchChange(val) {
      if (!val) {
        // 关闭时清空或保持数据根据业务需求
        this.formData = {}
        this.onDisable()
      }
    },
    // 确认服务项目
    confirmProject(e) {
      this.formData.projectNames = e.value[0]
      const selectedProject = this.projectData.find(
        item => item.cTitle === e.value[0]
      )
      if (selectedProject) this.formData.projectId = selectedProject.cId
      this.showProjectPicker = false
    },

    // 打开时间选择
    openTimePicker(field) {
      this.activeTimeField = field
      this.showTimePicker = true
      // TODO: 这里可以根据 this.formData[field] 的值去设置 defaultIndex (回显选中位置)
      // 如果需要回显，需要解析字符串 "09:00-21:00" 并计算索引
    },
    distanceChange(val) {
      this.formData.minDistance = Number(val).toFixed(2)
    },
    // 确认时间
    confirmTime(e) {
      const values = e.value // 拿到选中的数组，如 ["09时", "00分", "至", "21时", "30分"]

      // 提取数字部分
      const startHour = values[0].replace('时', '')
      const startMin = values[1].replace('分', '')
      const endHour = values[3].replace('时', '')
      const endMin = values[4].replace('分', '')

      // 拼接格式
      const timeString = `${startHour}:${startMin}-${endHour}:${endMin}`

      // 赋值给当前激活的字段
      if (this.activeTimeField) {
        this.formData[this.activeTimeField] = timeString

        // 检查时间重叠
        this.checkTimeOverlap()
      }

      this.showTimePicker = false
    },
    // 将时间范围字符串解析为开始和结束的分钟数
    parseTimeRange(timeRange) {
      if (!timeRange) return null

      const [start, end] = timeRange.split('-')
      const [startHour, startMinute] = start.split(':').map(Number)
      const [endHour, endMinute] = end.split(':').map(Number)

      return {
        start: startHour * 60 + startMinute,
        end: endHour * 60 + endMinute,
      }
    },

    // 检查两个时间范围是否重叠
    checkTimeOverlap() {
      const range1 = this.parseTimeRange(this.formData.timeRange1)
      const range2 = this.parseTimeRange(this.formData.timeRange2)

      // 如果两个时间都已设置，则检查重叠
      if (range1 && range2) {
        // 检查是否重叠
        const isOverlap = range1.start < range2.end && range2.start < range1.end

        if (isOverlap) {
          uni.showToast({
            title: '两个服务时间不能重合',
            icon: 'none',
            duration: 2000,
          })

          // 清空当前设置的时间
          this.formData[this.activeTimeField] = ''
        }

        return isOverlap
      }

      return false
    },

    // 保存
    onSave() {
      if (this.isFree) {
        if (!this.formData.projectNames || !this.formData.minDistance) {
          uni.showToast({
            title: '请完善配置信息',
            icon: 'none',
          })
          return
        }

        // 校验服务时间
        if (this.checkTimeOverlap()) {
          return
        }
      }
      const params = {
        ...this.formData,
        minDistance: Number(this.formData.minDistance),
        openId: this.openId,
        enable: this.isFree ? '1' : '0',
      }
      freeFareAdd(params).then(res => {
        if (res.data.code === 200) {
          if (this.isFree) {
            uni.showToast({
              title: '提交成功',
              icon: 'none',
            })

            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              })
            }, 1000)
          }
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
      })
    },
    onDisable() {
      const params = {
        openId: this.openId,
        enable: '0',
      }
      freeFareDisable(params).then(res => {
        if (res.data.code === 200) {
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
      })
    },
    onBack() {
      uni.navigateBack({
        delta: 1,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  padding: 20rpx;
  padding-bottom: 120rpx;
  background-color: #f6f7f9;

  .card {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
  }

  .switch-card {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .label {
      font-size: 30rpx;
      color: #333;
    }
  }

  .form-card {
    .input-slot {
      width: 300rpx;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }

    .unit-text {
      color: #333;
      margin-left: 4rpx;
      font-size: 30rpx;
    }
  }

  .tips-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;

    .tips-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 16rpx;
    }

    .tips-content {
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 10rpx;
      text-align: justify;
    }
  }
}
</style>