<template>
  <ElDialog
    v-model="visible"
    title="属性选择"
    width="65%"
    :close-on-click-modal="false"
  >
    <div class="dialog-body" style="height: 60vh; overflow: auto">
      <div class="header">
        <slot name="header" />
      </div>
      <div v-if="skuOptions?.length > 0">
        <div
          v-for="(item, index) in skuOptions"
          :key="index"
          class="option_wrap"
        >
          <div class="title">
            <span>{{ item.cnname }}</span>
            <span>({{ item.enname }})</span>
          </div>
          <div v-if="checkSkuArr(index)">
            <el-checkbox-group
              v-model="localSkuArr[index].listCode"
              class="attribute-checkbox"
            >
              <el-checkbox
                v-for="(item2, index2) in item.valueList || []"
                :key="index2"
                :label="item2.code"
                :disabled="isDisabled(item2.code)"
                :style="{
                  background: item2.bgColor,
                  color: item2.fontColor,
                  padding: '0 10px',
                }"
                @change="(v:boolean) => optionChange(index, index2, v)"
              >
                {{ item2.isCome }}
                {{ item2.cnname + '(' + item2.enname + ')' }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </ElDialog>
</template>
<script setup lang="ts">
import { defineModel, defineEmits, defineExpose, defineProps } from 'vue'
const visible = defineModel<boolean>('visible', { default: false })
import { SkuPropertyValue, SkuProperty, InterSkuArr } from '@/types/api/product'
import { storeToRefs } from 'pinia'
import { useOptionsStore } from '@/store/product'
const store = useOptionsStore()
const { keyCode } = storeToRefs(store)
const emits = defineEmits<{
  (event: 'success'): void
  (e: 'update:skuArr', payload: { skuArr: InterSkuArr[] }): void
  (event: 'close'): void
}>()
const props = defineProps({
  skuOptions: {
    type: Array as () => SkuProperty[],
    required: true,
  },
  skuArr: {
    type: Array as () => InterSkuArr[],
    required: true,
  },
  save: {
    type: Function,
    required: true,
  },
})
const mode = ref('add')
const currentIndex = ref<number>(-1)
const childrenIndex = ref<number>(-1)
const localSkuArr = ref(JSON.parse(JSON.stringify(props.skuArr)))
watch(
  () => props.skuArr,
  (newVal: InterSkuArr[]) => {
    localSkuArr.value = JSON.parse(JSON.stringify(newVal)) || [] //留下一开始回显的值
  },
)
const handleSubmit = async () => {
  emits('update:skuArr', {
    skuArr: JSON.parse(JSON.stringify(localSkuArr.value)),
  }) // 只提交本地深拷贝
  props.save() //提交属性的同时，表格数据变化
  ElMessage.success('提交成功')
  visible.value = false
}
const open = async (key = 'add') => {
  mode.value = key
}
const checkSkuArr = (index: number) => {
  const skuArr = localSkuArr.value
  return skuArr && skuArr.length > 0 && skuArr[index]?.listCode !== undefined
}

const optionChange = (i: number, j: number, value: boolean) => {
  const list = props.skuOptions
  const skuArr = localSkuArr.value
  if (keyCode.value === 'Shift' && value) {
    if (currentIndex.value === i) {
      let min: number, max: number
      if (j > childrenIndex.value) {
        min = childrenIndex.value
        max = j
      } else {
        min = j
        max = childrenIndex.value
      }
      const codeList = skuArr[i].listCode
      for (let index = min; index <= max; index++) {
        list[i].valueList[index].selected = value ? 1 : 0
        if (!codeList.includes(list[i].valueList[index].code)) {
          codeList.push(list[i].valueList[index].code)
        }
      }
    } else {
      currentIndex.value = i
      childrenIndex.value = j
      list[i].valueList[j].selected = value ? 1 : 0
    }
  } else {
    if (value) {
      currentIndex.value = i
      childrenIndex.value = j
    } else {
      currentIndex.value = -1
      childrenIndex.value = -1
    }
    list[i].valueList[j].selected = value ? 1 : 0
  }
  // 保证valueList和listCode一致
  skuArr[i].valueList = list[i].valueList.filter((v: SkuPropertyValue) =>
    skuArr[i].listCode.includes(v.code),
  )
}
// const handleClose = () => {
//   emit('close')
// }

// 判断某属性是否在父组件skuArr中已被选中（不区分index）
const isDisabled = (code: string) => {
  return (props.skuArr ?? []).some((item: InterSkuArr) =>
    item.listCode.includes(code),
  )
}
defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
:deep(.el-checkbox__label) {
  font-size: 12px;
  width: 85px;
  overflow: hidden;
  white-space: nowrap;
  vertical-align: middle;
  text-overflow: ellipsis;
}
:deep(.el-checkbox) {
  padding-top: 3px;
  padding-bottom: 3px;
  margin-bottom: 10px !important;
}
.title {
  padding-left: 5px;
  font-size: 16px;
  line-height: 36px;
  font-weight: bold;
  border-bottom: 1px solid #efefef;
  margin-bottom: 10px;
}
.attribute-checkbox {
  padding-left: 5px;
}
.option_wrap + .option_wrap {
  border-top: 1px solid #bbb;
}
.dialog-footer {
  margin-top: 10px;
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
