<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-position="left" 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="margin-left: 80px">
          <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="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="公司简称" prop="shortName">
              <el-input v-model="addEditForm.shortName" clearable placeholder="请输入公司简称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <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="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="公司营业执照编码" prop="code">
              <el-input v-model="addEditForm.code" clearable placeholder="请输入公司营业执照编码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <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="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="公司地址" prop="address">
              <el-input v-model="addEditForm.address" clearable placeholder="公司地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </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 {
  orgTree,
  tableAdd,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/outsourcingCompanyMgmt'


export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      addEditForm: {
        orgId: '',
        orgName: '',
        orgFullId: '' // 新增 orgFullId 字段
      },
      addEditRules: {
        name: [
          {required: true, message: '公司全称不能为空', trigger: 'blur'}
        ],
        man: [
          {required: true, message: '公司法人不能为空', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '公司营业执照编码不能为空', trigger: 'blur'},
          {
            pattern: /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/,
            message: '公司营业执照编码输入格式有误',
            trigger: 'blur'
          }
        ],
        tel: [
          {required: true, message: '公司联系电话不能为空', trigger: 'blur'},
          {
            pattern: /\d{3}-\d{8}|\d{4}-\d{7}|^1(3[0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\d{8}$/,
            message: '公司联系电话输入有误',
            trigger: 'blur'
          }
        ],
        address: [
          {required: true, message: '公司地址不能为空', trigger: 'blur'}
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null,
      treeData: []
    }
  },
  created() {
    // this.getOrgTreeData()
  },
  mounted() {
    // 订阅 TreeItemSelected 事件
    this.pubSub = PubSub.subscribe('TreeItemSelected', (_, nodeItem) => {
      this.addEditForm.orgName = nodeItem?.name || ''
      // console.log(this.addEditForm.orgName, '点击的名字')
      this.addEditForm.orgId = nodeItem?.id || ''
      this.addEditForm.orgFullId = nodeItem?.path || '' // 更新 orgFullId

    })

    // 原有的事件订阅
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      console.log(data, '9999')
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        // 新增模式
        if (data.clearForm) {
          // 清空表单数据
          this.addEditForm = {
            orgId: '',
            orgName: '',
            orgFullId: '',
            name: '',
            shortName: '',
            man: '',
            code: '',
            tel: '',
            address: ''
          }
        }
        // 新增模式
        this.addEditForm.orgName = data.orgName
        this.addEditForm.orgId = data.catalogId
        this.addEditForm.orgFullId = data.path || '' // 更新 orgFullId
      }
    })
  },
  methods: {
    // orgIdChange() {
    //   this.addEditForm.orgFullId = this.$refs.cascader?.getCheckedNodes()[0]?.data?.path || ''
    //   this.addEditForm.orgId = this.$refs.cascader?.getCheckedNodes()[0]?.value || ''
    //   this.addEditForm.orgName = this.$refs.cascader?.getCheckedNodes()[0]?.label || ''
    // },
    // 获取公司树
    async getOrgTreeData() {
      let {value} = await orgTree()  // 调用 API 获取树形数据
      this.treeData = value
      // 确保 treeData 数据加载完成后再设置初始值
      if (this.treeData.length > 0) {
        this.addEditForm.orgName = this.treeData[0]?.name || ''
        this.addEditForm.orgId = this.treeData[0]?.id || ''
      }
    },

    // 关闭页面执行
    closePage() {
      // 清空表单数据
      this.addEditForm = {
        orgId: '',
        orgName: '',
        orgFullId: '',
        name: '',
        shortName: '',
        man: '',
        code: '',
        tel: '',
        address: ''
      }
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {pubSub: this.pubSub})
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      const {...addEditForm} = await tableDetail(id)
      this.addEditForm = {
        ...addEditForm
      }
    },

    // 保存
    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
          try {
            let {state, message} = await myInterFace({
              ...this.addEditForm,
              orgFullId: this.addEditForm.orgFullId // 确保 orgFullId 被传递
            })
            if (state) {
              message = this.id ? '修改' : '新增'
              this.$message.success(`外包公司信息${message}成功`)
              // 清空表单数据
              this.addEditForm = {
                orgId: '',
                orgName: '',
                orgFullId: '',
                name: '',
                shortName: '',
                man: '',
                code: '',
                tel: '',
                address: ''
              }
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      // 清空表单数据
      this.addEditForm = {
        orgId: '',
        orgName: '',
        orgFullId: '',
        name: '',
        shortName: '',
        man: '',
        code: '',
        tel: '',
        address: ''
      }
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped></style>
