import options from '@/utils/dict/options'
import { fetchPuzzleGoals, fetchSortList } from '@/api/toy/sort'
import { getDictLabel } from '@/utils/dict/config'
import '@/assets/styles/jsxStyle.scss'

const toySortMap = {
  1: { key: 'putArea', level: '1' },
  2: { key: 'toyCategory', level: '2' },
  3: { key: 'detailCategory', level: '3' },
  4: { key: 'developmentGoals', level: '4' }, // 发展目标
  5: { key: 'diversityLabels', level: '5' } // 多样性
}
export default {
  props: {
    toyCategory: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      levelOptions: new Map(),
      puzzleGoals: [], // 发展目标
      sortTreeData: [],
      formState: [],
      noSetDevelop: false // 是否需要设置发展目标；分类数据单独处理：选择益智玩具>认知加工玩具>常识认知类，的玩具无需选择发展目标 isDevelopmentGoals === 1
    }
  },
  watch: {
    formState: {
      handler(val) {
        if (val && val.length > 0) {
          const toyCategory = {}
          val.forEach((category) => {
            const hasValue = Array.isArray(category)
              ? category.length > 0
              : category && JSON.stringify(category) !== '{}'
            if (hasValue) {
              // 益智区的发展目标 多选
              const formKey = Array.isArray(category)
                ? toySortMap[category[0].level].key
                : toySortMap[category.level].key
              toyCategory[`${formKey}Code`] = Array.isArray(category)
                ? category.map((item) => item.sortCode).join(',')
                : category.sortCode
            }
          })
          this.$emit('update:toyCategory', toyCategory)
        }
      },
      immediate: true,
      deep: true
    },
    toyCategory: {
      handler(val) {
        this.$nextTick(() => this.formatLevelOptions())
      }
      // immediate: true,
      // deep: true
    }
  },
  created() {
    this.getPuzzleGoals()
    this.getSortList()
  },
  methods: {
    onSubmit() {
      const toyCategory = {}
      this.formState.forEach((category) => {
        const hasValue = Array.isArray(category)
          ? category.length > 0
          : category && JSON.stringify(category) !== '{}'
        if (hasValue) {
          // 益智区的发展目标 多选
          const formKey = Array.isArray(category)
            ? toySortMap[category[0].level].key
            : toySortMap[category.level].key
          toyCategory[`${formKey}Code`] = Array.isArray(category)
            ? category.map((item) => item.sortCode).join(',')
            : category.sortCode
        }
      })
      this.$emit('update:toyCategory', toyCategory)
    },
    // 校验必须选到末级
    onValidator() {
      return this.commonValidate()
      // if (this.toyCategory.putAreaCode) {
      //   const val = '1'
      //   this.$emit('changeType', val)
      //   return this.commonValidate()
      // } else {
      //   const val = '2'
      //   this.$emit('changeType', val)
      //   return this.onValidatorEmpty()
      // }
    },
    commonValidate() {
      const formState = this.formState.filter((k) => Array.isArray(k) ? k.length > 0 : k)
      const notEmpty = formState.filter(obj => obj ? (Array.isArray(obj) ? obj.filter(sort_ => sort_.sortCode).length > 0 : obj && obj.sortCode) : false)
      const levelKeys = Array.from(this.levelOptions.keys())
      const filterKeys = this.noSetDevelop ? levelKeys.filter(k => Number(k) !== 4) : levelKeys
      const valid =
        filterKeys.length > notEmpty.length - 1
      let batchValid = false
      if (!valid) {
        const level1 = this.formState && this.formState[0]
        Array.from(this.levelOptions.keys()).forEach((k, index) => {
          if (Number(k) === 4 && Number(level1.isBatch) > 0) {
            batchValid =
              this.formState[index + 1] && this.formState[index + 1].length > 3
          }
        })
      }
      return {
        validValue: valid,
        batchValid: batchValid
      }
    },
    // 校验非空 true: 校验失败 false: 校验成功
    onValidatorEmpty() {
      const validValue =
        this.formState &&
        (this.formState.length === 0 ||
          this.formState.filter((k) => !!k).length === 0)
      return {
        validValue
      }
    },
    getPuzzleGoals() {
      fetchPuzzleGoals().then(({ data }) => {
        this.puzzleGoals = data
      })
    },
    setLevelOptions(selected, formIndex) {
      if (selected) {
        if (selected.children && selected.children.length > 0) {
          const level = selected.children[0].level
          // 只有益智玩具的三级 设置
          if (this.formState && Number(this.formState[0].isBatch) > 0 && Number(selected.level) === 3) this.noSetDevelop = Number(selected.isDevelopmentGoals) === 1
          this.levelOptions.set(level, selected.children)
        } else {
          // 益智类玩具
          if (this.formState && Number(this.formState[0].isBatch) > 0) {
            if (!this.noSetDevelop) this.levelOptions.set(4, this.puzzleGoals)
          }
        }
        let formCode = null
        let selectCatergory = null
        const nextOptions = selected.nextLevel
          ? this.levelOptions.get(selected.nextLevel)
          : []
        const isSetNext = nextOptions && nextOptions.length > 0
        if (isSetNext) {
          formCode = toySortMap[selected.nextLevel].key + 'Code'
          selectCatergory = this.levelOptions.get(selected.nextLevel).find((item) => item.sortCode === this.toyCategory[formCode])
          if (selectCatergory) {
            this.setLevelOptions(selectCatergory, formIndex + 1)
            this.formState[formIndex] = selectCatergory
          } else {
            this.formState[formIndex] = this.formState && Number(this.formState[0].isBatch) > 0 ? [] : {}
          }
        } else {
          // 益智区发展目标
          if (this.formState && Number(this.formState[0].isBatch) > 0 && !this.noSetDevelop) {
            formCode = 'developmentGoalsCode'
            const codeArr = (this.toyCategory[formCode] && this.toyCategory[formCode].split(',')) || ''
            selectCatergory = this.levelOptions.get(4).filter((item) => codeArr.includes(item.sortCode))
            this.formState[formIndex] = selectCatergory
          }
        }
      }
    },
    getSortList() {
      fetchSortList().then(({ data }) => {
        this.sortTreeData = this.handleTree(data, 'sortCode', 'parentCode')
        this.formatLevelOptions()
      })
    },
    formatLevelOptions() {
      this.noSetDevelop = false
      this.levelOptions = new Map()
      if (this.toyCategory.putAreaCode) {
        const level1 = this.sortTreeData.find(
          (item) => item.sortCode === this.toyCategory.putAreaCode
        )
        this.formState[0] = level1
        this.setLevelOptions(level1, 1)
        // this.onInitCategory(level1, true)
      } else {
        this.formState = []
      }
    },
    async onInitCategory(val, isSetNextLevel) {
      if (val) {
        let selectItem = val
        // 发展目标多选以第一个目标的多样性
        if (Array.isArray(val) && val.length > 0) selectItem = val[0]
        // 所选的是益智区的三级 且 不需要设置发展目标
        if (this.formState && Number(this.formState[0].isBatch) > 0 && selectItem && Number(selectItem.level) === 3) {
          this.noSetDevelop = Number(selectItem.isDevelopmentGoals) === 1
        } else {
          this.noSetDevelop = false
        }
        const hasChildren =
          selectItem && selectItem.children && selectItem.children.length > 0
        if (hasChildren) {
          const level = selectItem.children[0].level
          this.levelOptions.set(
            level,
            isSetNextLevel ? selectItem.children : []
          )
          this.onInitCategory(selectItem.children[0], false)
        } else {
          // 选择的末级是益智区的末级且需要选择发展目标
          if (this.formState && Number(this.formState[0].isBatch) > 0) {
            this.levelOptions.set(4, this.puzzleGoals)
          }
          if (this.noSetDevelop) this.levelOptions.delete(4)
        }
      }
    },
    handleChange(val, modelValueIndex) {
      this.formState = this.formState.splice(0, modelValueIndex + 1)
      const level1 = this.formState && this.formState[0]
      // 重置所选项之后的下拉项
      Array.from(this.levelOptions.keys()).forEach((k, index_) => {
        if (Number(index_ + 1) > modelValueIndex) {
          this.levelOptions.delete(k)
        }
      })
      this.onInitCategory(val, true)
      Array.from(this.levelOptions.keys()).forEach((k, index_) => {
        if (Number(index_ + 1) > modelValueIndex) {
          this.formState[index_ + 1] =
            Number(k) === 4 && Number(level1.isBatch) > 0 ? [] : null
        }
      })
    }
  },
  render() {
    const { sortTreeData, formState } = this
    const levelKeys = Array.from(this.levelOptions.keys())
    const filterKeys = this.noSetDevelop ? levelKeys.filter(k => Number(k) !== 4) : levelKeys
    return (
      <div>
        <el-select
          style={{ width: '100px' }}
          class={'mr10 short-select'}
          vModel={this.formState[0]}
          clearable
          value-key='sortCode'
          placeholder='一级分类'
          on-change={(val) => this.handleChange(val, 0)}
        >
          {sortTreeData.map((item) => {
            return (
              <el-option
                disabled={item.status === '1'}
                key={item.sortCode}
                label={item.sortName}
                value={item}
              />
            )
          })}
        </el-select>
        {filterKeys.map((k, index) => {
          const multiple =
            formState && Number(formState[0].isBatch) > 0 && Number(k) === 4
          return (
            <el-select
              class={multiple ? 'mr10' : 'short-select mr10'}
              vModel={formState[index + 1]}
              clearable
              multiple={multiple}
              multiple-limit={3}
              collapse-tags={multiple}
              value-key='sortCode'
              placeholder={`${getDictLabel(options.sortLevel, k)}`}
              on-change={(val) => this.handleChange(val, index + 1)}
            >
              {this.levelOptions.get(k).map((option) => {
                return (
                  <el-option
                    disabled={option.status === '1'}
                    key={option.sortCode}
                    label={option.sortName}
                    value={option}
                  />
                )
              })}
            </el-select>
          )
        })}
      </div>
    )
  }
}
