<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-row :gutter="24"  style="margin-left: 80px">
            <el-col :span="8">
                <el-form-item label="附件" prop="files">
                    <el-upload
                        :data="{
                            file: JSON.stringify({storeType: 'minio'}),
                        }"
                        name="files"
                        :action="actionUrl + '/file/v1/fileUpload'"
                        :before-upload="beforeUpload"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :on-preview="handlePreview"
                        :before-remove="beforeRemove"
                        :on-remove="handleRemove"
                        :multiple="true"
                        :headers="headers"
                        :file-list="addEditForm.filesArr"
                        ref="upload"
                    >
                        <el-button size="small" type="primary"
                            >点击上传</el-button
                        >
                        <span slot="tip" class="el-upload__tip">
                            请上传PDF格式的文件
                        </span>
                    </el-upload>
                </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'
import {mapState} from 'vuex'

export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      addEditForm: {
        orgId: '',
        orgName: '',
        orgFullId: '', // 新增 orgFullId 字段
        files: [],
      },
      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()
  },
  computed: {
        actionUrl: (_) => window.context.portal,
        previewUrl: (_) =>
            window.context.portal +
            '/file/onlinePreviewController/v1/getFileById_',
        downloadUrl: (_) =>
            window.context.portal + '/file/v1/downloadFile?fileId=',
        ...mapState({
            headers: (state) => ({
                Authorization: `Bearer ${state.login.currentUser.token}`,
            }),
        }),
    },
  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: '',
            files: [],
            filesArr: [],
          }
        }
        // 新增模式
        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: '',
        files: [],
      }
      // 重置组件数据
      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 {files=[],...addEditForm } = await tableDetail(id)
      this.addEditForm = {
        ...addEditForm,
        files,
        filesArr: files.map((i) => ({
            ...i,
            fileId: i.id,
            name: i.fileName,
        })),
      }
    },

    // 保存
    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})
      })
    },
    // 文件上传前
    beforeUpload(file) {
      this.saveLoading = true
      const {type} = file
      if (type !== 'application/pdf' ) {
          this.$message.warning('请上传PDF文件')
          setTimeout((_) => (this.saveLoading = false), 0)
          return false
      }
    },
    // 文化上传成功
    handleSuccess(response) {
      const {
          fileId:id = '',
          fileName = '',
          size: fileSizes = 0,
          success,
      } = response
      if (success) {
          this.addEditForm.files.push({id, fileName})
      } else {
          this.$message.error('文件上传失败')
      }
      this.saveLoading = false
    },
    // 文件上传失败
    handleError() {
      this.$message.warning('文件上传失败')
    },
    // 文件删除前
    beforeRemove(file) {
      return new Promise((resolve, reject) => {
          this.$confirm(`确定移除${file.name}吗？`, '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
          })
              .then((_) => {
                  resolve()
              })
              .catch((_) => reject())
      })
    },
    // 文件删除后
    handleRemove(file) {
      const fileId = file.id || file.response.fileId || ''
      const index = this.addEditForm.files.findIndex(
          (i) => i.id === fileId
      )
      if (index !== -1) this.addEditForm.files.splice(index, 1)
    },

    // 已上传文件点击
    async handlePreview(file) {
      const fileId = file.id || file.response.fileId || '' // 文件ID
      const fileExt = file.extensionName || file.response.fileExt || '' // 扩展名
      if (!(fileId && fileExt))
          return this.$message.warning('文件错误，请删除后重新上传')
      const browserOperablePattern = /pdf$/i
      
      if (browserOperablePattern.test(fileExt.replace(/\./, ''))) {
          window.open(this.previewUrl + fileId, '_blank')
      } else {
          window.open(this.downloadUrl + fileId, '_blank')
      }
    },
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.el-upload__tip{
  color: #f5963d;
  margin-left: 10px;
}</style>
