<template>
  <div class="comprehensive-center-form">
    <div class="form-header">
      <h2>{{ formType === 'add' ? '新增' : '编辑' }}综治中心规范化建设运行情况表</h2>
    </div>

    <Form
      ref="formValidate"
      :model="formData"
      :rules="rules"
      :label-width="180"
      style="padding: 20px;"
    >
      <!-- 1. 场所设置 -->
      <div class="form-section">
        <h3 class="section-title">1. 场所设置</h3>

        <FormItem label="面积（平方米）：" prop="square_measure">
          <InputNumber
            v-model="formData.square_measure"
            :min="0"
            :precision="0"
            style="width: 200px;"
            placeholder="请输入面积"
          />
        </FormItem>

        <FormItem label="场所选址：" prop="construction_selection">
          <RadioGroup v-model="formData.construction_selection" @on-change="handleConstructionSelectionChange">
            <Radio
              v-for="item in constructionSelectionOptions"
              :key="item.value"
              :label="item.value"
            >{{ item.label }}
            </Radio>
          </RadioGroup>
        </FormItem>

        <FormItem
          v-if="isOtherConstructionSelection"
          label="其他选项："
          prop="locationOther"
        >
          <Select v-model="formData.locationOther" style="width: 300px;" placeholder="请选择">
            <Option v-for="item in locationOtherOptions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>

        <FormItem label="功能布局：" prop="functional_layout">
          <CheckboxGroup v-model="formData.functional_layout">
            <Checkbox
              v-for="item in functionalLayoutOptions"
              :key="item.value"
              :label="item.value"
            >{{ item.label }}
            </Checkbox>
          </CheckboxGroup>
        </FormItem>
      </div>

      <!-- 2. 机构编制 -->
      <div class="form-section">
        <h3 class="section-title">2. 机构编制</h3>

        <FormItem label="有无机构编制：" prop="institutional_staffing">
          <RadioGroup v-model="formData.institutional_staffing" @on-change="handleInstitutionChange">
            <Radio label="1">有</Radio>
            <Radio label="2">无</Radio>
          </RadioGroup>
        </FormItem>

        <template v-if="formData.institutional_staffing === '1'">
          <FormItem label="单位级别：" prop="unit_level">
            <Select v-model="formData.unit_level" style="width: 200px;" placeholder="请选择">
              <Option value="股级">股级</Option>
              <Option value="副科级">副科级</Option>
              <Option value="正科级">正科级</Option>
              <Option value="副处级">副处级</Option>
              <Option value="正处级">正处级</Option>
            </Select>
          </FormItem>

          <FormItem label="编制人数：" prop="authorized_strength">
            <InputNumber
              v-model="formData.authorized_strength"
              :min="0"
              :precision="0"
              style="width: 200px;"
              placeholder="请输入编制人数"
            />
          </FormItem>

          <FormItem label="实有人数：" prop="actual_number">
            <InputNumber
              v-model="formData.actual_number"
              :min="0"
              :max="formData.authorized_strength"
              :precision="0"
              style="width: 200px;"
              placeholder="请输入实有人数"
            />
            <span style="color: #999; margin-left: 10px;">实有人数≤编制人数</span>
          </FormItem>
        </template>
      </div>

      <!-- 3. 入驻情况 -->
      <div class="form-section">
        <h3 class="section-title">3. 入驻情况</h3>

        <!-- 多中心入驻情况 -->
        <div class="subsection">
          <h4 class="subsection-title">多中心入驻情况</h4>

          <FormItem label="公共法律服务中心（法律援助中心）：" prop="public_legal">
            <RadioGroup v-model="formData.public_legal">
              <Radio label="1">整体</Radio>
              <Radio label="2">派员</Radio>
              <Radio label="3">未入驻</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="信访接待中心：" prop="reception_center">
            <RadioGroup v-model="formData.reception_center">
              <Radio label="1">整体</Radio>
              <Radio label="2">派员</Radio>
              <Radio label="3">未入驻</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="诉讼服务中心：" prop="lawsuit">
            <RadioGroup v-model="formData.lawsuit">
              <Radio label="1">整体</Radio>
              <Radio label="2">派员</Radio>
              <Radio label="3">未入驻</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="检察服务中心：" prop="procuratorial">
            <RadioGroup v-model="formData.procuratorial">
              <Radio label="1">整体</Radio>
              <Radio label="2">派员</Radio>
              <Radio label="3">未入驻</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="其他：" prop="multicenter_other_type">
            <RadioGroup v-model="formData.multicenter_other_type" @on-change="handleMulticenterOtherFlagChange">
              <Radio label="1">有</Radio>
              <Radio label="2">无</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            v-if="formData.multicenter_other_type === '1'"
            label="其他选项："
            prop="multicenter_other"
          >
            <RadioGroup v-model="formData.multicenter_other">
              <Radio
                v-for="item in multicenterOtherDictOptions"
                :key="item.value || item.label"
                :label="item.value || item.label"
              >{{ item.label }}
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            v-if="formData.multicenter_other_type === '1' && formData.multicenter_other"
            label="入驻状态："
            prop="multicenter_other_number"
          >
            <RadioGroup v-model="formData.multicenter_other_number" >
              <Radio label="1">整体</Radio>
              <Radio label="2">派员</Radio>
              <Radio label="3">未入驻</Radio>
            </RadioGroup>
          </FormItem>
        </div>

        <!-- 常驻部门和单位 -->
        <div class="subsection">
          <h4 class="subsection-title">常驻部门和单位</h4>

          <div
            v-for="item in residentDepartments"
            :key="item.valueKey"
            class="department-row"
          >
            <FormItem :key="item.valueKey" :label="item.name + '：'" :prop="item.valueKey">
              <RadioGroup v-model="formData[item.valueKey]"
                          @on-change="(val) => handleResidentChange(item.countKey, val)">
                <Radio label="1">入驻</Radio>
                <Radio label="2">未入驻</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem
              v-if="formData[item.valueKey] === '1'"
              :key="item.countKey"
              :label="item.name + '人数：'"
              :prop="item.countKey"
            >
              <InputNumber
                v-model="formData[item.countKey]"
                :min="0"
                :precision="0"
                style="width: 200px;"
                placeholder="请输入人数"
              />
            </FormItem>
          </div>

          <FormItem label="其他：" prop="resident_department_other">
            <RadioGroup v-model="formData.resident_department_other" @on-change="handleResidentOtherChange">
              <Radio label="1">有</Radio>
              <Radio label="2">无</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem
            v-if="formData.resident_department_other === '1'"
            label="其他选项："
            prop="residentOtherOptions"
          >
            <RadioGroup v-model="formData.residentOtherOptions">
              <Radio
                v-for="item in residentOtherDictOptions"
                :key="item.value || item.label"
                :label="item.value || item.label"
              >{{ item.label }}
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            v-if="formData.resident_department_other === '1' && formData.residentOtherOptions"
            label="入驻人数："
            prop="resident_department_other_settle_number"
          >
            <InputNumber
              v-model="formData.resident_department_other_settle_number"
              :min="0"
              :precision="0"
              style="width: 200px;"
              placeholder="请输入人数"
            />
          </FormItem>
        </div>

        <!-- 轮驻部门和单位 -->
        <div class="subsection">
          <h4 class="subsection-title">轮驻部门和单位</h4>

          <div
            v-for="item in rotatingDepartments"
            :key="item.valueKey"
            class="department-row"
          >
            <FormItem :key="item.valueKey" :label="item.name + '：'" :prop="item.valueKey">
              <RadioGroup v-model="formData[item.valueKey]"
                          @on-change="(val) => handleRotatingChange(item.countKey, val)">
                <Radio label="1">入驻</Radio>
                <Radio label="2">未入驻</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem
              v-if="formData[item.valueKey] === '1'"
              :key="item.countKey"
              :label="item.name + '人数：'"
              :prop="item.countKey"
            >
              <InputNumber
                v-model="formData[item.countKey]"
                :min="0"
                :precision="0"
                style="width: 200px;"
                placeholder="请输入人数"
              />
            </FormItem>
          </div>

          <FormItem label="其他：" prop="rotating_department_other">
            <RadioGroup v-model="formData.rotating_department_other" @on-change="handleRotatingOtherChange">
              <Radio label="1">有</Radio>
              <Radio label="2">无</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem
            v-if="formData.rotating_department_other === '1'"
            label="其他选项："
            prop="rotatingOtherOptions"
          >
            <RadioGroup v-model="formData.rotatingOtherOptions">
              <Radio
                v-for="item in rotatingOtherDictOptions"
                :key="item.value || item.label"
                :label="item.value || item.label"
              >{{ item.label }}
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            v-if="formData.rotating_department_other === '1' && formData.rotatingOtherOptions"
            label="入驻人数："
            prop="rotating_department_other_settle_number"
          >
            <InputNumber
              v-model="formData.rotating_department_other_settle_number"
              :min="0"
              :precision="0"
              style="width: 200px;"
              placeholder="请输入人数"
            />
          </FormItem>
        </div>

        <!-- 随驻部门和单位 -->
        <div class="subsection">
          <h4 class="subsection-title">随驻部门和单位</h4>

          <div
            v-for="item in followDepartments"
            :key="item.valueKey"
            class="department-row"
          >
            <FormItem :key="item.valueKey" :label="item.name + '：'" :prop="item.valueKey">
              <RadioGroup v-model="formData[item.valueKey]"
                          @on-change="(val) => handleFollowChange(item.countKey, val)">
                <Radio label="1">入驻</Radio>
                <Radio label="2">未入驻</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem
              v-if="formData[item.valueKey] === '1'"
              :key="item.countKey"
              :label="item.name + '人数：'"
              :prop="item.countKey"
            >
              <InputNumber
                v-model="formData[item.countKey]"
                :min="0"
                :precision="0"
                style="width: 200px;"
                placeholder="请输入人数"
              />
            </FormItem>
          </div>

          <FormItem label="其他：" prop="accompanying_department_other">
            <RadioGroup v-model="formData.accompanying_department_other" @on-change="handleFollowOtherChange">
              <Radio label="1">有</Radio>
              <Radio label="2">无</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem
            v-if="formData.accompanying_department_other === '1'"
            label="其他选项："
            prop="followOtherOptions"
          >
            <RadioGroup v-model="formData.followOtherOptions">
              <Radio
                v-for="item in followOtherDictOptions"
                :key="item.value || item.label"
                :label="item.value || item.label"
              >{{ item.label }}
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            v-if="formData.accompanying_department_other === '1' && formData.followOtherOptions"
            label="入驻人数："
            prop="accompanying_department_other_settle_number"
          >
            <InputNumber
              v-model="formData.accompanying_department_other_settle_number"
              :min="0"
              :precision="0"
              style="width: 200px;"
              placeholder="请输入人数"
            />
          </FormItem>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-footer">
        <Button type="primary" @click="handleSubmit" :loading="submitting">提交</Button>
        <Button style="margin-left: 10px;" @click="handleCancel">取消</Button>
      </div>
    </Form>
  </div>
</template>

<script>
import {
  getComprehensiveCenterById,
  insertComprehensiveCenter,
  updateComprehensiveCenter,
  selectDictList
} from '@/api/contradiction'

export default {
  name: 'ComprehensiveCenterForm',
  data () {
    return {
      formType: 'add', // add 或 edit
      submitting: false,
      formData: {
        id: '',
        city_id: '',
        city_name: '',
        area_id: '',
        area_name: '',
        square_measure: null,
        construction_selection: '',
        locationOther: '',
        functional_layout: [],
        institutional_staffing: '',
        unit_level: '',
        authorized_strength: null,
        actual_number: null,
        public_legal: '',
        reception_center: '',
        lawsuit: '',
        procuratorial: '',
        multicenter_other_type: '',
        multicenter_other: '',
        multicenter_other_number: null,
        resident_department_other: '',
        residentOtherOptions: '',
        resident_department_other_status: '',
        resident_department_other_settle_number: null,
        rotating_department_other: '',
        rotatingOtherOptions: '',
        rotating_department_other_status: '',
        rotating_department_other_settle_number: null,
        accompanying_department_other: '',
        followOtherOptions: '',
        accompanying_department_other_status: '',
        accompanying_department_other_settle_number: null
      },
      constructionSelectionOptions: [],
      functionalLayoutOptions: [],
      locationOtherOptions: [],
      multicenterOtherDictOptions: [],
      residentOtherDictOptions: [],
      rotatingOtherDictOptions: [],
      followOtherDictOptions: [],
      residentDepartments: [
        { name: '法院', valueKey: 'resident_department_fy', countKey: 'resident_department_fy_settle' },
        { name: '检察院', valueKey: 'resident_department_jcy', countKey: 'resident_department_jcy_settle' },
        { name: '公安', valueKey: 'resident_department_gg', countKey: 'resident_department_gg_settle' },
        { name: '司法行政', valueKey: 'resident_department_sa', countKey: 'resident_department_sa_settle' },
        { name: '信访', valueKey: 'resident_department_xf', countKey: 'resident_department_xf_settle' },
        { name: '人力资源社会保障', valueKey: 'resident_department_rl', countKey: 'resident_department_rl_settle' },
        {
          name: '人民调解组织（特色调解室、金牌调解员）',
          valueKey: 'resident_department_rm',
          countKey: 'resident_department_rm_settle'
        }
      ],
      rotatingDepartments: [
        { name: '民政', valueKey: 'rotating_department_mz', countKey: 'rotating_department_mz_settle' },
        { name: '自然资源', valueKey: 'rotating_department_zr', countKey: 'rotating_department_zr_settle' },
        { name: '生态环境', valueKey: 'rotating_department_st', countKey: 'rotating_department_st_settle' },
        { name: '住房城乡建设', valueKey: 'rotating_department_zf', countKey: 'rotating_department_zf_settle' },
        { name: '卫生健康', valueKey: 'rotating_department_ws', countKey: 'rotating_department_ws_settle' },
        { name: '退役军人事务', valueKey: 'rotating_department_ty', countKey: 'rotating_department_ty_settle' },
        { name: '市场监管', valueKey: 'rotating_department_sc', countKey: 'rotating_department_sc_settle' },
        { name: '工会', valueKey: 'rotating_department_gh', countKey: 'rotating_department_gh_settle' },
        { name: '共青团', valueKey: 'rotating_department_gqt', countKey: 'rotating_department_gqt_settle' },
        { name: '妇联', valueKey: 'rotating_department_fl', countKey: 'rotating_department_fl_settle' },
        { name: '法学会', valueKey: 'rotating_department_fxh', countKey: 'rotating_department_fxh_settle' },
        { name: '行业性专业性调解组织', valueKey: 'rotating_department_hy', countKey: 'rotating_department_hy_settle' }
      ],
      followDepartments: [
        {
          name: '民商事仲裁机构',
          valueKey: 'accompanying_department_ms',
          countKey: 'accompanying_department_ms_settle'
        },
        {
          name: '劳动争议仲裁机构',
          valueKey: 'accompanying_department_ld',
          countKey: 'accompanying_department_ld_settle'
        },
        { name: '公证机构', valueKey: 'accompanying_department_gz', countKey: 'accompanying_department_gz_settle' },
        { name: '鉴定机构', valueKey: 'accompanying_department_jd', countKey: 'accompanying_department_jd_settle' },
        { name: '心理服务机构', valueKey: 'accompanying_department_xl', countKey: 'accompanying_department_xl_settle' },
        {
          name: '公益性社会组织',
          valueKey: 'accompanying_department_gy',
          countKey: 'accompanying_department_gy_settle'
        },
        { name: '律师', valueKey: 'accompanying_department_ls', countKey: 'accompanying_department_ls_settle' }
      ],
      residentOtherOptions: [],
      rotatingOtherOptions: [],
      followOtherOptions: [],
      rules: {
        square_measure: [
          { required: true, type: 'number', message: '请输入面积', trigger: 'blur' }
        ],
        construction_selection: [
          { required: true, message: '请选择场所选址', trigger: 'change' }
        ],
        functional_layout: [
          { required: true, type: 'array', min: 1, message: '请至少选择一项功能布局', trigger: 'change' }
        ],
        institutional_staffing: [
          { required: true, message: '请选择有无机构编制', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 判断是否选择了"其他"选项
    isOtherConstructionSelection () {
      if (!this.formData.construction_selection) return false
      // 检查字典中是否有 label 为"其他"的选项，且当前选择的值匹配
      const otherOption = this.constructionSelectionOptions.find(
        item => item.label === '其他' || item.value === '其他'
      )
      return otherOption && this.formData.construction_selection === otherOption.value
    }
  },
  async mounted () {
    this.formType = this.$route.params.type || 'add'
    this.initFormData()
    // 先加载字典，再加载数据（编辑模式下需要字典数据来判断是否需要加载子级选项）
    await this.loadDictOptions()
    if (this.formType === 'edit' && this.$route.params.id) {
      await this.loadData(this.$route.params.id)
    }
  },
  methods: {
    // 初始化表单数据
    initFormData () {
      const initDepartmentFields = (list) => {
        list.forEach(item => {
          if (!Object.prototype.hasOwnProperty.call(this.formData, item.valueKey)) {
            this.$set(this.formData, item.valueKey, '')
          } else {
            this.formData[item.valueKey] = this.formData[item.valueKey] || ''
          }
          if (!Object.prototype.hasOwnProperty.call(this.formData, item.countKey)) {
            this.$set(this.formData, item.countKey, null)
          } else if (this.formData[item.valueKey] !== '1') {
            this.formData[item.countKey] = this.formData[item.countKey] || null
          }
        })
      }
      initDepartmentFields(this.residentDepartments)
      initDepartmentFields(this.rotatingDepartments)
      initDepartmentFields(this.followDepartments)
    },

    // 加载数据
    async loadData (id) {
      try {
        const response = await getComprehensiveCenterById({ id })
        if (response.data && response.data.errcode === 0) {
          const data = response.data.data || {}
          data.functional_layout = this.normalizeToArray(data.functional_layout)
          // data.multicenter_other = this.normalizeToArray(data.multicenter_other)
          this.formData.residentOtherOptions = data.resident_department_other_settle
          this.formData.rotatingOtherOptions = data.rotating_department_other_settle
          this.formData.followOtherOptions = data.accompanying_department_other_settle
          data.multicenter_other_number = data.multicenter_other_number.toString()
          Object.assign(this.formData, data)
          console.log(this.formData)
          this.initFormData()

          // 如果场所选址是"其他"，需要加载子级选项
          const otherOption = this.constructionSelectionOptions.find(
            item => item.label === '其他' || item.value === '其他'
          )
          if (otherOption && this.formData.construction_selection === otherOption.value) {
            await this.loadLocationOtherOptions(otherOption.value)
          }
        } else {
          this.$Message.error(response.data.errmsg || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$Message.error('加载数据失败')
      }
    },

    // 加载字典选项
    async loadDictOptions () {
      try {
        const [constructionRes, functionalLayoutRes, registrationRes] = await Promise.all([
          selectDictList({ type: 'event_construction_selection' }),
          selectDictList({ type: 'event_functional_layout' }),
          selectDictList({ type: 'event_registration_status' })
        ])

        // 场所选址字典
        if (constructionRes.data && constructionRes.data.errcode === 0) {
          this.constructionSelectionOptions = this.formatDictOptions(constructionRes.data.data)
        } else {
          this.constructionSelectionOptions = []
        }
        // locationOtherOptions 在选择"其他"时动态加载

        // 功能布局字典
        if (functionalLayoutRes.data && functionalLayoutRes.data.errcode === 0) {
          this.functionalLayoutOptions = this.formatDictOptions(functionalLayoutRes.data.data)
        } else {
          this.functionalLayoutOptions = []
        }

        // 注册状态字典（用于其他选项）
        if (registrationRes.data && registrationRes.data.errcode === 0) {
          const options = this.formatDictOptions(registrationRes.data.data)
          this.multicenterOtherDictOptions = options
          this.residentOtherDictOptions = options
          this.rotatingOtherDictOptions = options
          this.followOtherDictOptions = options
        } else {
          this.multicenterOtherDictOptions = []
          this.residentOtherDictOptions = []
          this.rotatingOtherDictOptions = []
          this.followOtherDictOptions = []
        }
      } catch (error) {
        console.error('加载字典失败:', error)
        this.$Message.error('加载字典失败')
        this.constructionSelectionOptions = []
        this.functionalLayoutOptions = []
        this.locationOtherOptions = []
        this.multicenterOtherDictOptions = []
        this.residentOtherDictOptions = []
        this.rotatingOtherDictOptions = []
        this.followOtherDictOptions = []
      }
    },

    // 场所选址其他选项变化
    async handleConstructionSelectionChange () {
      // 检查是否选择了"其他"选项
      const otherOption = this.constructionSelectionOptions.find(
        item => item.label === '其他' || item.value === '其他'
      )
      if (otherOption && this.formData.construction_selection === otherOption.value) {
        // 选择了"其他"，加载子级字典选项
        await this.loadLocationOtherOptions(otherOption.value)
      } else {
        // 未选择"其他"，清空选项
        this.formData.locationOther = ''
        this.locationOtherOptions = []
      }
    },

    // 加载场所选址"其他"选项
    async loadLocationOtherOptions (parentId) {
      try {
        const response = await selectDictList({
          type: 'event_construction_selection',
          parent_id: parentId
        })
        if (response.data && response.data.errcode === 0) {
          this.locationOtherOptions = this.formatDictOptions(response.data.data)
        } else {
          this.locationOtherOptions = []
        }
      } catch (error) {
        console.error('加载场所选址其他选项失败:', error)
        this.locationOtherOptions = []
      }
    },

    // 机构编制变化
    handleInstitutionChange () {
      if (this.formData.institutional_staffing !== '1') {
        this.formData.unit_level = ''
        this.formData.authorized_strength = null
        this.formData.actual_number = null
      }
    },

    // 常驻部门变化
    handleResidentChange (countKey, val) {
      if (val !== '1') {
        this.$set(this.formData, countKey, null)
      }
    },

    handleMulticenterOtherFlagChange () {
      if (this.formData.multicenter_other_type !== '1') {
        this.formData.multicenter_other = ''
      }
    },

    // 常驻部门其他变化
    handleResidentOtherChange () {
      if (this.formData.resident_department_other !== '1') {
        this.formData.residentOtherOptions = ''
        this.formData.resident_department_other_status = ''
        this.formData.resident_department_other_settle_number = null
      }
    },

    // 常驻部门其他入驻状态变化
    handleResidentOtherStatusChange () {
      if (this.formData.resident_department_other_status === '3') {
        this.formData.resident_department_other_settle_number = null
      }
    },

    // 轮驻部门变化
    handleRotatingChange (countKey, val) {
      if (val !== '1') {
        this.$set(this.formData, countKey, null)
      }
    },

    // 轮驻部门其他变化
    handleRotatingOtherChange () {
      if (this.formData.rotating_department_other !== '1') {
        this.formData.rotatingOtherOptions = ''
        this.formData.rotating_department_other_status = ''
        this.formData.rotating_department_other_settle_number = null
      }
    },

    // 轮驻部门其他入驻状态变化
    handleRotatingOtherStatusChange () {
      if (this.formData.rotating_department_other_status === '3') {
        this.formData.rotating_department_other_settle_number = null
      }
    },

    // 随驻部门变化
    handleFollowChange (countKey, val) {
      if (val !== '1') {
        this.$set(this.formData, countKey, null)
      }
    },

    // 随驻部门其他变化
    handleFollowOtherChange () {
      if (this.formData.accompanying_department_other !== '1') {
        this.formData.followOtherOptions = ''
        this.formData.accompanying_department_other_status = ''
        this.formData.accompanying_department_other_settle_number = null
      }
    },

    // 随驻部门其他入驻状态变化
    handleFollowOtherStatusChange () {
      if (this.formData.accompanying_department_other_status === '3') {
        this.formData.accompanying_department_other_settle_number = null
      }
    },

    normalizeToArray (value) {
      if (!value) return []
      if (Array.isArray(value)) return value
      if (typeof value === 'string') {
        return value.split(',').map(item => item.trim()).filter(item => item)
      }
      return []
    },

    formatDictOptions (list) {
      if (!Array.isArray(list)) return []
      return list
        .map(item => {
          const label = item.label || item.dict_name || item.name || ''
          const value = item.value || item.dict_value || item.code || label
          if (!label) return null
          return { label, value }
        })
        .filter(Boolean)
    },

    // 提交
    async handleSubmit () {
      this.$refs.formValidate.validate(async (valid) => {
        if (valid) {
          // 验证实有人数不能大于编制人数
          if (this.formData.institutional_staffing === '1') {
            if (this.formData.actual_number > this.formData.authorized_strength) {
              this.$Message.error('实有人数不能大于编制人数')
              return
            }
          }

          this.submitting = true
          try {
            const params = { ...this.formData }
            params.functional_layout = (this.formData.functional_layout || []).join(',')
            params.multicenter_other = this.formData.multicenter_other.length > 0 ? this.formData.multicenter_other.toString() : ''
            params.resident_department_other_settle = this.formData.residentOtherOptions.length > 0 ? this.formData.residentOtherOptions.toString() : ''
            params.rotating_department_other_settle = this.formData.rotatingOtherOptions.length > 0 ? this.formData.rotatingOtherOptions.toString() : ''
            params.accompanying_department_other_settle = this.formData.followOtherOptions.length > 0 ? this.formData.followOtherOptions.toString() : ''
            // 如果选择了"其他"选项，使用 locationOther 的值
            if (this.isOtherConstructionSelection && this.formData.locationOther) {
              params.construction_selection = this.formData.locationOther
            }
            delete params.residentOtherOptions
            delete params.rotatingOtherOptions
            delete params.followOtherOptions
            let response
            if (this.formType === 'add') {
              response = await insertComprehensiveCenter(params)
            } else {
              response = await updateComprehensiveCenter(params)
            }

            if (response.data && response.data.errcode === 0) {
              this.$Message.success(this.formType === 'add' ? '新增成功' : '更新成功')
              this.$router.go(-1)
            } else {
              this.$Message.error(response.data.errmsg || '操作失败')
            }
          } catch (error) {
            console.error('提交失败:', error)
            this.$Message.error('提交失败')
          } finally {
            this.submitting = false
          }
        } else {
          this.$Message.error('请完善表单信息')
        }
      })
    },

    // 取消
    handleCancel () {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped lang="less">
.comprehensive-center-form {
  padding: 20px;
  background: #fff;

  .form-header {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e8e8e8;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .form-section {
    margin-bottom: 30px;
    padding: 20px;
    background: #fafafa;
    border-radius: 4px;

    .section-title {
      margin: 0 0 20px 0;
      font-size: 16px;
      font-weight: 500;
      color: #333;
      padding-bottom: 10px;
      border-bottom: 2px solid #2d8cf0;
    }

    .subsection {
      margin-top: 20px;
      padding: 15px;
      background: #fff;
      border-radius: 4px;

      .subsection-title {
        margin: 0 0 15px 0;
        font-size: 14px;
        font-weight: 500;
        color: #666;
        padding-bottom: 8px;
        border-bottom: 1px solid #e8e8e8;
      }
    }
  }

  .form-footer {
    text-align: center;
    padding: 20px 0;
    border-top: 1px solid #e8e8e8;
    margin-top: 30px;
  }
}
</style>
