<template>
  <div class="common-dialog">
    <div class="common-dialog-content">
      <div class="common-dialog-title-box">
        <i class="common-dialog-title-icon" />
        <div>新建三防责任人信息</div>
      </div>
      <div class="common-dialog-box" style="width: 1000px">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="160px">
          <el-form-item label="姓名：" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="电话号码：" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话号码" />
          </el-form-item>
          <el-form-item label="所属单位：" prop="unit_name">
            <el-input v-model="form.unit_name" placeholder="例如：XX市XX县人民政府" />
            <span style="color: #999; font-size: 12px; margin-left: 5px">请使用单位全称</span>
          </el-form-item>
          <el-form-item label="职务：" prop="position">
            <el-input v-model="form.position" placeholder="例如：县长/办公室主任/办事员等" />
          </el-form-item>
          <el-form-item label="行政区划：" prop="area_code">
            <el-select v-model="data1" placeholder="请选择" style="width: 200px; margin-right: 5px" clearable @change="getOptions2()">
              <el-option v-for="item in options1" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
            <el-select v-model="data2" placeholder="请选择" style="width: 200px; margin-right: 5px" clearable @change="getOptions3()">
              <el-option v-for="item in options2" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
            <el-select v-model="data3" placeholder="请选择" style="width: 200px; margin-right: 5px" clearable @change="getAreaContent()">
              <el-option v-for="item in options3" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="办公电话：" prop="office_phone">
            <div class="phone-input-container">
              <el-input v-model="form.office_phone_prefix" placeholder="例如：0668" style="width: 120px;"></el-input>
              <span class="phone-input-separator">-</span>
              <el-input v-model="form.office_phone_number" placeholder="例如：88888888" style="width: 200px;"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="排位顺序：" prop="order_num">
            <el-input v-model="form.order_num" placeholder="例如：请输入排位序号1-999" />
            <span style="color: #999; font-size: 12px; margin-left: 5px">序号数值越小越靠前</span>
          </el-form-item>
          <el-form-item label="选择类别：" prop="category">
            <div>
              <el-checkbox-group v-model="checkboxGroup2" @change="changeChildType">
                <el-checkbox-button v-for="type in category" :key="type" :value="type" @click="deleteOne(type)">
                  {{ type.label }}
                </el-checkbox-button>
              </el-checkbox-group>
              <el-tabs v-model="childType" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane v-for="item in checkboxGroup2" :label="item.label" :name="item.label">
                  <el-checkbox-group v-model="item.checked" @change="getSubOption()">
                    <el-checkbox-button v-for="item2 in item.children" :key="item2.id" :value="item2.id">
                      {{ item2.label }}
                    </el-checkbox-button>
                  </el-checkbox-group>
                  <div v-if="item.label === '成员单位'">
                    <span>请填写单位名称：</span>
                    <el-input v-model="item.dept_name" style="width: 240px" placeholder="如：茂名供电局" @change="memberUnits" />
                  </div>
                  <div v-if="item.label === '重点部门'">
                    <span>请填写单位名称：</span>
                    <el-input v-model="item.dept_name" style="width: 240px" placeholder="如：茂名市中心小学" @change="memberUnits" />
                    <div style="display: flex">
                      <span>请选择责任类别：</span>
                      <el-checkbox-group v-model="item.other_type_id" @change="getChOption">
                        <el-checkbox-button v-for="item2 in item.children2" v-if="item.id === '5'" :key="item2" :value="item2.id">
                          {{ item2.label }}
                        </el-checkbox-button>
                      </el-checkbox-group>
                    </div>
                  </div>
                  <div v-if="item.label === '水利工程'">
                    <span>请填写单位名称：</span>
                    <el-input v-model="item.dept_name" style="width: 240px" placeholder="如：北江大堰" @change="memberUnits" />
                    <div style="display: flex">
                      <span v-if="item.label === '水利工程'">请选择责任类别：</span>
                      <el-checkbox-group v-model="item.other_type_id" @change="getChOption">
                        <el-checkbox-button v-for="item2 in item.children2" v-if="item.id === '7'" :key="item2" :value="item2.id">
                          {{ item2.label }}
                        </el-checkbox-button>
                      </el-checkbox-group>
                    </div>
                  </div>
                  <div v-if="item.label === '抢险队伍'" style="display: flex">
                    <span>请选择责任类别：</span>
                    <el-checkbox-group v-model="item.other_type_id" @change="getChOption">
                      <el-checkbox-button v-for="item2 in item.children2" v-if="item.id === '9'" :key="item2" :value="item2.id">
                        {{ item2.label }}
                      </el-checkbox-button>
                    </el-checkbox-group>
                  </div>
                  <div v-if="item.label === '地质灾害'">
                    <span>请填写隐患点名称：</span>
                    <el-input v-model="item.denger_point_name" style="width: 240px" placeholder="" @change="memberUnits" />
                  </div>
                  <div v-if="item.label === '其他'">
                    <span>请填写具体类型：</span>
                    <el-input
                      v-model="item.other_type_2_name"
                      style="width: 240px"
                      placeholder="请填写责任类型，如：重点单位等"
                      @change="memberUnits"
                    />
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-form-item>
        </el-form>
        <div class="common-dialog-footer">
          <el-button @click="goBack">取消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitNewPerson()">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, toRefs } from 'vue';
import type { TabsPaneContext } from 'element-plus';
import { createNewPerson, getPersonRespon, getZoning, responsibleDetail } from '@/api/PreventionResponsible';

const category = ref([]);
const checkboxGroup2 = ref([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  id: String
});
const buttonLoading = ref(false);
const data1 = ref();
const data2 = ref();
const data3 = ref();

// 表单数据
const data = reactive({
  form: {
    unit_name: '',
    name: '',
    area_code: '',
    position: '',
    phone: '',
    order_num: '',
    type_list: []
  },
  rules: {
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    unit_name: [{ required: true, message: '所属单位不能为空', trigger: 'change' }],
    phone: [{ required: true, message: '电话号码不能为空', trigger: 'change' }],
    position: [{ required: true, message: '职务不能为空', trigger: 'blur' }],
    area_code: [{ required: true, message: '行政区划不能为空', trigger: 'change' }]
  }
});
const { form } = toRefs(data);
const emits = defineEmits(['close']);
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const options1 = ref('');
const options2 = ref('');
const options3 = ref('');
const getOptions1 = (id) => {
  getZoning(id).then((res) => {
    options1.value = res.data;
  });
};
const getOptions2 = () => {
  if (!data1.value) {
    data2.value = '';
    data3.value = '';
    form.value.area_code = undefined;
    options2.value = undefined;
    return;
  } else {
    getZoning(data1.value).then((res) => {
      options2.value = res.data;
    });
    form.value.area_code = data1.value;
  }
};
const getOptions3 = () => {
  if (!data2.value) {
    data3.value = '';
    form.value.area_code = data1.value;
    options3.value = undefined;
    return;
  } else {
    getZoning(data2.value).then((res) => {
      options3.value = res.data;
    });
    form.value.area_code = data2.value;
  }
};
const getAreaContent = () => {
  if (!data3.value) {
    form.value.area_code = data2.value;
    return;
  } else {
    form.value.area_code = data3.value;
  }
};
watch(data1, () => {
  data2.value = '';
  data3.value = '';
  options2.value = undefined;
});
watch(data2, () => {
  data3.value = '';
  options3.value = undefined;
});
const getCategory = () => {
  getPersonRespon().then((res) => {
    category.value = res.rows;
  });
};

const childType = ref();
const changeChildType = () => {
  category.value.forEach((item) => {
    let index = checkboxGroup2.value.findIndex((item2) => item2.id === item.id);
    if (index === -1) {
      delete item.checked;
    }
  });
  childType.value = checkboxGroup2.value[checkboxGroup2.value.length - 1].label;
};

const getSubOption = () => {
  const obj = {
    type_parent_id: '',
    children: ''
  };
  for (let i = 0; i < checkboxGroup2.value.length; i++) {
    obj.type_parent_id = checkboxGroup2.value[i].id;
    obj.children = checkboxGroup2.value[i].checked;
    form.value.type_list[i] = obj;
  }
};
const memberUnits = () => {
  let datatemp = [];
  for (let i = 0; i < checkboxGroup2.value.length; i++) {
    if (!!checkboxGroup2.value[i] && checkboxGroup2.value[i].children.length > 0) {
      const obj = {
        type_parent_id: checkboxGroup2.value[i].id,
        children: checkboxGroup2.value[i].checked
      };
      if (['4', '5', '7'].includes(checkboxGroup2.value[i].id) && checkboxGroup2.value[i].dept_name) {
        //成员单位
        obj.dept_name = checkboxGroup2.value[i].dept_name;
      } else if (checkboxGroup2.value[i].id === '10' && checkboxGroup2.value[i].denger_point_name) {
        //地质灾害
        obj.denger_point_name = checkboxGroup2.value[i].denger_point_name;
      } else if (checkboxGroup2.value[i].id === '11' && checkboxGroup2.value[i].other_type_2_name) {
        //其他
        obj.other_type_2_name = checkboxGroup2.value[i].other_type_2_name;
      }
      datatemp.push(obj);
    }
  }
  form.value.type_list = datatemp;
};

const deleteOne = (type) => {
  const index = form.value.type_list.findIndex((item) => item.type_parent_id === type.id);
  if (index !== -1) {
    form.value.type_list.splice(index, 1);
  }
};
const getChOption = () => {
  debugger;
  let datatemp = [];
  for (let i = 0; i < checkboxGroup2.value.length; i++) {
    if (!!checkboxGroup2.value[i] && checkboxGroup2.value[i].other_type_id.length > 0) {
      const obj = {
        type_parent_id: checkboxGroup2.value[i].id,
        other_type_id: checkboxGroup2.value[i].other_type_id
      };
      datatemp.push(obj);
    }
  }
  form.value.type_list = datatemp;
};
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};
const personType = ref([]);
for (const i in category.value) {
  personType.value.push(category.value[i].label);
}

const submitNewPerson = async () => {
  // 打印当前表单值用于调试
  console.log('Form values before submit:', form.value);

  // 验证表单
  try {
    if (!formRef.value) {
      throw new Error('Form reference is not set');
    }

    const valid = await formRef.value.validate((valid, invalidFields) => {
      if (!valid) {
        console.error('Validation failed:', invalidFields); // 输出未通过验证的字段
      }
      return valid;
    });

    if (!valid) {
      proxy.$modal.msgError('请检查输入信息');
      return;
    }
  } catch (error) {
    console.error('Validation error:', error);
    proxy.$modal.msgError('请检查输入信息');
    return;
  }

  // 构建请求体
  const requestBody = {
    unit_name: form.value.unit_name,
    name: form.value.name,
    area_code: form.value.area_code,
    position: form.value.position,
    phone: form.value.phone,
    order_num: form.value.order_num,
    type_list: checkboxGroup2.value
      .map((item) => ({
        type_parent_id: item.id,
        children: item.checked || [],
        dept_name: item.dept_name || null,
        other_type_2_name: item.other_type_2_name || null,
        denger_point_name: item.denger_point_name || null
      }))
      .filter((item) => Object.values(item).some((val) => val !== null && val !== undefined))
  };

  buttonLoading.value = true; // 开始加载状态

  try {
    // 发送请求
    await createNewPerson(requestBody);
    proxy.$modal.msgSuccess('新增成功');
    emits('close', true); // 关闭对话框并通知父组件
    emits('refresh');
  } catch (error) {
    console.error('Error creating new person:', error);
    proxy.$modal.msgError('新增失败，请稍后再试或联系管理员');
  } finally {
    buttonLoading.value = false; // 结束加载状态
  }
};

onMounted(() => {
  if (props.id) {
    responsibleDetail(props.id).then((res) => {
      Object.assign(form.value, res.data);
      // 如果有特殊情况处理，如将API返回的类型列表转换为checkboxGroup2的格式
      checkboxGroup2.value = res.data.type_list.map((item) => ({
        id: item.type_parent_id,
        checked: item.children || [],
        dept_name: item.dept_name,
        other_type_2_name: item.other_type_2_name,
        denger_point_name: item.denger_point_name
      }));
    });
  }
  getOptions1(2);
  getCategory();
});
// 返回上一级
const goBack = () => {
  emits('close');
};
</script>

<style scoped lang="scss">
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
