import _get from 'lodash.get'
import { export_json_to_excel } from '@/Excel/Export2Excel'
export default {
  props: {
    modelName: {
      type: String,
      default: () => ''
    },
    layoutKey: {
      type: String,
      default: () => ''
    }
  },
  filters: {
    capitalize: (list, filterWorld, tableColumns) => {
      return list.filter(row => {
        if (!filterWorld) {
          return true
        }
        const world = filterWorld.toLocaleLowerCase()
        let flag = false
        for (const a in tableColumns) {
          const val = _get(row, tableColumns[a].key)
          if (val && val.toString().toLocaleLowerCase().includes(world)) {
            flag = true
            break
          }
        }
        return flag
      })
    }
  },
  data() {
    return {
      filterWorld: '',
      dialogVisibleTable: false,
      showTableColumnsCopy: [],
      showTableColumns: [],
      tableColumnsCopy: [],
      localStorageName: '',
      // 存储排序的名称
      localStorageSortName: ''
    }
  },
  watch: {
    'tableConfig.tableColumns'() {
      this.getColumns()
    },
    'dialogVisibleTable'(flag) {
      if (flag) {
        // this.showTableColumns.forEach(col => {
        //   const item = this.tableConfig.tableColumns.find(r => r.key === col.key)
        //   if (item) {
        //     item.defaultItem = col.defaultItem
        //   }
        // })
        // this.tableColumnsCopy = JSON.parse(JSON.stringify(this.tableConfig.tableColumns))
        // this.showTableColumnsCopy = JSON.parse(JSON.stringify(this.showTableColumns))
        // 读取本地‘不展示的’列
        let unCheckList = localStorage.getItem(this.localStorageName)
        // 读取本地‘排序’列
        let sortList = localStorage.getItem(this.localStorageSortName)
        unCheckList = JSON.parse(unCheckList)
        sortList = JSON.parse(sortList)
        const checkList = []
        let tableColumnsCopy = []
        let showTableColumnsCopy = []
        if (Array.isArray(unCheckList) && Array.isArray(this.tableConfig.tableColumns)) {
          tableColumnsCopy = this.tableConfig.tableColumns.map(t => {
            t = JSON.parse(JSON.stringify(t))
            // 找出排除的列
            const item = unCheckList.find(m => m.key === t.key)
            if (item) {
              t.defaultItem = false
            } else {
              t.defaultItem = true
              checkList.push(t.key)
              showTableColumnsCopy.push(t)
            }
            return t
          })
          if (Array.isArray(sortList) && sortList.length > 0) {
            const sortItems = []
            sortList.forEach(k => {
              const idx = showTableColumnsCopy.findIndex(n => n.key === k)
              if (idx > -1) {
                const item = showTableColumnsCopy.splice(idx, 1)[0]
                sortItems.push(item)
              }
            })
            showTableColumnsCopy = sortItems.concat(showTableColumnsCopy)
          }
        }
        this.checkList = checkList
        this.tableColumnsCopy = tableColumnsCopy
        this.showTableColumnsCopy = showTableColumnsCopy
        unCheckList = this.tableColumnsCopy.filter(m => !m.defaultItem)
        localStorage.setItem(this.localStorageName, JSON.stringify(unCheckList))
      } else {
        this.tableColumnsCopy = []
        this.showTableColumnsCopy = []
      }
    }
  },
  created() {
    this.getColumns()
  },
  mounted() {
    const userId = localStorage.getItem('userId')
    this.localStorageName = `Table-${this.modelName || this.configDetails.rootBaseModelName}-${this.layoutKey}-${userId}`
    this.localStorageSortName = `Table-Sort-${this.modelName || this.configDetails.rootBaseModelName}-${this.layoutKey}-${userId}`
    this.getColumns()
  },
  methods: {
    export_excel() {
      const tHeader = []
      const filterVal = []
      // 使用全列表
      this.tableConfig.tableColumns.forEach(col => {
        if (!col.component) {
          tHeader.push(col.title)
          filterVal.push(col.key)
        }
      })
      // 加入默认项 id
      tHeader.push('id')
      filterVal.push('id')
      const data = this.formatJson(filterVal, this.tableData)
      export_json_to_excel(tHeader, data, this.localStorageName + '-' + this.$moment().format('YYYYMMDDHHmmss'))
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(row => filterVal.map(j => _get(row, j)))
    },
    removeVisibleColumn(index) {
      const item = JSON.parse(JSON.stringify(this.showTableColumnsCopy[index]))
      let idex = this.tableColumnsCopy.findIndex(c => c.key === item.key)
      item.defaultItem = false
      this.$set(this.tableColumnsCopy, idex, item)
      idex = this.showTableColumnsCopy.findIndex(c => c.key === item.key)
      if (idex > -1) {
        this.showTableColumnsCopy.splice(idex, 1)
      }
    },
    saveConfig(flag = false) {
      // if (!flag) {
      //   const showTableColumns = JSON.parse(JSON.stringify(this.showTableColumnsCopy))
      //   this.showTableColumns = showTableColumns
      //   const tableColumns = JSON.parse(JSON.stringify(this.tableColumnsCopy))
      //   tableColumns.forEach(col => {
      //     const item = this.tableConfig.tableColumns.find(r => r.key === col.key)
      //     if (item) {
      //       item.defaultItem = col.defaultItem
      //     }
      //   })
      //   this.dialogVisibleTable = false
      // }

      // // save config
      // localStorage.setItem(this.localStorageName, JSON.stringify(this.showTableColumns))
      if (!flag) {
        const showTableColumns = JSON.parse(JSON.stringify(this.showTableColumnsCopy))
        this.showTableColumns = showTableColumns
        const tableColumns = JSON.parse(JSON.stringify(this.tableColumnsCopy))
        tableColumns.forEach(col => {
          const item = this.tableConfig.tableColumns.find(r => r.key === col.key)
          if (item) {
            item.defaultItem = col.defaultItem
          }
        })
        this.dialogVisibleTable = false
      }
      // 只保存未选择的列
      if (Array.isArray(this.tableColumnsCopy) && this.tableColumnsCopy.length > 0) {
        const unCheckList = this.tableColumnsCopy.filter(m => !m.defaultItem)
        localStorage.setItem(this.localStorageName, JSON.stringify(unCheckList))
      }
      // 保存排序的字段
      if (Array.isArray(this.showTableColumnsCopy) && this.showTableColumnsCopy.length > 0) {
        const sortList = this.showTableColumnsCopy.map(m => m.key)
        localStorage.setItem(this.localStorageSortName, JSON.stringify(sortList))
      }
    },
    setColumns() {
      this.showTableColumns = this.tableConfig.tableColumns.map(col => {
        // 没有定义默认项 定义默认项 避免没有可显示项
        if (!col.hasOwnProperty('defaultItem')) {
          col.defaultItem = true
        }
        return col
      })
      this.showTableColumns = this.showTableColumns.filter(col => col.fixedItem || col.defaultItem)
      this.saveConfig(true)
    },
    getColumns() {
      let unCheckList = localStorage.getItem(this.localStorageName)
      unCheckList = JSON.parse(unCheckList)
      // 获取选择列
      if (Array.isArray(unCheckList) && Array.isArray(this.tableConfig.tableColumns)) {
        this.showTableColumns = this.tableConfig.tableColumns.map(t => {
          t = JSON.parse(JSON.stringify(t))
          const item = unCheckList.find(m => m.key !== t.key)
          t.defaultItem = !item
          return t
        })
      }
      // try {
      //   let showTableColumns = localStorage.getItem(this.localStorageName)
      //   showTableColumns = JSON.parse(showTableColumns)
      //   if (!showTableColumns || !this.showConfig || this.isPreview) { // 没有读取到配置 或 不设置列配置
      //     this.setColumns()
      //     return
      //   }
      //   this.showTableColumns = showTableColumns
      //   if (this.tableConfig && this.tableConfig.tableColumns) {
      //     // 新加字段
      //     this.tableConfig.tableColumns.forEach(col => {
      //       const item = this.showTableColumns.find(r => r.key === col.key)
      //       if (!item) {
      //         col.defaultItem = true
      //         this.showTableColumns.push(col)
      //       }
      //     })
      //     this.showTableColumns.forEach(col => {
      //       const item = this.tableConfig.tableColumns.find(r => r.key === col.key)
      //       if (item) {
      //         item.defaultItem = col.defaultItem
      //       } else {
      //         col.remove = true
      //       }
      //     })
      //     this.showTableColumns = this.showTableColumns.filter(r => !r.remove)
      //   }
      // } catch {
      //   if (this.tableConfig && this.tableConfig.tableColumns) {
      //     this.setColumns()
      //   }
      // }
    },
    changeVisibleColumn(index, flag) {
      const item = JSON.parse(JSON.stringify(this.tableColumnsCopy[index]))
      let idex = this.tableColumnsCopy.findIndex(c => c.key === item.key)
      item.defaultItem = flag
      this.$set(this.tableColumnsCopy, idex, item)
      if (flag) {
        this.showTableColumnsCopy.push(item)
      } else {
        idex = this.showTableColumnsCopy.findIndex(c => c.key === item.key)
        this.showTableColumnsCopy.splice(idex, 1)
      }
    },
    changeAllVisibleColumn(flag) {
      if (!flag) {
        this.showTableColumnsCopy = this.showTableColumnsCopy.filter(col => col.fixedItem)
        this.tableColumnsCopy.forEach(col => {
          if (!col.fixedItem) {
            col.defaultItem = false
          }
        })
      } else {
        this.tableColumnsCopy.forEach(col => {
          if (!col.defaultItem) {
            col.defaultItem = true
            this.showTableColumnsCopy.push(col)
          }
        })
      }
    }
  }
}