<template>
	<view class="fs-p30">
		<tui-form ref="form" :showMessage="false">
			<view class="fs-radius__sm">
				<tui-input placeholder="请选择" label="养护街道" v-model="formData.streetName" disabled @click="pickerOpen(1)"></tui-input>
				<tui-input placeholder="请选择" label="养护道路" v-model="formData.roadName" disabled @click="pickerOpen(2)"></tui-input>
				<tui-input placeholder="请选择" label="养护组长" v-model="formData.leaderUserName" disabled @click="pickerOpen(3)"></tui-input>
				<tui-input placeholder="请选择" label="具体位置" v-model="formData.lonLatAddress" disabled @click="openMap()">

          <template v-slot:right>
            <tui-icon name="position"  size="16"></tui-icon>
          </template>
        </tui-input>

        <tui-input placeholder="请选择" label="问题来源" v-if="editDisabled" v-model="formData.problemSourceName" disabled></tui-input>
				<tui-input placeholder="请选择" label="问题来源" v-else v-model="formData.problemSourceName" disabled @click="pickerOpen(4)"></tui-input>
				<tui-form-item label="紧急程度" :bottomBorder="false">
					<tui-radio-group v-model="formData.pressingType">
						<view class="fs-flex">
							<tui-label margin="0 0 0 30rpx" v-for="(item,index) in pressingTypeList">
								<tui-radio :checked="item.checked" :value="item.value"></tui-radio>
								<text class="fs-ml16">{{item.name}}</text>
							</tui-label>
						</view>
					</tui-radio-group>
				</tui-form-item>
			</view>
			<tui-white-space></tui-white-space>
			<tui-textarea :radius="20" placeholder="请输入问题描述" isCounter :size="28" :maxlength="500" v-model="formData.remark"></tui-textarea>
			<tui-white-space></tui-white-space>
			<tui-tab :tabs="tabList" scroll bold :leftGap="30" @change="tabChange"></tui-tab>
			<tui-white-space></tui-white-space>
			<tui-upload v-show="currentIndex == 0" background="#fff" :value="imgsValue" :width="210" :radius="10" :height="210" delColor="#333" custom :serverUrl="serverURL" :header="{'Authorization': userToken}" :limit="3" @complete="complete($event, 'imgs')">
				<text class="fs-size__28 fs-color__subtitle fs-weight__400">问题图片</text>
			</tui-upload>
			<tui-upload v-show="currentIndex == 1" background="#fff" :width="210" :radius="10" :height="210" delColor="#333" custom :serverUrl="serverURL" :header="{'Authorization': userToken}" :limit="3" @complete="complete($event, 'streetImgList')">
				<text class="fs-size__28 fs-color__subtitle fs-weight__400">街景图片</text>
			</tui-upload>
			<tui-upload v-show="currentIndex == 2" background="#fff" :width="210" :radius="10" :height="210" delColor="#333" custom :serverUrl="serverURL" :header="{'Authorization': userToken}" :limit="3" @complete="complete($event, 'longRangeImgList')">
				<text class="fs-size__28 fs-color__subtitle fs-weight__400">远景图片</text>
			</tui-upload>
		</tui-form>
		<view class="fs-mt60 fs-flex__center fs-safe__area">
			<tui-button shape="circle" width="600rpx" height="80rpx" shadow :loading="isLoading" :disabled="isLoading" @click="onSubmit">提 交</tui-button>
		</view>
		<tui-picker :show="pickerShow" radius :pickerData="pickerList[pickerType]" textField="name" valueField="id" @hide="pickerHide" @change="pickerChange"></tui-picker>
	</view>
</template>

<script>
import { uploadURL, OSSURL } from '@/config/app'
import { apiCaseAdd, apiStreetList, apiRoadListByStreetId, apiLeaderList } from '@/api/work'
import { apiTypeList } from '@/api/app'
const rules = [
	{
		name: "streetName",
		rule: ["required"],
		msg: ["请选择养护街道"]
	}, 
	{
		name: "roadName",
		rule: ["required"],
		msg: ["请选择养护道路"]
	}, 
	{
		name: "leaderUserName",
		rule: ["required"],
		msg: ["请选择养护组长"]
	},
	{
		name: "problemSourceName",
		rule: ["required"],
		msg: ["请选择问题来源"]
	},
	{
		name: "lonLatAddress",
		rule: ["required"],
		msg: ["请选择具体位置"]
	},
	{
		name: "remark",
		rule: ["required"],
		msg: ["请输入问题描述"]
	}
]
export default {
	data() {
		return {
			formData: {
				streetId: 0,
				streetName: '',
				roadId: 0,
				roadName: '',
				leaderUserId: 0,
				leaderUserName: '',
				remark: '',
				imgs: [],
				pressingType: 3,
				streetImgList: [],
				longRangeImgList: [],
				latLonType: 1,
				lat: 0,
				lon: 0,
				lonLatAddress: '',
				problemSourceId: 0,
				problemSourceName: ''
			},
			pickerList: [],
			isLoading: false,
			pickerShow: false,
			pickerType: 0,
			pressingTypeList: [
				{value:1, name:'特急'},
				{value:2, name:'紧急'},
				{value:3, name:'一般', checked:true}
			],
			serverURL: uploadURL,
			currentIndex: 0,
			tabList: ['问题图片', '街景图片', '远景图片'],
      hotlinenumber:'',
      editDisabled:false,
      imgsValue:[], //初始化图片
		}
	},
	onLoad(options) {
    this.getStreetList()
		this.getLeaderList()
		this.getTypeList()
    this.hotlinenumber = options.hotlinenumber
    if(this.hotlinenumber){
      // 1. 获取 eventChannel 实例
      const eventChannel = this.getOpenerEventChannel();

      // 2. 监听A页面发送的事件，接收大量数据
      eventChannel.on('largeDataFromWorkOrder', (largeData) => {
        console.log('A页面传递的大量数据：', largeData);
        // 存储到 data 中供页面使用
        // this.formData = largeData;
        this.editDisabled = true
        let largeData1 = {
          "searchEntities": null,
          "createBy": "吴宗刚",
          "createTime": "2025-09-08 22:48:39",
          "updateBy": "xcyl",
          "updateTime": "2025-09-09 19:56:56",
          "remark": null,
          "beginTime": null,
          "endTime": "2025-09-30 15:52:20",
          "exportType": null,
          "params": {},
          "id": "5a76e18752f69dca1e98666aa93cc7c9",
          "hotlinenumber": "WO005_20250908224839",
          "casefile": null,
          "eventsouce": "12345",
          "citynum": "西城自己的-2250627-7777777",
          "regionnum": "西城园林-250627-7777777",
          "taskstate": "gdtype02",
          "ownership": "0",
          "casesource": "01",
          "department": "10002",
          "companyid": "10002",
          "companyVo": "西城园林",
          "street": "110102012000",
          "streetVo": "什刹海街道",
          "callName": "王虹云-西城自己创建",
          "callTel": "13581551620",
          "acceptcasetime": "2025-09-02 00:00:00",
          "address": "什刹海公园东门东侧道北",
          "content": "市民反映，西城区恭王府南门口东侧道北有一颗近百年的杨树，被连根斩了，希望查询财产去向、哪个部门砍伐的，是否是盗伐的，之前北京站前街也发生过类似的情况，希望核实，来电反映协调核实恭王府南门口东侧道北杨树被砍伐问题。市民反映，西城区恭王府南门口东侧道北有一颗近百年的杨树，被连根斩了，希望查询财产去向、哪个部门砍伐的，是否是盗伐的，之前北京站前街也发生过类似的情况，希望核实，来电反映协调核实恭王府南门口东侧道北杨树被砍伐问题。市民反映，西城区恭王府南门口东侧道北有一颗近百年的杨树，被连根斩了，希望查询财产去向、哪个部门砍伐的，是否是盗伐的，之前北京站前街也发生过类似的情况，希望核实，来电反映协调核实恭王府南门口东侧道北杨树被砍伐问题。市民反映，西城区恭王府南门口东侧道北有一颗近百年的杨树，被连根斩了，希望查询财产去向、哪个部门砍伐的，是否是盗伐的，之前北京站前街也发生过类似的情况，希望核实，来电反映协调核实恭王府南门口东侧道北杨树被砍伐问题。",
          "casepic": "https://test.jichengshanshui.com.cn:28310/yuanlin/alioss/yl/images/2025/09/08/af671146754be2596b65e87e544c481f.jpg",
          "dealuser": "xcyl严家齐巡查员",
          "dispatcher": "0",
          "dispperson": "368",
          "disppersonVo": "xcyl严家齐巡查员",
          "replyResult": null,
          "picResult1": null,
          "picResult2": null,
          "picResult3": null,
          "finishTime": null,
          "replayrtime": null,
          "ownercompany": null,
          "casetype": null,
          "handingresult": null,
          "resolvedesp": "是我的问题， 但就是不处理， 就这么着~！！！！！！",
          "rstResolvedesp": null,
          "dealBy": null,
          "dealTime": null,
          "replayBy": null,
          "replayTime": null,
          "ownershipBy": "xcyl",
          "ownershipTime": "2025-09-09 19:56:56",
          "reserve1": "1",
          "reserve2": null,
          "reserve3": null,
          "sysPhotoList": null
        }
        console.log(this.formData)
        console.log(this.pickerList[1])
        this.formData.streetName = largeData.streetVo
        this.formData.streetId = largeData.street
        this.getRoadList( this.formData.streetId)
        this.formData.lonLatAddress = largeData.address
        this.formData.remark = largeData.content
        this.formData.problemSourceName = '12345工单'
        this.formData.problemSourceId = 2
        this.formData.thirdWorkOrderNo = largeData.hotlinenumber

        const key = 'f8693f334fa04f3749677f4b4f13b286';
        // 高德地理编码API
        uni.request({
          url: 'https://restapi.amap.com/v3/geocode/geo',
          method: 'GET',
          data: {
            address: this.formData.lonLatAddress,  // 要解析的地址，如"北京市朝阳区光华路"
            key: key,          // 你的高德Key
            city: '北京'           // 可选，指定城市可提高解析精度
          },
          success: (res) => {
            const result = res.data;
            if (result.status === '1' && result.count > 0) {
              // 解析成功，获取经纬度
              const geocodes = result.geocodes[0];
              const location = geocodes.location.split(','); // 格式为"经度,纬度"
              const longitude = location[0];
              const latitude = location[1];
              this.formData.lon = longitude
              this.formData.lat = latitude

              console.log('解析成功：', {
                address: geocodes.formatted_address,
                longitude: longitude,
                latitude: latitude
              });
            } else {
              this.formData.lon = '116.364966'
              this.formData.lat = '39.920401'
              console.log('解析失败：', result.info || '未找到匹配地址');
            }
          },
          fail: (err) => {
            console.log('请求失败：', err);
          }
        });

        // this.formData.imgs = largeData.casepic
        if(largeData.casepic){
          let picData = largeData.casepic.replace(OSSURL, "")
          this.imgsValue = [picData]
          // this.formData.imgs.push({
          //   url: picData, // 接口返回的图片地址
          //   id: Date.now() // 用时间戳作为唯一标识
          // });
        }
      });
    }else{


    }
	},
	methods: {
		// 获取街道列表
		getStreetList() {
			apiStreetList().then(res => {
				this.pickerList[1] = res.data
			})
		},
		// 获取道路列表
		getRoadList(streetId) {
			apiRoadListByStreetId({data:{stree_id:streetId}}).then(res => {
				this.formData.roadId = ''
				this.formData.roadName = ''
				this.pickerList[2] = res.data
			})
		},
		// 获取组长列表
		getLeaderList() {
			apiLeaderList().then(res => {
				res.data.forEach(item => {item.id = item.userId})
				this.pickerList[3] = res.data
			})
		},
		// 获取问题来源列表
		getTypeList() {
			apiTypeList({data:{dict_type: 'problem_source'}}).then(res => {
				res.data.forEach(item => {
					item.id = item.value
					item.name = item.label
				})
				this.pickerList[4] = res.data
			})
		},
		// 打开选择框
		pickerOpen(type) {
			this.pickerShow = true
			this.pickerType = type
		},
		// 关闭选择框
		pickerHide() {
			this.pickerShow = false
		},
		// 选择选择框
		pickerChange(event) {
			switch (this.pickerType) {
				case 1:
					this.formData.streetId = event.id
					this.formData.streetName = event.name
					this.formData.roadId = 0
					this.formData.roadName = ''
					// 查询道路列表
					this.getRoadList(event.id)
					break
				case 2:
					this.formData.roadId = event.id
					this.formData.roadName = event.name
					break
				case 3:
					this.formData.leaderUserId = event.id
					this.formData.leaderUserName = event.name
					break
				case 4:
					this.formData.problemSourceId = event.id
					this.formData.problemSourceName = event.name
					break
			}
		},
		// 上传完成
		complete(e, type) {
			if (e.status == 1) {
        if(type == 'imgs'){
          // 直接添加新图，不删除默认图
          // this.imgsValue.push({
          //   url: event.url, // 接口返回的新图地址
          //   isDefault: false,
          //   id: Date.now() // 时间戳作为唯一标识
          // });
          this.imgsValue = e.imgArr
        }else{
          this.formData[type] = e.imgArr
        }

        console.log( this.formData[type])
      }
		},
		// 提交
		onSubmit() {
      if (this.isLoading) return;
			this.$refs.form.validate(this.formData, rules).then(res => {
				if (!res.isPass) {
					uni.$tui.toast(res.errorMsg)
					return
				}
        // 关键：提交所有图片（默认图 + 新图）
        // this.formData.imgs = this.imgsValue.map(item => item.url);
        this.formData.imgs = this.imgsValue
				if (!this.formData.imgs.length || !this.formData.streetImgList.length || !this.formData.longRangeImgList.length) {
					uni.$tui.toast('请上传图片')
					return
				}
				this.isLoading = true



				apiCaseAdd({data:{...this.formData}}).then(res => {
					uni.$tui.toast('提交成功')
          uni.navigateBack()
				}).finally(() => {
					this.isLoading = false
				})
			})
		},
		// 选择位置
		openMap() {
			var that = this
			uni.chooseLocation({
				success: function (res) {
					that.formData.lat = res.latitude
					that.formData.lon = res.longitude
					that.formData.lonLatAddress = res.address
				}
			})
		},
		// 选项卡
		tabChange(event) {
			this.currentIndex = event.index
		},
	}
}
</script>

<style lang="scss" scoped>

</style>
