<template>
  <view class="app-container">
    <HeaderBar title="一键报修" text-align="center" enable-back />

    <view class="form-box">
      <!-- 地址选择 -->
      <view class="form-item" @click="chooseLocation">
        <view class="label">定位</view>
        <view class="input">
          <text :class="{'placeholder': !form.regionMergerName}">{{ form.regionMergerName || '请选择定位' }}</text>
        </view>
      </view>

      <!-- 详细地址 -->
      <view class="form-item">
        <view class="label">详细地址</view>
        <textarea
          class="textarea"
          v-model="form.createAddress"
          placeholder="请输入详细地址"
          placeholder-class="placeholder"
        />
      </view>

      <!-- 任务类型 -->
      <view class="form-item">
        <view class="label">任务类型</view>
        <picker
          :range="taskTypeList"
          @change="onTypeChange"
          :value="typeIndex"
        >
          <view class="input">{{ taskTypeList[typeIndex] }}</view>
        </picker>
      </view>

      <!-- 上传视频 -->
      <view class="form-item">
        <view class="label">
          上传视频/照片
          <span class="required">(必填)</span>
        </view>
        <image-upload
          :limit="1"
          accept="media"
          :multiple="false"
          v-model="form.video"
        />
      </view>

      <!-- 备注 -->
      <view class="form-item">
        <view class="label">
          备注
          <span class="optional">(可不填)</span>
        </view>
        <textarea
          class="textarea"
          v-model="form.remark"
          maxlength="300"
          placeholder="详细描述"
        />
        <view class="count">{{ form.remark.length }}/300</view>
      </view>
    </view>

    <button class="submit-btn" @click="submitForm">一键报修</button>
  </view>
</template>

<script>
import HeaderBar from '@/components/HeaderBar.vue'
import ImageUpload from '@/components/image-upload/image-upload.vue'
import { appAddTask, appGetTaskDetail } from '@/api/app/task'
import { appGetDefaultCar } from '@/api/app/car'
import { appGetRegionByLocation } from '@/api/app/region'

export default {
  name: 'TaskEdit',
  components: {
    HeaderBar,
    ImageUpload
  },
  data() {
    return {
      taskTypeList: ['急修', '拖车'],
      typeIndex: 0,
      form: {},
      sourceId: null,
    }
  },
  onLoad(options) {
    this.sourceId = options.sourceId;
    this.reset();
  },
  methods: {
    reset() {
      this.form = {
        type: "1",
        video: '',
        regionId: null,
        regionMergerName: '',
        createLon: null,
        createLat: null,
        createName: '',
        createMobile: '',
        createAddress: '',
        remark: '',
        carId: null,
        carNo: null
      }

      if (this.sourceId) {
        this.$modal.loading("加载中");
        appGetTaskDetail(this.sourceId).then(res => {
          if (res.code === 200 && res.data != null) {
            this.form = res.data;
            this.form.id = null;
          }
        }).finally(() => {
          this.$modal.closeLoading();
        })
      } else {
        this.initRegion();
      }
    },
    chooseLocation() {
      wx.chooseLocation({
        success: (res) => {
          console.log("res", res);
          this.form.createLon = res.longitude
          this.form.createLat = res.latitude
          this.getRegion(res.name);
        },
        fail: (err) => {
          console.error('选择位置失败：', err)
          this.$modal.msgError('选择位置失败，请重试')
        }
      })
    },
    // 初始化行政区
    initRegion() {
      this.$modal.loading("加载中");
      // 获取当前位置
      wx.getLocation({
        type: "gcj02",
        accuracy: 'best',
        isHighAccuracy: true,
        success: (res) => {
          console.log("res", res);
          this.form.createLon = res.longitude
          this.form.createLat = res.latitude
          this.getRegion(res.name);
        },
        fail: (err) => {
          this.$modal.closeLoading();
          console.error('获取当前位置失败：', err)
        }
      })
    },
    // 获取行政区
    getRegion(address) {
      if (this.form.createLon == null || this.form.createLat == null) {
        this.$modal.closeLoading();
        return;
      }
      this.$modal.loading("加载中");
      appGetRegionByLocation(this.form.createLon, this.form.createLat).then(res => {
        if (res.data != null && res.data.region != null) {
          this.form.regionId = res.data.region.id;
          this.form.regionMergerName = res.data.region.mergerName;
          if (res.data.regeo != null && address == null) {
            this.form.createAddress = res.data.regeo.regeocode?.formatted_address;
          } else {
            this.form.createAddress = this.form.regionMergerName?.replaceAll(",", "") + address;
          }
        }
        this.$modal.closeLoading();
      })
    },
    getDefaultCar() {
      appGetDefaultCar().then(res => {
        if (res.data) {
          this.form.carId = res.data.id
          this.form.carNo = res.data.no
        }
      })
    },
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.form.type = (parseInt(e.detail.value) + 1).toString()
    },
    submitForm() {
      this.$modal.loading("提交中");
      // 调用报修接口
      appAddTask(this.form).then(res => {
        if (res.code === 200 && res.data != null) {
          this.$modal.msgSuccess('提交成功');
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/task/detail?id=' + res.data })
          }, 500)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding-bottom: 180rpx;
}
.form-box {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx 20rpx;
  margin: 30rpx 20rpx;
}
.form-item {
  margin-bottom: 30rpx;
  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    .required { color: #f56c6c; font-size: 22rpx; }
    .optional { color: #999; font-size: 22rpx; }
  }
  .input {
    background: #f7f8fa;
    border-radius: 10rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #666;

    .address-info {
      .name-phone {
        margin-bottom: 10rpx;

        .name {
          font-size: 32rpx;
          color: #333;
          margin-right: 20rpx;
        }

        .phone {
          font-size: 28rpx;
          color: #666;
        }
      }

      .address {
        font-size: 28rpx;
        color: #666;
      }
    }

    .add-placeholder {
      background: #ffffff71;
      border: 2rpx dashed #fff;
      border-radius: 10rpx;
      padding: 40rpx;
      text-align: center;

      .add-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10rpx;

        .add-text {
          font-size: 28rpx;
          color: #2979ff;
        }
      }
    }
  }
  .textarea {
    width: 100%;
    min-height: 120rpx;
    background: #f7f8fa;
    border-radius: 10rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #666;
    resize: none;
    border: none;
  }
  .count {
    text-align: right;
    color: #bbb;
    font-size: 22rpx;
  }
}
.submit-btn {
  width: 90%;
  margin: 40rpx auto 0;
  display: block;
  background: #2979ff;
  color: #fff;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border: none;
}
</style>