<template>
  <div id="ImportData">
    <h2>数据导入</h2>
    <el-divider></el-divider>
    <el-form v-if="auth" :model="importForm" ref="importForm" :rules="importFormRules" :label-width="120">
      <el-form-item label="数据类型：" prop="dataType">
        <el-select v-model="importForm.dataType" placeholder="请选择要导入的数据类型" clearable>
          <el-option v-for="(item,key) in dataTypes" :key="key" :label="item.label" :value="key"/>
        </el-select>
      </el-form-item>
      <el-form-item label="导入类型：" prop="importType">
        <el-select v-model="importForm.importType" placeholder="请选择导入的文件类型" :disabled="!importForm.dataType"
                   clearable>
          <template v-for="(item,key) in importTypes">
            <el-option :key="key" :value="item.value" :label="item.label"
                       v-if="currDataType.importTypes && currDataType.importTypes.indexOf(item.id)>-1"/>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="文件选择：" prop="file">
        <el-upload ref="import-upload" :disabled="!importForm.importType"
                   v-model:file-list="importForm['fileList']"
                   :limit="1"
                   :accept="currImportType.accept"
                   :auto-upload="false"
                   :on-exceed="handleUploadExceed"
                   :on-change="handleUploadChange"
                   :before-remove="handleUploadRemove"
                   style="min-width: 50%"
        >
          <el-input v-model="importForm.file" :disabled="true" type="hidden"/>
          <el-button type="default" size="small" :disabled="!importForm.importType">选择文件</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="字段映射：" v-if="importForm.file">
        <el-table :data="importForm.tableData" border stripe max-height="220">
          <el-table-column prop="fieldName" label="字段名称"/>
          <el-table-column prop="title" label="字段说明"/>
          <el-table-column prop="newFieldName" label="文件中字段名称">
            <template #default="scope">
              <el-form-item :prop="scope.row.fieldName==='数据类型'?'menuId':scope.row.fieldName">
                <el-select v-model="importForm['menuId']" @change="handleMenuIdSelect"
                           v-if="scope.row.fieldName==='数据类型'">
                  <el-option v-for="item in category" :key="item.id" :label="item.title" :value="item.id"/>
                </el-select>
                <el-input v-else v-model="importForm[scope.row.fieldName]" placeholder="请输入文件中对应字段的名字"/>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label-width="70%">
        <el-button type="primary" @click="submit">确认导入</el-button>
      </el-form-item>
    </el-form>
    <el-empty v-if="!auth" description="无权限"></el-empty>
  </div>
</template>

<script>
import {genFileId} from "element-plus";
import menuApi from "@/api/data/MenuData";
import api from "@/api/data/ImportData"
import importData from "@/api/data/ImportData";

export default {
  data() {
    return {
      auth: false,
      importForm: {},
      importFormRules: {
        dataType: [
          {required: true, message: '请选择数据类型', trigger: 'blur'},
          {required: true, message: '请选择数据类型', trigger: 'change'}
        ],
        importType: [
          {required: true, message: '请选择导入类型', trigger: 'blur'},
          {required: true, message: '请选择导入类型', trigger: 'change'}
        ],
        file: [
          {required: true, message: '请选择文件', trigger: 'blur'},
          {required: true, message: '请选择文件', trigger: 'change'},
        ],
        title: [
          {required: true, message: '字段不能为空', trigger: 'blur'},
          {required: true, message: '字段不能为空', trigger: 'change'},
        ],
        content: [
          {required: true, message: '字段不能为空', trigger: 'blur'},
          {required: true, message: '字段不能为空', trigger: 'change'},
        ],
        menuId: [
          {required: true, message: '字段不能为空', trigger: 'blur'},
          {required: true, message: '字段不能为空', trigger: 'change'},
        ],
      },
      dataTypes: {
        1: {label: '二维数据', value: 1, importTypes: [1, 2, 3], importId: 1},
        2: {label: '三维数据', value: 2, importTypes: [1, 2], importId: 4},
        3: {label: '业务数据', value: 3, importTypes: [1, 2, 3], importId: 3},
        4: {label: '模型数据', value: 4, importTypes: [1], importId: 5},
        // 5: {label: '元数据', value: 5, importTypes: [1], importId: 6},
        6: {label: '物联感知数据', value: 6, importTypes: [1, 2, 3], importId: 2},
      },
      currDataType: {},
      currImportType: {},
      importTypes: {
        'Excel': {id: 1, label: 'Excel', value: 'Excel', accept: '.xls,.xlsx'},
        'GeoJson': {id: 2, label: 'GeoJson', value: 'GeoJson', accept: '.json,.geojson'},
        'Shape': {id: 3, label: 'Shape', value: 'Shape', accept: '.zip'},
      },
      uploadType: {
        Excel: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
        GeoJson: ['application/json', 'application/geojson', ''],
        Shape: ['application/x-zip-compressed'],
      },
      fieldTableData: [
        {title: '标题', fieldName: 'title', newFieldName: 'title', dataType: [1,2,3,4,6], importType: [1,2,3]},
        {title: '描述', fieldName: 'content', newFieldName: 'content', dataType: [1,2,3,4,6], importType: [1,2,3]},
        {title: '类别', fieldName: '数据类型', newFieldName: '', dataType: [1,2,3,4,6], importType: [1,2,3]},
        {title: 'url地址', fieldName: 'url', newFieldName: 'url', dataType: [4,6], importType: [1,2,3]},
        {title: '纬度', fieldName: 'latStr', newFieldName: '', dataType: [1,2,3,4,6], importType: [1]},
        {title: '经度', fieldName: 'lonStr', newFieldName: '', dataType: [1,2,3,4,6], importType: [1]},
        {title: '高程', fieldName: 'height', newFieldName: '', dataType: [2,4], importType: [1]},
        {title: '地名地址库', fieldName: 'address', newFieldName: 'address', dataType: [1,2,3,4,6], importType: [1,2,3]},
        {title: '地名地址库ID', fieldName: 'addId', newFieldName: 'addId', dataType: [1,2,3,4,6], importType: [1,2,3]},
        {title: '第三方id', fieldName: 'thirdId', newFieldName: 'thirdId', dataType: [1,2,3,4,6], importType: [1,2,3]},
        {title: '海拔', fieldName: 'elevation', newFieldName: '', dataType: [4], importType: [1,2,3]},
        {title: '是否移动', fieldName: 'isMove', newFieldName: '', dataType: [4], importType: [1,2,3]},
      ],
      category: []
    }
  },
  props: {},
  watch: {
    "importForm.dataType": function (newVal, oldVal) {
      if (newVal) {
        newVal = Number(newVal)
        this.currDataType = this.dataTypes[newVal];
        this.importForm.importType = '';
        this.importForm.file = null;
        this.importForm['fileList'] = [];
      } else {
        this.currDataType = {};
        this.importForm = {};
      }
    },
    "importForm.importType": function (newVal, oldVal) {
      if (newVal) {
        let dataType = Number(this.importForm.dataType);
        this.getMenuData(dataType)
        this.currImportType = this.importTypes[newVal]
        this.importForm.tableData = this.fieldTableData.filter(i=> i.dataType.indexOf(dataType)>-1 && i.importType.indexOf(this.currImportType.id)>-1);
      } else {
        this.currImportType = {};
        this.importForm.file = null;
        this.importForm['fileList'] = [];
      }
    }
  },
  created() {
    let userInfo = this.$store.state.userInfo;
    if (userInfo.userLevel < 2
        || (userInfo.userLevel === 2) && userInfo.serviceId.split(',').indexOf(this.$constant.serviceId) > -1) {
      this.auth = true;
    }
  },
  mounted() {
  },
  methods: {
    handleUploadChange(file) {
      let fileObj = file.raw;
      if (this.uploadType[this.importForm.importType].indexOf(fileObj.type) < 0) {
        this.$message({message: '不支持的文件类型', type: 'warning'})
        this.$refs['import-upload'].clearFiles();
        this.importForm['fileList'] = []
        this.importForm.file = null;
        return;
      }
      this.importForm.file = file.raw;
    },
    getMenuData(type) {
      let app = this;
      let params = {
        type: type,
        parentId: "1",
      }
      menuApi.getMenuData(params).then(res => {
        if (res.code === 200) {
          app.category = res.content;
          if (app.importForm.dataType==1 && app.importForm.importType=='Excel') {
            app.category = app.category.filter(i=>i.geometryType=='Point')
          }
        }
      })
    },
    handleMenuIdSelect(val) {
      for (let i = 0; i < this.category.length; i++) {
        let item = this.category[i];
        if (item.id == val) {
          this.importForm['menuNameTwo'] = item.title
          break;
        }
      }
    },
    handleUploadExceed(file) {
      this.$refs['import-upload'].clearFiles();
      file = file[0];
      file.uid = genFileId()
      this.$refs['import-upload'].handleStart(file);
    },
    handleUploadRemove(val) {
      this.importForm.file = null;
    },
    submit() {
      let app = this;
      this.$refs.importForm.validate((valid, obj) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(app.importForm));
          delete params.tableData;
          delete params.fileList;
          delete params.dataType;
          delete params.importType;
          params['userName'] = app.$store.state.userInfo.username;
          params['file'] = app.importForm.file;
          params['menuNameOne'] = '二维数据'
          params['importType'] = app.currDataType.importId;
          app.$util.loading.handleLoading(true);
          api.importData(params, app.importForm.importType).then(res => {
            res = res.data;
            if (res.code === 200) {
              app.$message({message: '导入成功', type: 'success'})
            }
            app.$util.loading.handleLoading(false);
          }).catch(err => {
            app.$util.loading.handleLoading(false);
            app.$message({message: err.message, type: 'error'})
          })
        } else {
          app.$util.loading.handleLoading(false);
          app.$message({message: '请先检查并完善信息', type: 'warning'})
        }
      })
    },
  }
}
</script>