<template>
  <div class="box pa-3 d-flex">
    <div class="box-resource mr-3">
      <v-card class="box-resource-content d-flex flex-column" elevation="5">
        <v-banner single-line>
          <div class="d-flex align-center">
            <div class="py-2 title">数据资源预览 {{ fileName || '' }}</div>
            <v-spacer></v-spacer>
            <upload-btn
              text
              color="primary"
              @change="handleChangeFile"
            >
              <v-icon left>mdi-import</v-icon>
              导入Excel
            </upload-btn>
          </div>
        </v-banner>
        <div class="box-resource-content-excel" ref="excelBox">
          <file-review
            v-loading="showExcel"
            v-if="dataSource"
            ref="excel"
            :style="`height: ${ExcelHeight}px;`"
            :src="dataSource"
            @click:bottom-bar="initMap"
            @rendered="handleRendered"
            @error="showExcel = false"
          ></file-review>
          <template v-else>
            <none-page></none-page>
          </template>
        </div>
      </v-card>
    </div>
    <div class="box-left d-flex flex-column">
      <v-card class="box-left-content d-flex" elevation="5">
        <div class="box-left-content-panel d-flex flex-column">
          <div>
            <v-tabs v-model="tab">
              <v-tab>元数据设置</v-tab>
              <v-tab>基础信息配置</v-tab>
            </v-tabs>
          </div>
          <v-tabs-items v-model="tab">
            <v-tab-item>
              <edit-selected
                style="position: relative;height: 100%;"
                ref="selected"
                v-model="headMap"
                v-loading="loading"
              >
                <template #head>
                  <form-list ref="form" :items="formItems">
                    <template #actions>
                      <div style="width: 100%;" class="d-flex justify-space-between">
                        <v-btn
                          v-for="btn in controlBtn"
                          :key="btn.text"
                          rounded
                          class="buttons ml-3"
                          :color="btn.color"
                          :disabled="btn.disabled && !multipartFile"
                          @click="btn.handle(btn)"
                        >
                          <v-progress-circular
                            v-if="btn.loading"
                            indeterminate
                            :size="18"
                            width="2"
                            color="white"
                            class="mr-1"
                          ></v-progress-circular>
                          <v-icon left v-else>{{ btn.icon }}</v-icon>
                          {{ btn.text }}
                        </v-btn>
                      </div>
                    </template>
                  </form-list>
                </template>
              </edit-selected>
            </v-tab-item>
            <v-tab-item>
              <div class="pa-3 d-flex align-center justify-center flex-column">
                <edit-base ref="base" style="max-width: 500px;" hideEnName :names="names" :item-data="itemData"></edit-base>
                <v-btn
                  class="buttons"
                  rounded
                  color="primary"
                  :disabled="loading"
                  @click="handleSubmit"
                >
                  <v-icon left>mdi-send-variant</v-icon>
                  保存
                </v-btn>
              </div>
            </v-tab-item>
          </v-tabs-items>
        </div>
      </v-card>
    </div>

    <v-overlay :value="overlay" z-index="20">
      <div class="d-flex flex-column align-center justify-center" style="width: 300px;">
        <div class="mb-3">正在提交</div>
        <v-progress-linear
          color="primary"
          indeterminate
          rounded
          height="6"
        ></v-progress-linear>
      </div>
    </v-overlay>
  </div>
</template>

<script>
import UploadBtn from '@/components/UploadBtn'
// import FileReview from '@/components/MExcelReview'
import FileReview from '@/components/FileReview'
import EditSelected from '../editSelected'
import NonePage from '@/components/Common/empty.vue'
// import MDialog from '@/components/Dialog'
import { handleReadFile } from '@/utils/file'
import EditBase from '../editBase'
import FormList from '@/components/Form/list'
import { mapGetters } from 'vuex'
import { api } from '@/api/dataGovernance'
export default {
  name: 'data-resource-edit',
  props: {
    itemData: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    FormList,
    FileReview,
    UploadBtn,
    // MDialog,
    EditBase,
    EditSelected,
    NonePage
  },
  data () {
    return {
      tab: 0,
      overlay: false,
      formItems: {
        options: [
          {
            type: 'number',
            key: 'headRowNumber',
            value: 1,
            col: 4,
            label: '请输入表头所在行数 *',
            outlined: true,
            dense: true,
            rules: [v => v > 0 || '请输入表头所在行数'],
            change: this.handleChangeRow
          },
          {
            col: 8,
            slotName: 'actions'
          }
        ]
      },
      show: false,
      loading: false,
      controlBtn: [
        {
          icon: 'mdi-swap-horizontal',
          key: 'analysis',
          color: 'primary',
          loading: false,
          disabled: false,
          text: '解析',
          handle: this.handleAnalysis
        }
      ],
      result: {},
      ExcelHeight: 0,
      ExcelWidth: 0,
      showExcel: false,
      itemMap: {}, // 选中的映射
      dataSource: null, // excel数据
      multipartFile: null,
      fileName: null,
      // sheetName: null,
      headMap: [],
      isUpdateMap: true,
      content: '',
      contentLoad: '',
      renderSheet: true // 自动渲染
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    names () {
      return {
        name_en: this.result.data_resource?.name_en,
        name_zh: this.result.data_resource?.name_zh
      }
    }
  },
  created () {
    if (!Object.keys(this.itemData).length) {
      return
    }
    this.renderSheet = false
    this.headMap = this.itemData.parsed_data.map(e => {
      return {
        text: e.name_zh,
        map: e
      }
    }).reverse()
    this.result = {
      data_resource: {
        name_zh: this.itemData.name_zh,
        name_en: this.itemData.name_en
      }
    }
    // 获取文件流
    if (!this.itemData.url) {
      return
    }
    this.getFile(this.itemData.url)
  },
  mounted () {
    this.$nextTick(() => {
      this.ExcelHeight = this.$refs.excelBox.clientHeight
      this.ExcelWidth = this.$refs.excelBox.clientWidth
    })
  },
  methods: {
    async getFile (url) {
      try {
        const { data } = await api.getResourceFile({ url })
        this.multipartFile = new File([data], url, { type: data.type })
        this.showExcel = true
        this.fileName = url
        const type = url.split('.').pop()
        handleReadFile(data, type, files => {
          // 返回blob
          this.dataSource = files
        })
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 运行
    async handleRun () {
      if (!this.headMap.length) {
        return
      }
      this.loading = true
      const name = this.fileName.split('.')
      name.pop()

      const params = new FormData()
      params.append('data_resource', name.join('.'))
      params.append('meta_data', JSON.stringify(this.headMap.map(e => `${e.text}`)))
      params.append('file', this.multipartFile)

      try {
        const { data } = await api.resourceTranslate(params)
        this.result = data
        this.headMap.map(e => {
          e.map = {
            ...data.head_data.find(_e => _e.name_zh === e.text),
            master_data: null,
            data_standard: null
          }
          return e
        })
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    // handleShow () {
    //   if (!this.headMap.length) {
    //     this.$snackbar.error('请先补充完整资料')
    //     return
    //   }
    //   this.show = true
    // },
    // 提交
    async handleSubmit () {
      if (!this.headMap.length) {
        this.$snackbar.error('请先补充元数据设置')
        this.tab = 0
        return
      }
      this.overlay = true
      try {
        const obj = this.$refs.base.getValue()
        if (!obj) {
          return
        }
        const { addLine, ...params } = obj
        // 添加生产线
        // if (addLine) {
        //   return
        // }
        // 上传文件
        const { data } = await api.uploadResource({ file: this.multipartFile })
        if (this.itemData.id) {
          Object.assign(params, {
            id: this.itemData.id,
            parsed_data: this.headMap.map(e => {
              const { data_standard: dataStandard, ..._obj } = e.map
              return {
                data_standard: dataStandard?.id ?? null,
                ..._obj
              }
            }),
            type: 'structure',
            name_en: this.result.data_resource.name_en,
            url: data.url // 文件上传路径
          })
        } else {
          Object.assign(params, {
            additional_info: {
              head_data: this.headMap.map(e => e.map),
              data_resource: this.result.data_resource
            },
            type: 'structure',
            url: data.url // 文件上传路径
          })
        }
        const subApi = this.itemData.id ? api.resourceUpdateByDDL : api.saveResource
        await subApi(params)
        this.$snackbar.success('提交成功')
        this.$emit('close')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.overlay = false
      }
    },
    // 解析
    async handleAnalysis (item) {
      item.loading = true
      await this.initMap()
      item.loading = false
    },
    handleRendered () {
      this.showExcel = false
      if (!this.renderSheet) {
        return
      }
      // 渲染完毕
      this.initMap()
    },
    async initMap () {
      if (!this.isUpdateMap || !this.dataSource) {
        return
      }
      const row = this.formItems.options.find(e => e.key === 'headRowNumber').value
      const mapItems = this.$refs.excel?.getRow(row - 1)
      if (!mapItems || !mapItems.length) {
        this.headMap = []
        return
      }
      this.headMap = mapItems.map(_e => {
        return {
          map: null,
          text: _e
        }
      })
      // 执行翻译
      await this.handleRun()
    },
    async handleChangeFile (multipartFile) {
      this.multipartFile = multipartFile
      this.showExcel = true
      const type = multipartFile.name.split('.').pop()
      if (type !== 'xlsx' && type !== 'xls') {
        this.$snackbar.error('请导入Excel文件')
        return
      }

      // 导入文件解锁
      this.fileName = multipartFile.name
      this.renderSheet = true
      handleReadFile(multipartFile, type, files => {
        // 返回blob
        this.dataSource = files
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  flex: 1;
  overflow: hidden;
  &-resource {
    flex: 1;
    width: 0;
    height: 100%;
    &-content {
      height: 100%;
      &-excel {
        position: relative;
        overflow-y: auto;
        height: 0;
        flex: 1;
      }
    }
  }
  &-left {
    // width: 600px;
    width: 50%;
    &-toolbar {
      flex-grow: 0;
    }
    &-content {
      height: 0;
      flex: 1;
      position: relative;
      &-panel {
        width: 100%;;
        flex: 1;
      }
    }
  }
  &-right {
    position: relative;
    width: 400px;
    height: 100%;
    &-content {
      height: 100%;
      &-control {
        height: 100%;
        &-edit {
          flex: 1;
          overflow: auto;
        }
      }
    }
  }
}
.title {
  color: #1976D2;
  font-weight: 600;
}
::v-deep .v-tabs-items {
  height: 0;
  flex: 1;
  .v-window-item {
    overflow: auto;
    height: 100%;
  }
  .v-window__container {
    height: 100%;
  }
}
</style>
