<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="120px">
          <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 v-if="id" :span="8">
              <el-form-item label="账号名" prop="account">
                <el-input v-model="addEditForm.account" clearable disabled 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="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="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 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="flex-wrap: wrap;margin-left: 80px" type="flex">
            <el-col :span="8">
              <el-form-item label="是否外派人员" prop="isOut">
                <el-radio-group v-model="addEditForm.isOut" size="medium">
                  <el-radio-button v-for="(item, index) in getDictionaryByCode('sfpj')" :key="index"
                                   :label="item.value">
                    {{ item.name }}
                  </el-radio-button>
                </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 v-if="addEditForm.isOut === '1'" :span="6">
              <el-form-item label="外包公司" prop="outCompanyId">
                <el-select v-model="addEditForm.outCompanyId" filterable placeholder="请选择外包公司"
                >
                  <el-option v-for="item in companyOptions" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </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="post">
                <el-select v-model="addEditForm.post" placeholder="请选择人员职务" style="width: 100%">
                  <el-option v-for="item in postOpt" :key="item.value" :label="item.name" :value="item.value">
                  </el-option>
                </el-select>
              </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 {
  tableAdd,
  tableDetail,
  tableEdit
} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescuePersonnelMgmt'
import {getCascadeDictByCodeEvent, getDictionaryByCode} from '@/utils/dictionary'
import {orgTree} from '@/api/systemInterface'
import {tableData as teamData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueTeamsMgmt'
import {companyData} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/outsourcingCompanyMgmt'

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位手机号`))
      }
    }

    const validateCode = (_, value, callback) => {
      const idCardRegex = /^(?:\d{15}|\d{17}[\dXx])$/

      if (idCardRegex.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的身份证号'))
      }
    }

    return {
      addEditForm: {
        type: '0',
        post: '',
        isOut: '1',
        roadId: '',
        roadName: '',
        roadFullId: ''
      },
      filteredDwlx: [], // 用于存储过滤后的字典值
      addEditRules: {
        account: [
          {required: true, message: '账号名不能为空', trigger: ['change', 'blur']},
          {
            required: false,
            validator: (_, val, cb) => validateAccountTel('账号名', val, cb),
            trigger: ['change', 'blur']
          }
        ],
        tel: [
          {required: true, message: '手机号不能为空', trigger: ['change', 'blur']},
          {
            required: false,
            validator: (_, val, cb) => validateAccountTel('手机号', val, cb),
            trigger: ['change', 'blur']
          }
        ],
        code: [
          {required: true, message: '身份证号不能为空', trigger: ['change', 'blur']},
          {required: false, validator: validateCode, trigger: ['change', 'blur']}
        ],
        name: [
          {required: true, message: '队员姓名不能为空', trigger: ['change', 'blur']}
        ],
        outCompanyId: [
          {required: true, message: '外包公司不能为空', trigger: ['change', 'blur']}
        ],
        type: [
          {required: true, message: '人员类型不能为空', trigger: ['change', 'blur']}
        ],
        post: [
          {required: true, message: '人员职务不能为空', trigger: ['change', 'blur']}
        ],
        teamId: [
          {required: true, message: '所属队伍不能为空', trigger: ['blur']}
        ],
        isOut: [
          {required: true, message: '是否外派人员不能为空', trigger: ['change']}
        ]
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      pubSub: null,
      outCompanyDialog: false, // 是否展示选择外包公司选择
      treeData: [], // 组织树
      teamOptions: [],
      companyOptions: []
    }
  },
  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.treePubSub = PubSub.subscribe('TreeItemSelected', (_, data) => {
      this.addEditForm.roadId = data.id
      this.addEditForm.roadName = data.name
      this.addEditForm.roadFullId = data.path
      this.addEditForm.orgId = data.orgId
    })
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      console.log(data, '999999999999')
      if (data.treeItem) {
        this.addEditForm.roadName = data.treeItem.name
        this.addEditForm.roadId = data.treeItem.id
        this.addEditForm.orgId = data.treeItem.orgId
        // this.addEditForm.roadFullId = data.treeItem.id
      }
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        this.addEditForm = {
          ...this.addEditForm,
          roadId: data.roadId || data.treeItem?.id || '', // 确保 teamId 被正确赋值
          roadName: data.roadName || data.treeItem?.name || '',// 确保 roadName 被正确赋值
          orgId: data.orgId || data.treeItem?.orgId || '' // 确保 roadName 被正确赋值
        }
      }
    })

    this.getTeamData()

  },
  methods: {
    // 过滤字典值，只保留第一个
    filterDwlx() {
      const dwlx = this.getDictionaryByCode('rylx-xcjyry')
      if (dwlx && dwlx.length > 0) {
        this.filteredDwlx = [dwlx[0]] // 只保留第一个值
        this.addEditForm.type = dwlx[0].value // 设置默认值
      }
    },
    getDictionaryByCode,

    //外包公司查询
    async getCompanyData() {
      const {rows = []} = await companyData()
      this.companyOptions = rows
      console.log(rows, '外包公司')
    },

    // 通过路段信息获取巡查救援队伍信息
    async getTeamData() {
      const {rows = []} = await teamData()
      this.teamOptions = rows

    },

    // 打开页面执行
    openPage() {
      this.typeChange()
      this.filterDwlx() // 过滤字典值
      this.getCompanyData()
    },

    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules, treeData, teamOptions, companyOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules,
        treeData,
        teamOptions,
        companyOptions
      })

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

    // 获取详情
    async getDetail(id) {
      let {post = '', ...addEditForm} = await tableDetail(id)
      const oldPost = post  // 保持详情原始post内容，避免因表单赋值后触发typeChange事件而丢失post的值
      this.addEditForm = {
        ...addEditForm,
        post,
        roadName: addEditForm.roadName || this.addEditForm.roadName // 确保 roadName 被赋值
      }
      this.addEditForm.post = oldPost
    },

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

    // 点位类型发生变化
    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

          if(this.addEditForm.isOut === '0') {
            this.addEditForm.outCompanyId = ''
            this.addEditForm.outCompanyName = ''
          }

          const {
           account = '', tel = '',  roadId = '', orgId = '', roadName = '',
            ...addEditForm
          } = this.addEditForm

          try {
            let {state, message} = await myInterFace({
              ...addEditForm,
              tel,
              account,
              roadId,
              orgId,
              roadName
            })

            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`巡查人员${message}成功`)
              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.treePubSub) // 新增取消订阅
    // 在组件销毁之前 清除订阅消息
    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;
    }
  }
}

</style>
