<template>
  <div class="edit-add-detail">
    <div class="form-content">
    </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 {refineRequestBody} from '@/utils/requestWrappers'
import {
  getTree,
  tableAdd,
  tableDetail,
  tableEdit,
  verifyCarNumber
} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/bindUser'

import {getDictionaryByCode} from '@/utils/dictionary'

// 图片上传
import imgDialog from './components/imgDialog'

import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {tableData as rescuePointData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/rescueSiteMgmt'

export default {
  name: 'EditAddPage',
  components: {
    imgDialog
  },
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
    this.getOrgTreeData()
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      console.log(data.roadName, '/////////////////////')
      if (data.roadName !== '') {
        this.addEditForm.roadName = data?.roadName || ''
        this.addEditForm.roadId = data?.catalogId || ''
        this.addEditForm.roadFullId = data?.path || ''
      }
      console.log(this.addEditForm.roadName, 'cascascasc')
      console.log(this.addEditForm.roadId, 'cascascasc111')
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        this.getRoadData()
      }
    })
  },
  methods: {
    //获取所在路段列表数据
    async getRoadData(value) {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map(item => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      if (!this.id) {
        // this.$set(this.addEditForm, 'roadId', this.roadOptions[0].id)
        this.roadChange(this.roadOptions[0].id)
      } else {
        this.roadChange(value)
      }
    },
    roadChange(value) {
      this.getTeamData(value)
      this.getRescuePointData(value)
    },
    // 通过路段信息获取巡查救援队伍信息
    async getTeamData(value) {
      this.addEditForm.teamId = ''
      const {rows = []} = await teamData(refineRequestBody({
        querys: [{operation: 'IN', property: 'r.id_', value}]
      }), 'addEdit')
      this.teamOptions = rows
    },
    // 根据路段查询救援点
    async getRescuePointData(value) {
      const {rows = []} = await rescuePointData(refineRequestBody({
        querys: [{operation: 'IN', property: 'road_id_', value}]
      }), 'addEdit')
      this.rescuePointOptions = rows
    },
    teamIdChange() {
      this.addEditForm.teamFullId = this.$refs.cascader?.getCheckedNodes()[0]?.data?.path || ''
      this.addEditForm.teamId = this.$refs.cascader?.getCheckedNodes()[0]?.value || ''
    },
    // 获取公司树
    async getOrgTreeData() {
      this.treeData = await getTree()
    },
    async blurCheckout(e) {
      let id = this.addEditForm.id || ''
      const {state} = await verifyCarNumber({id, carNumber: e.target.value})
      this.isCarNamber = !state
    },
    updateFile(url, type) {
      this.$set(this.addEditForm, type, url)
    },
    getDictionaryByCode,
    // 打开页面执行
    openPage() {
    },
    // 关闭页面执行
    closePage() {
      const {roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {pubSub: this.pubSub, roadOptions})
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
        this.$refs.upload?.clearFiles()
      })
    },

    // 获取详情
    async getDetail(id) {
      const {policyFiles = [], roadId = '', ...addEditForm} = await tableDetail(id)
      this.addEditForm = {
        ...addEditForm,
        roadId,
        policyFiles,
        roadName: addEditForm.roadName || this.addEditForm.roadName,// 如果接口返回的 orgName 为空，使用当前表单的 orgName，
        policyFilesArr: policyFiles.map(i => ({
          ...i, name: i.fileName
        }))
      }
      if (this.roadOptions.length) {
        this.roadChange(roadId)
      } else {
        this.getRoadData(roadId)
      }
    },


    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          if (!this.isCarNamber) {
            this.saveLoading = true
            const myInterFace = this.id ? tableEdit : tableAdd
            try {
              const response = await myInterFace({
                ...this.addEditForm,
                roadId: this.addEditForm.roadId, // 传递 orgId
                roadName: this.addEditForm.roadName, // 传递 orgName
                roadFullId: this.addEditForm.roadFullId,// 传递 roadFullId
                type: this.addEditForm.type, // 传递队伍类型的 value
                useType: Number(this.addEditForm.useType),
                carClass: Number(this.addEditForm.carClass)
              })
              console.log(this.addEditForm.roadId, '1111222221111')
              const {state, message} = response
              if (state) {
                const action = this.id ? '编辑' : '新增'
                this.$message.success(`${action}成功`)
                PubSub.publish('TablePage', {type: this.id ? 'edit' : 'add'})
                // 调用 changePage 方法，传递正确的参数
                this.changePage('TablePage', this.id ? 'edit' : 'add')
              }
            } finally {
              this.saveLoading = false
            }
          } else {
            this.$message.error('车牌号已存在，请重新录入')
          }
        }
      })

    },

    // 展示弹层
    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";

.form-content {
  height: 0;
}

</style>
