<template>
  <div style="position: fixed; z-index: 10000">
    <el-dialog :title="jdt.title" :close-on-click-modal="false" :close-on-press-escape="false"
               v-model="jdt.isOpen" :before-close="closeModal">
      <el-progress :text-inside="true" :stroke-width="22" :percentage="percentage"
                   :status="percentage === 100 ? 'success' : ''">
        <span>
          {{ cptUpldRsTxt }}
          <i v-show="percentage < 100" class="el-icon-loading"></i>
          <i v-show="percentage === 100" class="el-icon-check"></i>
        </span>
      </el-progress>
      {{ index }} / {{ total }}
      <div v-if="notExcel">
        <el-tabs type="border-card" v-model="tabName">
          <el-tab-pane label="上传" name="上传">
            <ul style="overflow: auto" class="infinite-list" id="jdtRef">
              <li v-for="i in jdtData" :key="i" class="infinite-list-item" :class="infiniteList(i)">
                <div class="jdt-message" :title="i.message">{{ i.title }} 结果: {{ i.message }}</div>
              </li>
            </ul>
          </el-tab-pane>
          <el-tab-pane label="结果" name="结果" v-if="jdt.closeButton">
            <el-result icon="success" :title="jdt.title" :sub-title="tips">
              <template #extra>
                <el-button @click="closeModal" type="warning" icon="Close" index="small"> 关闭</el-button>
                <el-button @click="exportExcel" type="primary" icon="Download" index="small"> 导出Excel</el-button>
              </template>
            </el-result>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {computed, onMounted, ref} from 'vue'
import {useStore} from 'vuex'
import {setCallback} from '@/utils/websocket'
import {Export} from '@/utils/ExportExcel'
import {makePercentage} from './progUtils'
import {stringNotBlank} from '@/utils/blank-utils'
import {reactive, watch} from 'vue'
import Cookies from "js-cookie";
import {endLoading} from "@/utils/loading";

export default {
  setup() {
    const store = useStore()
    const jdt = computed(() => {
      return store.state.app.jdt
    })
    const cptUpldRsTxt = computed(() => {
      if (percentage.value < 100) {
        return `上传中 ( ${percentage.value}% ) ...`
      }
      return '上传完成(100%)'
    })
    const jdtData = ref([])

    const closeModal = () => {
      jdtData.value = []
      excelTitle.value = {}
      percentage.value = 0
      tips.value = ''
      tabName.value = '上传'
      store.commit('app/closeJdt')
    }

    const cuoWuLeiXin = reactive({
      success: 0,
      danger: 0,
      warning: 0,
      info: 0,
    })

    // 提示语
    const tips = ref('')
    const notExcel = ref(false)

    const total = ref(0)
    const index = ref(0)
    const excelTitle = ref({})
    const tabName = ref('上传')

    const socketCallback = (data) => {
      store.commit('app/setJdt', {
        title: Cookies.get('jdtTitle'),
        isOpen: true,
        closeButton: false,
      })
      endLoading()
      total.value = data.total
      index.value = data.index
      percentage.value = makePercentage(data.index, data.total)
      if (stringNotBlank(data.jdtType) && data.jdtType === 'download') {
        notExcel.value = false
      } else if (stringNotBlank(data.jdtType) && data.jdtType === 'upload') {
        for (let key in data) {
          if (key.indexOf('#') > -1) {
            let newKey = key.split('#')
            data[newKey[0]] = data[key]
            if (newKey[0] === 'type') {
              excelTitle.value.typeName = newKey[1]
            } else {
              excelTitle.value[newKey[0]] = newKey[1]
            }
            delete data[key]
          }
        }
        notExcel.value = true
        jdtData.value.push(data)
        const jdtRef = document.getElementById('jdtRef')
        try {
          jdtRef.scrollTop = jdtRef.scrollHeight
        } catch (e) {
          console.error('小bug不用管')
        }
      }
    }

    const percentage = ref(0)

    const infiniteList = (val) => {
      switch (val.type) {
        case 0:
          val.typeName = '成功'
          return 'jdt-success'
        case 1:
          val.typeName = '上传错误'
          return 'jdt-danger'
        case 2:
          val.typeName = '内部错误'
          return 'jdt-warning'
        default:
          val.typeName = '未知错误'
          return 'jdt-info'
      }
    }

    const exportExcel = () => {
      if (Object.keys(excelTitle.value).length === 0) {
        return (tips.value = '没有可以导出 Excel 的字段。')
      }
      const arr = {}
      for (let key in excelTitle.value) {
        // 这里获取 | 符号后面的 数字
        arr[key] = excelTitle.value[key].split('|')[1]
      }
      // 排序按照从小到大
      let result = Object.values(arr).sort((a, b) => {
        return a - b
      })
      const new_obj = {}
      // 按照排序生成新的对象
      for (let i = 0; i < result.length; i++) {
        Object.keys(arr).map((item, index) => {
          if (arr[item] === result[i]) {
            new_obj[item] = result[i]
          }
        })
      }
      const title = {}
      for (const a in new_obj) {
        title[a] = excelTitle.value[a].split('|')[0]
      }
      Export(jdtData.value, title, store.state.app.jdt.title)
    }

    watch(
        () => percentage.value,
        () => {
          if (percentage.value === 100) {
            if (jdtData.value.length > 0) {
              let success = 0
              let danger = 0
              let warning = 0
              let info = 0
              jdtData.value.forEach((item) => {
                if (item.type === 0) {
                  success++
                } else if (item.type === 1) {
                  danger++
                } else if (item.type === 2) {
                  warning++
                } else {
                  info++
                }
              })
              tips.value = `数据上传完成：成功：【${success}】、错误：【${danger}】、内部错误：【${warning}】、未知：【${info}】、总条数：【${jdtData.value.length}】`
            } else {
              tips.value = '上传成功'
            }
            tabName.value = '结果'
          }
        }
    )

    watch(
        () => jdt.value.isOpen,
        () => {
          if (!jdt.value.isOpen) {
            closeModal()
          }
        }
    )

    onMounted(() => {
      setCallback('jdtMessage', socketCallback)
    })

    return {
      jdt,
      closeModal,
      jdtData,
      infiniteList,
      exportExcel,
      percentage,
      cptUpldRsTxt,
      tips,
      notExcel,
      total,
      index,
      cuoWuLeiXin,
      tabName,
    }
  },
}
</script>

<style scoped>
.infinite-list {
  height: 300px;
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list .infinite-list-item {
  display: flex;
  height: 35px;
  margin: 10px;
  align-items: center;
  border-radius: 8px;
}

.jdt-success {
  background: #83e3534d;
  color: #67c23a;
}

.jdt-danger {
  background: #f38e8e5c;
  color: #f56c6c;
}

.jdt-warning {
  background: #e5a03a5c;
  color: #ea9c29;
}

.jdt-info {
  background: #a3a4ab6c;
  color: #909399;
}

.jdt-message {
  padding: 0 8px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>
