<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="145px">
          <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="roadName">
                <el-input v-model="addEditForm.roadName" :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-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-row :gutter="24" style="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item class="stake-mark" label="管辖范围开始桩号">
                <div class="pegVal-text1">K</div>
                <el-input
                  v-model="addEditForm.startPeg"
                  clearable
                  type="number"
                ></el-input>
                <div class="pegVal-text2">+</div>
                <el-input
                  v-model="addEditForm.startPegAdd"
                  clearable
                  type="number"
                ></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 class="stake-mark" label="管辖范围结束桩号">
                <div class="pegVal-text1">K</div>
                <el-input
                  v-model="addEditForm.endPeg"
                  clearable
                  type="number"
                ></el-input>
                <div class="pegVal-text2">+</div>
                <el-input
                  v-model="addEditForm.endPegAdd"
                  clearable
                  type="number"
                ></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>

  </div>
</template>

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

export default {
  name: 'EditAddPage',
  components: {},
  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位手机号`))
      }
    }
    return {
      addEditForm: {
        type: '1',
        roadName: '',
        roadFullId: ''
      },
      filteredDwlx: [], // 用于存储过滤后的字典值
      roadChoiceDialog: false,
      addEditRules: {
        name: [
          {required: true, message: '队伍名称不能为空', trigger: ['change', 'blur']}
        ],
        type: [
          {required: true, message: '队伍类型不能为空', trigger: ['change']}
        ],

        tel: [
          {required: true, message: '手机号不能为空', trigger: ['change', 'blur']},
          {
            required: false,
            validator: (_, val, cb) => validateAccountTel('手机号', val, cb),
            trigger: ['change', 'blur']
          }
        ],

        man: [
          {required: true, message: '队伍负责人不能为空', trigger: ['change', 'blur']}
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null,
      treeData: [] // 组织树
    }
  },
  computed: {},
  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.roadName = nodeItem?.name || ''
      this.addEditForm.roadId = nodeItem?.id || ''
      this.addEditForm.roadFullId = nodeItem?.path || ''
    })
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        if (data.roadName) {
          // 如果传递了 orgName，则使用传递的值
          this.addEditForm.roadName = data.roadName
          this.addEditForm.roadId = data.catalogId
          this.addEditForm.roadFullId = data.path || '' // 更新 orgFullId
        } else if (this.treeData.length > 0) {
          // 否则使用 treeData 中的默认值
          this.addEditForm.roadName = this.treeData[0]?.name || ''
          this.addEditForm.roadId = this.treeData[0]?.id || ''
          this.addEditForm.roadFullId = this.treeData[0]?.path || '' // 更新 orgFullId
        }
      }
    })
  },
  methods: {
    // 过滤字典值，只保留第一个
    filterDwlx() {
      const dwlx = this.getDictionaryByCode('dwlx')
      if (dwlx && dwlx.length > 0) {
        this.filteredDwlx = [dwlx[0]] // 只保留第一个值
        this.addEditForm.type = dwlx[0].value // 设置默认值
      }
    },
    getDictionaryByCode,
    // 获取公司树
    async getOrgTreeData() {
      let {value} = await getTree()
      this.treeData = value
    },
    // 打开页面执行
    openPage() {
      // this.typeChange()
      this.filterDwlx() // 过滤字典值
    },

    // 关闭页面执行
    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) {
      const response = await tableDetail(id)
      this.addEditForm = {
        ...response,
        roadName: response.roadName || this.addEditForm.roadName // 如果接口返回的 orgName 为空，使用当前表单的 orgName
      }
      const {
        pegSVal,
        pegEVal
      } = this.addEditForm
      if (pegSVal) {
        let startPegArr = pegSVal.split('+')
        this.$set(this.addEditForm, 'startPeg', startPegArr[0].slice(1))
        this.$set(this.addEditForm, 'startPegAdd', startPegArr[1])
      }
      if (pegEVal) {
        let endPegArr = pegEVal.split('+')
        this.$set(this.addEditForm, 'endPeg', endPegArr[0].slice(1))
        this.$set(this.addEditForm, 'endPegAdd', endPegArr[1])
      }
    },

    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          const {
            startPeg,
            startPegAdd,
            endPeg,
            endPegAdd
          } = this.addEditForm
          let pegSVal = ''
          let pegEVal = ''
          if ((startPeg !== '' && startPeg !== undefined) && (startPegAdd !== '' && startPegAdd !== undefined)) {
            pegSVal = 'k' + (startPeg !== '' ? startPeg : '') + '+' + (startPegAdd !== '' ? startPegAdd : '')
          }
          if ((endPeg !== '' && endPeg !== undefined) && (endPegAdd !== '' && endPegAdd !== undefined)) {
            pegEVal = 'k' + (endPeg !== '' ? endPeg : '') + '+' + (endPegAdd !== '' ? endPegAdd : '')
          }
          this.saveLoading = true
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            const response = await myInterFace({
              ...this.addEditForm,
              pegSVal,
              pegEVal,
              roadId: this.addEditForm.roadId, // 传递 orgId
              roadName: this.addEditForm.roadName, // 传递 orgName
              roadFullId: this.addEditForm.roadFullId,// 传递 roadFullId
              type: this.addEditForm.type // 传递队伍类型的 value
            })
            const {state, message} = response
            if (state) {
              const action = this.id ? '编辑' : '新增'
              this.$message.success(`巡查救援队伍信息${action}成功`)
              // 手动将 orgName 添加到返回的数据中
              // data.orgName = this.addEditForm.orgName
              // 发布事件，通知表格页面刷新数据
              PubSub.publish('TablePage', {type: this.id ? 'edit' : 'add'})
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },


    // 改变页面
    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>
