<template>
  <view class="app-container">
    <HeaderBar title="商家加盟" enable-back text-align="center"/>


    <view class="form-box">
      <!-- 审核意见 -->
      <view class="form-item" v-if="form.verifyRemark && form.status == MchStatus.REJECTED">
        <view class="verify-remark">审核意见：{{ form.verifyRemark }}</view>
      </view>
      <!-- 商家头像 -->
      <view class="form-item">
        <view class="label">
          商家头像
        </view>
        <image-upload
          :limit="1"
          accept="image"
          :multiple="false"
          v-model="form.avatar"
        />
      </view>

      <!-- 商家名称 -->
      <view class="form-item">
        <view class="label">
          商家名称
          <span class="required">(必填)</span>
        </view>
        <input
          class="input"
          v-model="form.name"
          placeholder="请输入商家名称"
          placeholder-class="placeholder"
        />
      </view>

      <!-- 联系方式 -->
      <view class="form-item">
        <view class="label">
          联系方式
          <span class="required">(必填)</span>
        </view>
        <input
          class="input"
          v-model="form.mobile"
          placeholder="请输入联系方式"
          placeholder-class="placeholder"
          type="number"
          maxlength="11"
        />
      </view>

      <!-- 营业执照 -->
      <view class="form-item">
        <view class="label">
          营业执照
          <span class="required">(必填)</span>
        </view>
        <image-upload
          :limit="1"
          accept="image"
          :multiple="false"
          v-model="form.businessLicense"
        />
      </view>

      <!-- 门面照片 -->
      <view class="form-item">
        <view class="label">
          门面照片
          <span class="required">(必填)</span>
        </view>
        <image-upload
          :limit="1"
          accept="image"
          :multiple="false"
          v-model="form.pictures"
        />
      </view>

      <!-- 法人身份证正面 -->
      <view class="form-item">
        <view class="label">
          法人身份证正面
          <span class="required">(必填)</span>
        </view>
        <image-upload
          :limit="1"
          accept="image"
          :multiple="false"
          v-model="form.legalIdCardFront"
        />
      </view>

      <!-- 法人身份证反面 -->
      <view class="form-item">
        <view class="label">
          法人身份证反面
          <span class="required">(必填)</span>
        </view>
        <image-upload
          :limit="1"
          accept="image"
          :multiple="false"
          v-model="form.legalIdCardBack"
        />
      </view>

      <!-- 定位 -->
      <view class="form-item" @click="chooseLocation">
        <view class="label">
          定位
          <span class="required">(必填)</span>
        </view>
        <view class="input">
          <text :class="{'placeholder': !form.regionMergerName}">{{ form.regionMergerName || '请选择定位' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 详细地址 -->
      <view class="form-item">
        <view class="label">
          详细地址
          <span class="required">(必填)</span>
        </view>
        <textarea
          class="textarea"
          v-model="form.address"
          placeholder="请输入详细地址"
          placeholder-class="placeholder"
        />
      </view>

      <!-- 描述 -->
      <view class="form-item">
        <view class="label">
          描述
        </view>
        <textarea
          class="textarea"
          v-model="form.descriptons"
          placeholder="请输入商家描述"
          placeholder-class="placeholder"
          maxlength="300"
        />
        <view class="count">{{ form.descriptons.length }}/300</view>
      </view>
    </view>

    <button class="submit-btn" @click="handleSubmit">提交申请</button>

  </view>
</template>

<script>
import HeaderBar from '@/components/HeaderBar.vue'
import ImageUpload from '@/components/image-upload/image-upload.vue'
import RegionPicker from '@/components/RegionPicker.vue'
import { applyMch, updateMch, getMchDetail} from '@/api/app/mch'
import { appGetRegionByLocation } from '@/api/app/region'
import { MchStatus } from '@/utils/enums'

export default {
  name: 'MchWelcome',
  components: {
    HeaderBar,
    ImageUpload,
    RegionPicker
  },
  data() {
    return {
      MchStatus,
      form: {
        name: '',
        descriptons: '',
        avatar: '',
        regionId: null,
        lon: null,
        lat: null,
        regionMergerName: '',
        address: '',
        businessLicense: '',
        pictures: '',
        legalIdCardFront: '',
        legalIdCardBack: '',
        mobile: ''
      },
      selectedRegionIds: []
    }
  },
  onLoad(options) {
    this.initRegion();
    if (options.id) {
      this.getMchDetail(options.id);
    }
  },
  methods: {
    getMchDetail(id) {
      this.$modal.loading("加载中");
      getMchDetail(id).then(res => {
        if (res.data?.verifyInfo != null) {
          this.form = res.data.verifyInfo;
        } else {
          this.form = res.data;
        }
        this.form.id = id;
      }).finally(() => {
        this.$modal.closeLoading();
      })
    },
    // 初始化行政区
    initRegion() {
      this.$modal.loading("加载中");
      // 获取当前位置
      wx.getLocation({
        type: "gcj02",
        accuracy: 'best',
        isHighAccuracy: true,
        success: (res) => {
          this.form.lon = res.longitude
          this.form.lat = res.latitude
          this.getRegion();
        },
        fail: (err) => {
          this.$modal.closeLoading();
          console.error('获取当前位置失败：', err)
        }
      })
    },
    // 获取行政区
    getRegion(address) {
      if (this.form.lon == null || this.form.lat == null) {
        this.$modal.closeLoading();
        return;
      }
      this.$modal.loading("加载中");
      appGetRegionByLocation(this.form.lon, this.form.lat).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.address = res.data.regeo.regeocode?.formatted_address;
          } else {
            this.form.address = this.form.regionMergerName?.replaceAll(",", "") + address;
          }
        }
        this.$modal.closeLoading();
      })
    },
    chooseLocation() {
      wx.chooseLocation({
        success: (res) => {
          this.form.lon = res.longitude
          this.form.lat = res.latitude
          this.getRegion(res.name);
        },
        fail: (err) => {
          console.error('选择位置失败：', err)
          this.$modal.msgError('选择位置失败，请重试')
        }
      })
    },
    handleSubmit() {
      if (!this.form.name) {
        this.$modal.msgError('请输入商家名称')
        return
      }
      if (!this.form.mobile) {
        this.$modal.msgError('请输入联系方式')
        return
      }
      if (!this.form.businessLicense) {
        this.$modal.msgError('请上传营业执照')
        return
      }
      if (!this.form.pictures) {
        this.$modal.msgError('请上传门面照片')
        return
      }
      if (!this.form.legalIdCardFront) {
        this.$modal.msgError('请上传法人身份证正面')
        return
      }
      if (!this.form.legalIdCardBack) {
        this.$modal.msgError('请上传法人身份证反面')
        return
      }
      if (!this.form.regionId) {
        this.$modal.msgError('请选择定位')
        return
      }
      if (!this.form.address) {
        this.$modal.msgError('请输入详细地址')
        return
      }

      this.$modal.loading('提交中...')
      if (this.form.id == null) {
        applyMch(this.form).then(() => {
          this.$modal.msgSuccess('提交成功，请等待审核')
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        })
      } else {
        updateMch(this.form).then(() => {
          this.$modal.msgSuccess('提交成功，请等待审核')
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding-bottom: 100rpx;
}
.form-box {
  background: #fff;
  margin: 0 20rpx;
  border-radius: 24rpx;
  padding: 30rpx 20rpx;
  margin-top: 30rpx;
  box-shadow: 0 4rpx 24rpx rgba(106, 140, 255, 0.06);
}

.form-item {
  margin-bottom: 30rpx;
  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    font-weight: 500;
    .required { color: #f56c6c; font-size: 22rpx; }
  }
  .verify-remark {
    background: #fff7f7;
    border-radius: 12rpx;
    padding: 24rpx 20rpx;
    font-size: 28rpx;
    color: #f56c6c;
    line-height: 1.5;
  }
  .input {
    background: #f7f8fa;
    border-radius: 12rpx;
    padding: 24rpx 20rpx;
    font-size: 28rpx;
    color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    box-sizing: border-box;
  }
  .textarea {
    width: 100%;
    min-height: 120rpx;
    background: #f7f8fa;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    resize: none;
    border: none;
  }
  .count {
    text-align: right;
    color: #bbb;
    font-size: 22rpx;
    margin-top: 10rpx;
  }
}

.placeholder {
  color: #999;
}

.submit-btn {
  width: 90%;
  margin: 40rpx auto 0;
  display: block;
  background: linear-gradient(180deg, #6a8cff 0%, #4a6cff 100%);
  color: #fff;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(106, 140, 255, 0.3);
}
</style>