import { ref, watch, reactive } from "vue"
import { getApi } from "@/api/tobAcco_api.js"

const fieldDefalut = {
  placeid: "placeid", // 场所ID
  placeName: "placename", // 场所名称
  buildingid: "buildingid", // 建筑物ID
  buildingname: "buildingname", // 建筑物名称
  floorid: "floorid", // 楼层ID
  floorname: "floorname", // 楼层名称
  partid: "partid", // 部位ID
  partname: "partname" // 部位名称
}

/**
 * 获取 场所、建筑物、楼层、部位的公共方法
 * @param {Object} props - 组件传入的属性
 * @param {string} props.placeid - 场所ID
 * @param {string} props.placeName - 场所名称
 * @param {Object} fields - 需要处理的字段对象，键为字段名，值为默认值
 */
export const usePosition = (props, extendForm = {}, fields = fieldDefalut) => {
  // 场所列表
  const csmclist = ref([])
  // 建筑物列表
  const jzwlist = ref([])
  // 楼层列表
  const lclist = ref([])
  // 部位列表
  const bwlist = ref([])

  const fieldMap = { ...fieldDefalut, ...fields }

  // 表单数据
  const form = ref({ })

  // 其他数据,用于展示
  const othData = ref({
    publicarea: "2", // 公共区域 "1":场区(不显示楼层)  "2"：建筑物 用于判断
    areaLabel: "所属建筑物",
    partLabel: "所属部位"
  })

  // 设置其他数据
  const setOthData = publicareaValue => {
    othData.value = {
      publicarea: publicareaValue || "2",
      areaLabel: publicareaValue == "1" ? "所属场区" : "所属建筑物",
      partLabel: publicareaValue == "1" ? "场区部位" : "所属部位"
    }
  }

  // 清空指定表单值
  const clearFormValue = clearFieldKeys => {
    clearFieldKeys.forEach(key => {
      form.value[fieldMap[key]] = ""
    })
  }

  //根据操作人 查询 场所
  function getcsData() {
    getApi({}, "/mosty-jcgl/site/getSiteListByUser").then(res => {
      csmclist.value = res
      const currentItem = csmclist.value.find(item => item.id == props.placeid)
      if (currentItem) {
        form.value[fieldMap.placeName] = currentItem.placename
      }
    })
  }

  const init = () => {
    Object.assign(form.value, extendForm)
    Object.keys(fieldMap).forEach(key => {
      form.value[fieldMap[key]] = props?.[fieldMap[key]] || ""
    })
    getcsData()
  }

  //【部位】下拉框触发
  const changeBw = val => {
    const currentItem = bwlist.value.find(item => item.id == val)
    if (!currentItem) return
    form.value[fieldMap.partid] = currentItem.id
    form.value[fieldMap.partname] = currentItem.partname
  }

  // (新)根据楼层id查询部位
  function getbwdata(id) {
    getApi({ id }, "/mosty-jcgl/part/getListByFloorid").then(res => {
      bwlist.value = res ? res : []
    })
  }

  // 【楼层】下拉触发，获取部位数据
  function changeLcmc(val) {
    const currentItem = lclist.value.find(item => item.id == val)
    if (!currentItem) return
    const clearFieldKeys = ["partname", "partid"]
    clearFormValue(clearFieldKeys)
    form.value[fieldMap.floorid] = currentItem.id
    form.value[fieldMap.floorname] = currentItem.floorname
    getbwdata(currentItem.id)
  }

  //(新)根据建筑物id查询部位（此场景是场区，没有楼层）
  function getbw2data(id) {
    getApi({ id }, "/mosty-jcgl/part/getListByBuildid").then(res => {
      bwlist.value = res ? res : []
    })
  }

  // 根据建筑物查询楼层（此场景是建筑物，有楼层）
  function getlcdata(id) {
    getApi({ id }, "/mosty-jcgl/floor/queryFloorByBuildId").then(res => {
      lclist.value = res ? res : []
    })
  }

  //【建筑物】下拉触发,获取楼层数据/部位数据
  function changeJzwmc(val) {
    const currentItem = jzwlist.value.find(item => item.id == val)
    if (!currentItem) return
    const clearFieldKeys = ["floorname", "floorid", "partname", "partid"]
    setOthData(currentItem.publicarea)
    clearFormValue(clearFieldKeys)
    form.value[fieldMap.buildingid] = currentItem.id
    form.value[fieldMap.buildingname] = currentItem.buildingname
    if (currentItem.publicarea == "1") {
      getbw2data(currentItem.id)
    } else {
      getlcdata(currentItem.id)
    }
  }

  // 根据placeid(场所ID)，查询建筑物数据
  function getJzwList(placeid) {
    getApi({ placeid }, "/mosty-jcgl/building/queryBuildingByPlaceid").then(res => {
      jzwlist.value = res ? res : []
    })
  }
  //【场所】下拉框change事件触发，获取建筑物/场区数据
  const changeCsmc = val => {
    const currentItem = csmclist.value.find(item => item.id == val)
    if (!currentItem) return
    const clearFieldKeys = ["buildingname", "buildingid", "floorname", "floorid", "partname", "partid"]
    setOthData("")
    clearFormValue(clearFieldKeys)
    form.value[fieldMap.placeid] = currentItem.id
    form.value[fieldMap.placeName] = currentItem.placename
    getJzwList(currentItem.id)
  }

  watch(
    () => [props.placeName, props.placeid],
    () => {
      form.value.placeName = props?.placeName
      form.value.placeid = props?.placeid
      if (props.placeid) {
        getJzwList(props.placeid)
      }
    },
    { immediate: true }
  )
  init()

  /**
   * 根据当前表单数据更新选择框选项
   * 用于详情加载后初始化建筑物、楼层和部位的下拉框数据
   */
  const updateSelectOptions = () => {
    console.log("updateSelectOptions 开始执行")
    // 如果有场所ID，获取建筑物列表
    if (form.value[fieldMap.placeid]) {
      console.log("有场所ID，获取建筑物列表:", form.value[fieldMap.placeid])
      getJzwList(form.value[fieldMap.placeid])

      // 延迟执行，确保建筑物列表已加载
      setTimeout(() => {
        // 获取建筑物ID（兼容buildingid和buildingsid两种字段名）
        const buildingId = form.value[fieldMap.buildingid]

        // 如果有建筑物ID
        if (buildingId) {
          // 查找对应的建筑物
          const building = jzwlist.value.find(item => item.id === buildingId)
          console.log("找到的建筑物:", building)
          if (building) {
            // 设置公共区域类型
            setOthData(building.publicarea)
            console.log("建筑物公共区域类型:", building.publicarea)

            // 根据公共区域类型获取不同数据
            if (building.publicarea === "1") {
              // 场区类型，直接获取部位
              console.log("场区类型，获取部位数据")
              getbw2data(building.id)
            } else {
              // 建筑物类型，获取楼层
              console.log("建筑物类型，获取楼层数据")
              getlcdata(building.id)

              // 延迟执行，确保楼层列表已加载
              setTimeout(() => {
                // 如果有楼层ID，获取对应部位
                if (form.value[fieldMap.floorid]) {
                  console.log("有楼层ID，获取部位数据:", form.value[fieldMap.floorid])
                  getbwdata(form.value[fieldMap.floorid])
                }
              }, 300)
            }
          } else {
            console.log("未找到对应的建筑物")
          }
        } else if (form.value[fieldMap.floorid]) {
          // 如果没有建筑物ID但有楼层ID，直接获取部位
          console.log("没有建筑物ID但有楼层ID，获取部位数据")
          getbwdata(form.value[fieldMap.floorid])
        } else {
          console.log("没有建筑物ID和楼层ID")
        }
      }, 300)
    } else {
      console.log("没有场所ID")
    }
    console.log("updateSelectOptions 执行完毕")
  }

  return {
    form,
    othData,
    csmclist,
    jzwlist,
    lclist,
    bwlist,
    changeCsmc,
    changeJzwmc,
    changeLcmc,
    changeBw,
    updateSelectOptions
  }
}
