<template>
  <view class="container">

    <tui-form ref="form" :show-message="false" :model="formData">
      <tui-form-item asterisk label="名称" prop="treetype">
        <tui-input padding="0" :borderBottom="false" placeholder="请输入名称" maxlength="30"
                   v-model="formData.treetype"></tui-input>
      </tui-form-item>

      <tui-row>

        <tui-col :span="12">
          <tui-form-item label="胸径" asterisk prop="dbh" :position="2">
            <tui-input padding="0" :borderBottom="false" placeholder="请输入"  maxlength="10"    textLeft
                       v-model="formData.dbh"></tui-input>
            <template v-slot:right>
              <text style="padding-left: 12rpx;color:#ccc;font-size:12px">米</text>
            </template>
          </tui-form-item>
        </tui-col>
        <tui-col :span="12">
          <tui-form-item label="高度"  prop="treeheight" :position="2">
            <tui-input padding="0" :borderBottom="false" placeholder="请输入"  maxlength="10"    textLeft
                       v-model="formData.treeheight"></tui-input>
            <template v-slot:right>
              <text style="padding-left: 12rpx;color:#ccc;font-size:12px;">米</text>
            </template>
          </tui-form-item>
        </tui-col>
      </tui-row>


      <tui-form-item
          asterisk
          label="位置"
          class="location-form-item"
          @click="openMap"
          prop="growlocation"
      >
        <tui-input padding="0" :borderBottom="false" placeholder="请选择" disabled
                   v-model="formData.growlocation"></tui-input>
        <template v-slot:right>
          <tui-icon name="gps" :size="20"></tui-icon>
        </template>
      </tui-form-item>

      <tui-col :span="12">
        <tui-form-item
            label="经度"
            labelColor="#ccc"
            class="location-form-item"
            prop="latitude"
            :bottomBorder="false"
        >
          <span style="color: #ccc;font-size: 14px"> {{ formData.longitude }}</span>
        </tui-form-item>
      </tui-col>
      <tui-col :span="12">
        <tui-form-item
            :bottomBorder="false"
            label="纬度"
            labelColor="#ccc"
            class="location-form-item"
            prop="latitude"
        >
          <span style="color: #ccc;font-size: 14px"> {{ formData.latitude }}</span>
        </tui-form-item>
      </tui-col>


      <tui-form-item asterisk label="管护单位" prop="managedutyunit">

        <tui-input padding="0" :borderBottom="false" placeholder="请输入" maxlength="30"
                   v-model="formData.managedutyunit"></tui-input>

        <!--        <tui-input padding="0" :borderBottom="false" placeholder="请选择" disabled-->
        <!--                   backgroundColor="transparent" v-model="formData.managedutyunit"></tui-input>-->
      </tui-form-item>
      <tui-form-item asterisk label="权属分类" arrow highlight prop="oldtreeownershipText" @click="pickerShow">
        <tui-input padding="0" :borderBottom="false" placeholder="请选择" disabled
                   backgroundColor="transparent" v-model="formData.oldtreeownershipText"></tui-input>
      </tui-form-item>

      <tui-form-item label="图片信息" asterisk prop="treeImgList">
        <!-- 使用ThorUI的tui-upload组件 -->
        <!--           @remove="handleRemove"   :multiple="true"    :value="formData.treeImgList"-->
        <tui-upload
            :height="140"
            :width="140"
            :value="formData.treeImgListFile"
            :serverUrl="serverURL" :header="{'Authorization': userToken}"
            @complete="handleComplete"
            @remove="handleRemove"
            :limit="3"
            accept="image/*"
        >
          <!-- 自定义上传按钮 -->
          <view class="upload-btn">
            <tui-icon name="plus" size="32" color="#999"></tui-icon>
          </view>
        </tui-upload>
      </tui-form-item>

      <!-- 动画区域（初始隐藏） -->
      <view
          class="animated-area"
          :style="{
        height: isShow ? contentHeight + 'px' : '0',
        opacity: isShow ? 1 : 0,
        overflow: 'hidden'
      }"
      >

        <tui-row>
          <tui-col :span="12">
            <tui-form-item label="拉丁文" prop="latinname">
              <tui-input padding="0" :borderBottom="false" placeholder="请输入" maxlength="30"
                         v-model="formData.latinname"></tui-input>
            </tui-form-item>
          </tui-col>
          <tui-col :span="12">
            <tui-form-item label="级别" arrow highlight prop="treeleveltext" @click="pickerLevelShow">
              <tui-input padding="0" :borderBottom="false" placeholder="请选择" disabled
                         backgroundColor="transparent" v-model="formData.treeleveltext"></tui-input>
            </tui-form-item>
          </tui-col>
        </tui-row>

        <tui-form-item label="生长环境" prop="growthenvironment">
          <tui-input padding="0" :borderBottom="false" placeholder="请输入" maxlength="50"
                     v-model="formData.growthenvironment"></tui-input>
        </tui-form-item>


        <tui-row>
          <tui-col :span="12">
            <tui-form-item label="预估树龄" prop="estimationtreeage" :position="2">
              <tui-input padding="0" :borderBottom="false" placeholder="请输入"  maxlength="10"
                         v-model="formData.estimationtreeage"></tui-input>
              <template v-slot:right>
                <text style="padding-left: 12rpx;color:#ccc;font-size: 12px">年</text>
              </template>
            </tui-form-item>
          </tui-col>
          <tui-col :span="12">
            <tui-form-item label="干周" prop="weekday" :position="2">
              <tui-input padding="0" :borderBottom="false" placeholder="请输入"  maxlength="10"
                         v-model="formData.weekday"></tui-input>
              <template v-slot:right>
                <text style="padding-left: 12rpx;color:#ccc;font-size: 12px">厘米</text>
              </template>
            </tui-form-item>
          </tui-col>
        </tui-row>


        <tui-row>
          <tui-col :span="12">
            <tui-form-item label="东西冠幅" prop="canopyeastwest" :position="2">
              <tui-input padding="0" :borderBottom="false" placeholder="请输入"  maxlength="10"
                         v-model="formData.canopyeastwest"></tui-input>
              <template v-slot:right>
                <text style="padding-left: 12rpx;color:#ccc;font-size: 12px">米</text>
              </template>
            </tui-form-item>
          </tui-col>
          <tui-col :span="12">
            <tui-form-item label="南北冠幅" prop="canopysouthnorth" :position="2">
              <tui-input padding="0" :borderBottom="false" placeholder="请输入"  maxlength="10"
                         v-model="formData.canopysouthnorth"></tui-input>
              <template v-slot:right>
                <text style="padding-left: 12rpx;color:#ccc;font-size: 12px">米</text>
              </template>
            </tui-form-item>
          </tui-col>
        </tui-row>


      </view>

      <!-- 触发按钮 -->
      <tui-button
          @click="toggleArea"
          type="primary"
          :loading="false"
          height="80rpx"
          plain
      >
        {{ isShow ? '- 隐藏区域' : '+ 显示区域' }}
      </tui-button>
    </tui-form>

    <view style="height: 60px;width: 100%"></view>

    <view class="tui-btn__box">
      <tui-button bold @click="submit">提交</tui-button>
    </view>
    <tui-picker :show="show" :pickerData="treeOwnershipData" textField="dictLabel" valueField="dictValue"
                @hide="pickerHide" @change="pickerChange">
    </tui-picker>

    <tui-picker :show="levelshow" :pickerData="treeLevelData" textField="dictLabel" valueField="dictValue"
                @hide="pickerLevelHide" @change="pickerLevelChange">
    </tui-picker>
  </view>
</template>

<script>
import { uploadURL, OSSURL } from '@/config/app'
import { treeOwnership, addTree, treeLevelReq } from "@/subPackages/common/api/tree.js";
const rules = [{
  name: "treetype",
  rule: ["required"],
  msg: ["请输入名称"]
}, {
  name: "treeheight",
  rule: ["maxLength:10", "isAmount"],
  msg: ["树高不能超过10个字符", "请输入正确"]
}, {
  name: "dbh",
  rule: ["required", "maxLength:10", "isAmount"],
  msg: ["请输入胸径", "胸径不能超过10个字符", "请输入正确"]
}, {
  name: "estimationtreeage",
  rule: ["maxLength:10", "isAmount"],
  msg: ["胸径不能超过10个字符", "请输入正确"]
},
  {
    name: "weekday",
    rule: ["maxLength:10", "isAmount"],
    msg: ["胸径不能超过10个字符", "请输入正确"]
  },
  {
    name: "canopyeastwest",
    rule: ["maxLength:10", "isAmount"],
    msg: ["胸径不能超过10个字符", "请输入正确"]
  },
  {
    name: "canopysouthnorth",
    rule: ["maxLength:10", "isAmount"],
    msg: ["胸径不能超过10个字符", "请输入正确"]
  }, {
    name: "growlocation",
    rule: ["required"],
    msg: ["请地图选择位置"]
  }, {
    name: "managedutyunit",
    rule: ["required"],
    msg: ["请输入管护单位"]
  }, {
    name: "oldtreeownershipText",
    rule: ["required"],
    msg: ["请选择权属分类"]
  }, {
    name: "treeImgListFile",
    rule: ["required", "custom"], // 增加required强制必选
    msg: ["请上传图片", "请至少上传一张图片"], // 对应两个规则的提示
    custom: function (value) {
      // 即使required通过，再校验数组长度
      return value.length > 0;
    }
  }];
export default {
  props: {
    // 外部传入的已上传图片列表
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isShow: false,       // 控制区域显示/隐藏
      contentHeight: 200,    // 内容区域高度
      serverURL: uploadURL,
      treeOwnershipData: [],
      treeLevelData: [], // 级别
      show: false,
      levelshow: false,
      //仅对部分数据进行收集演示
      formData: {
        //数名
        treetype: '',
        //树高
        treeheight: '',
        //胸径
        dbh: '',
        //级别
        treelevel: '',
        treeleveltext: '',
        //权属单位
        managedutyunit: '',
        //权属分类
        oldtreeownership: '',
        oldtreeownershipText: '',
        latinname: '', // 拉丁名
        estimationtreeage: '', // 估测树龄
        canopysouthnorth: '', // 冠幅南北
        canopyeastwest: '', // 冠幅东西
        weekday: '', // 干周
        growlocation: '', // 位置
        growthenvironment: '', // 生长环境
        treeImgList: [], // 图片信息
        treeImgListFile: [], // 图片信息
        address: '',      // 位置名称
        latitude: '',     // 纬度
        longitude: '',     // 经度
        road: ''
      },
    }
  },
  watch: {},
  onReady() {
    //开启即时校验，开启后输入即校验【参数必传】，第一参数：是否开启；第二参数：校验规则
    // 开启即时校验，参数：是否开启、校验规则
    this.$refs.form && this.$refs.form.immediateValidate(true, rules);
    // this.$refs.form && this.$refs.form.immediateValidate(true, rules)
  },
  onLoad(options) {
    this.formData.road = options.roadId

  },
  onShow(){
    treeLevelReq().then(res => {
      this.treeLevelData = res.data
    })
    this.treeOwnership()
  },
  methods: {
    // 权属分类
    treeOwnership() {
      treeOwnership().then(res => {
        console.log(res)
        this.treeOwnershipData = res.data
      })
    },
    // 切换显示/隐藏状态
    toggleArea() {
      this.isShow = !this.isShow;
    },
    // 上传完成回调
    handleComplete(e) {
      if (e.status == 1) {
        console.log(e)
        // this.formData.treeImgList.push(e.imgArr);
        console.log(e.imgArr[0])
        this.formData.treeImgListFile = e.imgArr
        this.formData.treeImgList = e.imgArr.map(item => OSSURL + item);
        console.log(this.formData.treeImgList)
        // baseURL
        // 手动触发treeImgList字段的校验
        this.$refs.form.validateField("treeImgList");
      }
      // this.formData.treeImgList = e.imgArr;
      // 根据实际接口返回格式调整
      // this.currentFiles.push(e.data);
    },
    // 删除图片回调
    handleRemove(index) {
      // 从列表中移除
      this.formData.treeImgList.splice(index, 1);
      this.formData.treeImgListFile.splice(index, 1);
      console.log(this.formData.treeImgList.length)
    },
    pickerShow() {
      this.show = true
    },
    pickerHide() {
      this.show = false
    },
    pickerChange(e) {
      console.log(e)
      this.formData.oldtreeownership = e.dictValue
      this.formData.oldtreeownershipText = e.dictLabel
    },
    pickerLevelShow() {
      this.levelshow = true
    },
    pickerLevelHide() {
      this.levelshow = false
    },
    pickerLevelChange(e) {
      console.log(e)
      this.formData.treelevel = e.dictValue
      this.formData.treeleveltext = e.dictLabel
    },
    submit() {

      // 3. 打印提交时的数据
      console.log("提交时treeImgList：", this.formData.treeImgList);
      // 手动校验图片
      if (!this.formData.treeImgList || this.formData.treeImgList.length === 0) {
        uni.showToast({title: "请上传图片", icon: "none"});
        return; // 阻止提交
      }
      //注：结合FormItem校验，validate方法第三个参数必须传true
      this.$refs.form.validate(this.formData, rules, true).then(res => {
        if (res.isPass) {
          console.log(this.formData)
          console.log('校验通过！')

          this.formData.maintainunit = this.userInfo.belongCompanyId
          // addTree()
          addTree({data: {...this.formData}}).then(res => {
            console.log(res)
            if (res.code == '200') {
              uni.showToast({title: "新增成功", icon: "none"});
              // uni.$tui.href(`/subPackages/treePage/treeRecord?roadId=${this.formData.road}`)
              // uni.$tui.href(`/subPackages/treePage/treeFiles`)
              uni.redirectTo({
                url: '/subPackages/treePage/treeFiles' // 目标页面路径
              });
            }
          })
        } else {
          console.log(res)
        }
      }).catch(errors => {
        console.log(errors)
      })
    },
    // 打开地图选择
    openMap() {
      // 如果已有位置信息，默认显示该位置，否则使用当前位置

      // const options = {
      //   latitude: this.formData.latitude ? Number(this.formData.latitude) : '116.359080',
      //   longitude: this.formData.longitude ? Number(this.formData.longitude) : '39.882889',
      //   scale: 16,        // 地图缩放级别
      //   name: this.formData.growlocation || '',  // 位置名称
      //   address: this.formData.growlocation || '' // 详细地址
      // };
      // 调用微信小程序地图选择API
      uni.chooseLocation({
        // ...options,
        success: (res) => {
          console.log(res)
          // 选择成功后更新位置信息
          this.formData.growlocation = res.address
          this.formData.latitude = res.latitude
          this.formData.longitude = res.longitude
        },
        fail: (err) => {
          console.error('地图选择失败', err);
          if (err.errMsg.includes('auth deny')) {
            uni.showToast({
              title: '请授权位置权限',
              icon: 'none'
            });
          }
        }
      });
    }
  }
}
</script>

<style>


.tui-btn__box {
  width: 100%;
  position: fixed;
  bottom: 0;
}

/* 动画区域样式 */
.animated-area {
  height: 200rpx;
  transition: all 0.3s ease-out; /* 动画过渡效果 */
}
</style>