<template>
  <div class="edit-add-detail">
    <div class="edit-add-detail-new-content">
      <div class="form-content">
        <el-form ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-position="left" label-suffix="："
                 label-width="135px">
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">巡查救援队伍信息</div>
            </div>
          </div>
          <el-row :gutter="24" style="margin-left: 80px">
            <el-col :span="8">
              <el-form-item label="所属路段" prop="orgName">
                <el-input v-model="addEditForm.orgName" :disabled="true" clearable
                          readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="队伍名称" prop="name">
                <el-input v-model="addEditForm.name" clearable placeholder="请输入队伍名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="队伍类型" prop="type">
                <el-radio-group v-model="addEditForm.type" size="medium">
                  <el-radio
                    v-for="(item, index) in filteredDwlx"
                    :key="index"
                    :label="item.value"
                    :value="item.value"
                    border
                  > {{ item.name }}
                  </el-radio>

                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-col :span="6">
            <el-form-item label="方向" prop="direction">
              <el-select v-model="addEditForm.direction" style="width: 100%" placeholder="方向">
                <el-option v-for="(item, index) in getDictionaryByCode(
                  'xsfx'
                )" :key="index" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="点位桩号全值" class="stake-mark" prop="pegVal">
              <div class="pegVal-text1">K</div>
              <el-input type="number" @blur="pileToPosition" clearable v-model="addEditForm.peg" placeholder="点位桩号"></el-input>
              <div class="pegVal-text2">+</div>
              <el-input type="number" @blur="pileToPosition" clearable v-model="addEditForm.pegAdd" placeholder="点位桩号附加"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="经度" prop="lng">
              <el-input clearable v-model="addEditForm.lng" placeholder="经度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="纬度" prop="lat">
              <el-input clearable v-model="addEditForm.lat" placeholder="纬度"></el-input>
            </el-form-item>
          </el-col> -->
          <!--          </el-row>-->
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="队伍负责人" prop="man">
                <el-input v-model="addEditForm.man" clearable placeholder="队伍负责人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="负责人联系电话" prop="tel">
                <el-input v-model="addEditForm.tel" clearable placeholder="负责人联系电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div slot="footer" class="footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>

    <!--  所在路段选择弹层  -->
    <RoadChoiceDialog :is-show.sync="roadChoiceDialog" :selected-content.sync="addEditForm.road"
                      @confirm="handleRoadSelect" />
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {
  getTree,
  tableAdd,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {getCascadeDictByCodeEvent, getDictionaryByCode} from '@/utils/dictionary'
import RoadChoiceDialog from './components/RoadChoiceDialog'
import {pieTolngAndLat} from '@/utils/pointConversion'

export default {
  name: 'EditAddPage',
  components: {RoadChoiceDialog},
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    const validateAccountTel = (text, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/

      if (phoneRegex.test(value)) {
        callback()
      } else {
        callback(new Error(`${text}需为11位手机号`))
      }
    }

    // const validatePegVal = (rule, value, callback) => {
    //   let {peg, pegAdd} = this.addEditForm
    //   if (!peg && !pegAdd) {
    //     return callback(new Error('桩号全值不能为空'))
    //   } else if (!peg || !pegAdd) {
    //     return callback(new Error('请填写完整桩号全值'))
    //   } else {
    //     return callback()
    //   }
    // }

    return {
      addEditForm: {
        type: '1',
        // direction: '1',
        road: {},
        orgId: '',
        orgName: '',
        orgFullId: '' // 新增 orgFullId 字段
      },
      filteredDwlx: [], // 用于存储过滤后的字典值
      roadChoiceDialog: false,
      addEditRules: {
        name: [
          {required: true, message: '队伍名称不能为空', trigger: ['change', 'blur']}
        ],
        code: [
          {required: true, message: '队伍编码不能为空', trigger: ['change', 'blur']}
        ],
        type: [
          {required: true, message: '队伍类型不能为空', trigger: ['change']}
        ],
        roadId: [
          {required: true, message: '队伍所在路段不能为空', trigger: ['change']}
        ],
        direction: [
          {required: true, message: '方向不能为空', trigger: ['change']}
        ],
        // pegVal: [
        //   {
        //     required: true,
        //     validator: validatePegVal,
        //     trigger: ['change', 'blur']
        //   }
        // ],
        tel: [
          {required: true, message: '手机号不能为空', trigger: ['change', 'blur']},
          {
            required: false,
            validator: (_, val, cb) => validateAccountTel('手机号', val, cb),
            trigger: ['change', 'blur']
          }
        ],

        'outCompany.outCompanyName': [
          {required: true, message: '外包公司不能为空', trigger: ['change', 'blur']}
        ],
        teamId: [
          {required: true, message: '救援队伍不能为空', trigger: ['change', 'blur']}
        ],
        man: [
          {required: true, message: '队伍负责人不能为空', trigger: ['change', 'blur']}
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null,
      outCompanyDialog: false, // 是否展示选择外包公司选择
      treeData: [] // 组织树
    }
  },
  computed: {
    postOpt() {
      // 获取级联字典
      return getCascadeDictByCodeEvent('rylx-xcjyry', this.addEditForm.type)
    }
  },
  watch: {
    componentName(newVal) {
      if (newVal === this.$options.name) {
        this.openPage()
      } else {
        this.closePage()
      }
    }
  },
  created() {
    this.getOrgTreeData()

  },
  mounted() {
    // 订阅 TreeItemSelected 事件
    this.pubSub = PubSub.subscribe('TreeItemSelected', (_, nodeItem) => {
      this.addEditForm.orgName = nodeItem?.name || ''
      this.addEditForm.orgId = nodeItem?.id || ''
      this.addEditForm.orgFullId = nodeItem?.path || '' // 更新 orgFullId
    })
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        // 新增模式
        if (data.orgName) {
          // 如果传递了 orgName，则使用传递的值
          this.addEditForm.orgName = data.orgName
          this.addEditForm.orgId = data.catalogId
          this.addEditForm.orgFullId = data.path || '' // 更新 orgFullId
        } else if (this.treeData.length > 0) {
          // 否则使用 treeData 中的默认值
          this.addEditForm.orgName = this.treeData[0]?.name || ''
          this.addEditForm.orgId = this.treeData[0]?.id || ''
          this.addEditForm.orgFullId = this.treeData[0]?.path || '' // 更新 orgFullId
        }
        const {id: orgId = '', path: orgFullId = ''} = data.treeItem || {}
        this.addEditForm = {
          ...this.addEditForm,
          orgId, orgFullId
        }
        console.log(this.addEditForm)

      }
    })
  },
  methods: {
    // 过滤字典值，只保留第一个
    filterDwlx() {
      const dwlx = this.getDictionaryByCode('dwlx')
      if (dwlx && dwlx.length > 0) {
        this.filteredDwlx = [dwlx[0]] // 只保留第一个值
      }
    },
    getDictionaryByCode,

    pileToPosition() {
      let {pegAdd, peg, direction: upDown, road} = this.addEditForm
      let stakeNum = Number(peg + '.' + pegAdd)
      if (pegAdd && peg) {
        pieTolngAndLat({routeCode: road.roadCode, stakeNum: Number(stakeNum), upDown, pointType: '02'}).then(res => {
          if (res.state) {
            let data = JSON.parse(res.value)
            this.$set(this.addEditForm, 'lng', data.lon)
            this.$set(this.addEditForm, 'lat', data.lat)
          }
        })
      }
    },
    // 打开页面执行
    openPage() {
      // this.typeChange()
      this.filterDwlx() // 过滤字典值
    },
    handleRoadSelect(road) {
      this.$set(this.addEditForm, 'roadId', road.roadId)
    },
    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules, treeData} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {pubSub, addEditRules, treeData})

      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      this.addEditForm = await tableDetail(id)
      const {roadCode = '', roadId = '', roadName = '', pegVal = ''} = this.addEditForm
      this.addEditForm.road = {
        roadCode,
        roadId,
        roadName
      }
      if (pegVal) {
        let startPegArr = pegVal.split('+')
        this.$set(this.addEditForm, 'peg', startPegArr[0].slice(1))
        this.$set(this.addEditForm, 'pegAdd', startPegArr[1])
      } else {
        this.$set(this.addEditForm, 'peg', '')
        this.$set(this.addEditForm, 'pegAdd', '')
      }
    },

    // 获取公司树
    async getOrgTreeData() {
      let {value} = await getTree()
      this.treeData = value
    },

    // 点位类型发生变化
    typeChange() {
      // 当表单中点位类型发生改变的时候，赋值内容字典中的第一项字典值给表单中内容字段
      this.addEditForm.post = this.postOpt[0]?.value || ''
    },

    // // 巡查队伍切换
    // teamIdChange() {
    //   this.addEditForm.teamFullId = this.$refs.cascader?.getCheckedNodes()[0]?.data?.path || ''
    // },

    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? tableEdit : tableAdd
          let data = JSON.parse(JSON.stringify(this.addEditForm))
          if (data.peg && data.pegAdd) {
            data.pegVal = 'k' + (data.peg || '') + '+' + (data.pegAdd || '')
          }
          try {
            let {state, message} = await myInterFace({
              ...data,
              ...data.road,
              ...this.addEditForm,
              orgFullId: this.addEditForm.orgFullId // 确保 orgFullId 被传递
            })

            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`巡查救援队伍信息${message}成功`)
              // 发布事件，通知表格页面刷新数据
              PubSub.publish('TablePage', {type: 'add'})
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";

.edit-add-detail {
  .edit-add-detail-new-content {
    width: 100%;
    display: flex;
    height: 0;
    flex: 1;
    column-gap: 20px;

    .form-content {
      flex: 1;
    }
  }

  .stake-mark {
    ::v-deep .el-form-item__content {
      display: flex;
      justify-content: space-between;

      .pegVal-text2,
      .pegVal-text1 {
        padding-right: 10px;
        font-size: 16px;
        width: fit-content;
      }

      .pegVal-text2 {
        padding-left: 10px;
        font-size: 24px;
      }
    }
  }
}
</style>
