import { defineComponent, ref } from 'vue'
import {
  ElPopover,
  ElScrollbar,
  ElCheckbox,
  ElCheckboxGroup,
  ElInput,
} from 'element-plus'

const styles = {
  searchForm: {
    position: 'relative',
  },
  titleBox: {
    display: 'flex',
    padding: '10px 18px',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  checkboxGroup: {
    display: 'flex',
    padding: '10px',
    justifyContent: 'flex-start',
    flexWrap: 'wrap',
    backgroundColor: '#efefef',
  },
} as const

interface ICompanyList {
  warehouseName: string
  wayList: IwayList[]
}
interface IwayList {
  name: string
  id: string
}
interface IAllList {
  factoryId: number
  id: number
  name: string
  serviceCode: string
  siteUrl: string
  status: number
  uinuinWarehouseId: number | null
  updateTime: string
  warehouseId: number
  warehouseName: string
}
export default defineComponent({
  name: 'CustomizeForm',
  props: {
    modelValue: {
      type: Array as PropType<(string | number)[]>,
      default: () => [],
    },
    companyList: {
      type: Array as PropType<IAllList[]>,
      default: () => [],
    },
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const companyList = ref<ICompanyList[]>([])
    const allList = ref<IAllList[]>([])
    const selectedList = ref<(string | number)[]>([])

    const waysName = ref('')

    watch(
      () => props.modelValue,
      (newVal) => {
        selectedList.value = newVal
      },
      {
        immediate: true,
        deep: true,
      },
    )

    watch(
      [() => selectedList.value, () => props.companyList],
      (newVal) => {
        emit('update:modelValue', newVal[0])
        allList.value = newVal[1]
        companyList.value = transformData(newVal[1])

        if (newVal[1]?.length) {
          waysName.value = newVal[1]
            .filter((item) => {
              if (newVal[0].includes(item.id)) {
                return item.name
              }
            })
            .map((item) => item.name)
            .join(',')
          // emit('waysName', res)
          console.log(87, waysName.value)
        }
      },
      { deep: true, immediate: true },
    )

    function setCheckAll(company: ICompanyList, event: boolean) {
      if (event) {
        selectedList.value = [
          ...selectedList.value,
          ...company.wayList.map((item) => item.id),
        ]
      } else {
        selectedList.value = selectedList.value.filter(
          (item) =>
            !company.wayList.map((el) => el.id).includes(item as string),
        )
      }
    }

    const getCompanySelectedStatus = computed(() => {
      const statusMap = new Map()

      companyList.value.forEach((company: ICompanyList) => {
        const allSelected = company.wayList.every((way) =>
          selectedList.value.includes(way.id),
        )
        statusMap.set(company.warehouseName, allSelected)
      })

      return (company: ICompanyList) => statusMap.get(company.warehouseName)
    })

    function transformData(data: IAllList[]) {
      const warehouseMap = new Map()
      for (const item of data) {
        const warehouseName = item.warehouseName ?? '未命名仓库'
        if (!warehouseMap.has(warehouseName)) {
          warehouseMap.set(warehouseName, new Set())
        }

        warehouseMap.get(warehouseName).add({ name: item.name, id: item.id })
      }
      const result: {
        warehouseName: string
        wayList: { name: string; id: string }[]
      }[] = []

      warehouseMap.forEach((children, parent) => {
        result.push({
          warehouseName: parent,
          wayList: Array.from(children),
        })
      })

      return result
    }

    return () => (
      <ElPopover
        width="650px"
        placement="bottom-start"
        trigger="click"
        popper-style={{ padding: 0 }}
        v-slots={{
          reference: () => (
            <ElInput
              modelValue={waysName.value}
              style={{ width: '100%' }}
              placeholder="请选择物流方式"
            />
          ),
        }}
      >
        <ElScrollbar class="scroll-container" maxHeight="450px">
          {companyList.value.map((company, index) => (
            <div class="companyBox" key={index}>
              <div style={styles.titleBox}>
                <div class="title">{company.warehouseName}</div>
                <ElCheckbox
                  modelValue={getCompanySelectedStatus.value(company)}
                  onChange={(v) => setCheckAll(company, v as boolean)}
                  class="selectAll"
                >
                  全选
                </ElCheckbox>
              </div>

              <ElCheckboxGroup
                modelValue={selectedList.value}
                onUpdate:modelValue={(value) => (selectedList.value = value)}
                style={styles.checkboxGroup}
              >
                {company.wayList.map((item) => (
                  <ElCheckbox
                    label={item.name}
                    value={item.id}
                    key={`item-${item.id}`}
                    class="checkboxItem"
                  />
                ))}
              </ElCheckboxGroup>
            </div>
          ))}
        </ElScrollbar>
      </ElPopover>
    )
  },
})
