<template>
  <el-dialog v-dialogDrag v-loading="loadingUpload" :title="$t('map.createNewMap')" :visible.sync="dialogShow" width="30%" :close-on-click-modal="false" :before-close="handleClose">
    <div>
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane :label="$t('map.normalCreate')" name="first">
          <el-form ref="newForm" label-position="right" :model="newModel" label-width="140px" size="mini" :rules="newRules" @submit.native.prevent>
            <el-form-item :label="$t('map.skinName')" prop="skinCode">
              <el-select v-model="newModel.skinCode" :placeholder="$t('map.pleaseSelect')">
                <el-option
                  v-for="item in skinCodeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('map.mapName')" prop="name">
              <el-input v-model="newModel.name" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="$t('map.publishMapCreation')" name="second">
          <el-form ref="pullForm" label-position="right" :model="pullModel" :rules="pullRules" label-width="140px" size="mini">
            <el-form-item :label="$t('map.publishMap')+ ':'" prop="id">
              <el-select v-model="pullModel.id" :placeholder="$t('map.pleaseSelect')">
                <el-option
                  v-for="item in publishMapList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('map.mapName')" prop="name">
              <el-input v-model="pullModel.name" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogShow = false">{{ $t('map.cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="create">{{ $t('map.confirm') }}</el-button>
    </span>
  </el-dialog>

</template>

<script>
import { newMap, postBuildMapImport, newUsePublishMap } from '@/api/jmap/mapdraft';
import { listPublishMap } from '@/api/jmap/map';
import XLSX from 'xlsx';
import { translate, translateSheetTitle } from '@/scripts/translate';
import { sheet_to_json } from '@/utils/Export2Excel';
import { getSkinCodeList } from '@/api/management/mapskin';

export default {
    name: 'MapCreate',
    props: {
        skinCode: {
            type: String,
            default() {
                return '';
            }
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            file: null,
            rABS: false,
            loadingUpload: false,
            resultJSON: {},
            activeTab: 'first',
            skinCodeList: [],
            publishMapList: [],
            newModel: {
                id: '',
                name: '',
                skinCode: ''
            },
            pullModel: {
                id: '',
                name: ''
            },
            newRules: {
                name: [
                    { required: true, message: this.$t('rules.pleaseEnterMapName'), trigger: 'blur' }
                ],
                skinCode: [
                    { required: true, message: this.$t('rules.pleaseChooseSkinCode'), trigger: 'change' }
                ]
            },
            pullRules: {
                id: [
                    { required: true, message: this.$t('rules.pleaseSelectMapSource'), trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('rules.pleaseEnterMapName'), trigger: 'change' }
                ]
            },
            cityList: []
        };
    },
    watch: {
        skinCode(val) {
            this.newModel.skinCode = val;
        }
    },
    methods: {
        show() {
            this.dialogShow = true;
            this.initLoadData();
        },
        close() {
            if (this.$refs.newForm) {
                this.$refs.newForm.resetFields();
            }
            if (this.$refs.pullForm) {
                this.$refs.pullForm.resetFields();
            }
            this.dialogShow = false;
        },
        handleClose() {
            this.close();
        },
        initLoadData() {
            this.skinCodeList = [];
            getSkinCodeList().then(response => {
                this.skinCodeList = response.data;
            });
            this.$Dictionary.cityType().then(list => {
                this.cityList = list;
            });
            listPublishMap().then(response => {
                this.publishMapList = response.data;
            }).catch(() => {
                this.$messageBox(this.$t('map.failedLoadListPublishedMaps'));
            });
        },
        create() {
            if (this.activeTab === 'first') {
                this.$refs['newForm'].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        newMap(this.newModel).then(response => {
                            this.loading = false;
                            this.$emit('refresh');
                            this.$message.success(this.$t('map.creatingSuccessful'));
                            this.close();
                        }).catch(() => {
                            this.loading = false;
                            this.$messageBox(this.$t('map.createFailure'));
                            this.close();
                        });
                    }
                });
            } else {
                this.$refs['pullForm'].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        newUsePublishMap(this.pullModel).then(response => {
                            this.loading = false;
                            this.$emit('refresh');
                            this.$message.success(this.$t('map.creatingSuccessful'));
                            this.close();
                        }).catch(() => {
                            this.loading = false;
                            this.$messageBox(this.$t('map.createFailure'));
                            this.close();
                        });
                    }
                });
            }
        },
        importf() { // 导入
            const obj = this.$refs.files;
            let wb;
            if (!obj.files) return;
            const f = obj.files[0];
            this.loadingUpload = true;
            const reader = new FileReader();
            const that = this;
            reader.onload = function (e) {
                const data = e.target.result;
                if (that.rABS) {
                    wb = XLSX.read(btoa(that.fixdata(data)), {// 手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary'
                    });
                }
                const resultJSONData = {};
                for (const index in wb.Sheets) {

                    const titleNum = that.formatSheetTitle(index);
                    const key = translateSheetTitle.sheetName[titleNum];

                    const filterVal = that.handelData(key);
                    const jsonData = sheet_to_json(wb.Sheets[index]);
                    const data = that.formatJson(filterVal, jsonData, key);
                    if (key === 'base') {
                        for (const i in data[0]) {
                            resultJSONData[i] = data[0][i];
                        }
                    } else {
                        resultJSONData[key] = data;
                    }
                }
                that.resultJSON = resultJSONData;
                if (that.resultJSON) {
                    postBuildMapImport(that.resultJSON).then(res => {
                        that.loadingUpload = false;
                        that.$message.success(this.$t('map.importSuccessful'));
                        that.$emit('refresh');
                        that.close();
                    }).catch(error => {
                        that.loadingUpload = false;
                        that.$message.error(this.$t('map.importFailure') + error.message);
                    });
                }
                obj.value = ''; // 清空上次导入文件
            };
            if (that.rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        },
        // 转换数据格式
        handelData(key) {
            const tHeader = [];
            const tHeaderF = [];
            if (translate[key]) {
                translate[key].columns.forEach(item => {
                    tHeader.push(item.tHeader);
                    tHeaderF.push(item.key);
                });
            }
            const filterVal = {
                tHeader: tHeader,
                tHeaderF: tHeaderF
            };
            return filterVal;
        },
        // 文件流转BinaryString
        fixdata(data) {
            var o = '';
            var l = 0;
            var w = 10240;
            for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
            return o;
        },
        // 转换属性名称 格式
        formatJson(filterVal, jsonData, key) {
            jsonData.map((item, index) => {
                const json = {};
                filterVal.tHeader.map((j, o) => {
                    if (item[j] != undefined) {
                        json[filterVal.tHeaderF[o]] = translate[key].columns[o].formatter(item[j]);
                    }
                });
                jsonData.splice(index, 1, json);
            });
            return jsonData;
        },
        // 转换sheet名字
        formatSheetTitle(title) {
            let index;
            translateSheetTitle.sheetTitle.forEach((v, i) => {
                if (title == v) index = i;
            });
            return index;
        }
    }
};
</script>
<style scoped rel="stylesheet/scss" lang="scss">
    .uploadDemo {
        .el-upload-dragger {
            margin: 0 auto;
        }

        .file_box {
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
    }
</style>
<style>
    .el-loading-mask {
        background-color: rgba(0, 0, 0, 0.3);
    }
</style>
