<template>
  <el-dialog v-dialogDrag :title="$t('map.mapEditor')" :visible.sync="dialogShow" :close-on-click-modal="false" width="30%" :before-close="handleClose">
    <div>
      <template v-if="basicInfo">
        <el-form ref="edit" label-position="right" :model="editModel" :rules="editRules" label-width="120px" size="mini" @submit.native.prevent>
          <el-form-item :label="$t('map.skinName')" prop="skinCode">
            <el-select v-model="editModel.skinCode" :placeholder="$t('map.pleaseSelect')" size="mini" disabled>
              <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="editModel.name" />
          </el-form-item>
        </el-form>
      </template>
      <template v-else>
        <el-form ref="updt" label-position="right" :model="updtModel" :rules="updtRules" label-width="120px" size="mini" @submit.native.prevent>
          <el-form-item :label="$t('map.offsetXColon')" :prop="'origin.x'">
            <el-input v-model="updtModel.origin.x" :label="$t('map.offsetX')" disabled />
          </el-form-item>
          <el-form-item :label="$t('map.offsetYColon')" :prop="'origin.y'">
            <el-input v-model="updtModel.origin.y" :label="$t('map.offsetY')" disabled />
          </el-form-item>
          <el-form-item :label="$t('map.scalingColon')" prop="scaling">
            <el-input-number v-model="updtModel.scaling" :precision="1" :step="0.2" disabled />
          </el-form-item>
        </el-form>
      </template>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogShow = false">{{ $t('map.cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="save">{{ $t('map.confirm') }}</el-button>
    </span>
  </el-dialog>

</template>

<script>
import { updateMap, getMapDetail } from '@/api/jmap/mapdraft';
import { getLineCodeList } from '@/api/management/mapline';
import { saveMap } from '@/api/jmap/mapdraft';

export default {
    name: 'MapEdit',
    props: {
        map: {
            type: Object,
            required: true
        },
        basicInfo: {
            type: Boolean,
            required: true,
            default: function () {
                return true;
            }
        },
        skinCode: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            skinCodeList: [],
            cityList: [],
            editModel: {
                id: '',
                name: '',
                skinCode: '01',
                cityCode: ''
            },
            updtModel: {
                code: '',
                scaling: '',
                origin: {
                    x: '',
                    y: ''
                }
            },
            isUpdate: false
        };
    },
    computed: {
        editRules() {
            return {
                name: [
                    { required: true, message: this.$t('rules.pleaseEnterMapName'), trigger: 'blur' }
                ],
                skinCode: [
                    { required: true, message: this.$t('rules.pleaseSelectAssociatedSkin'), trigger: 'change' }
                ]
            };
        },
        updtRules() {
            return {
                'origin.x': [
                    { required: true, message: this.$t('rules.enterXOffset'), trigger: 'blur' }
                ],
                'origin.y': [
                    { required: true, message: this.$t('rules.enterYOffset'), trigger: 'blur' }
                ],
                scaling: [
                    { required: true, message: this.$t('rules.enterScale'), trigger: 'blur' }
                ]
            };
        }
    },
    watch: {
        map: function (val, old) {
            if (val) {
                Object.assign(this.editModel, this.map);
            }
        },
        '$store.state.map.mapDataLoadedCount': function () {
            if (this.$jlmap.skinCode) {
                this.isUpdate = true;
            }
        }
    },
    mounted() {
        this.initLoadData();
    },
    methods: {
        show(type) {
            const dataZoom = this.$store.state.map.dataZoom;
            if (type == 'editCode') {
                this.editModel.skinCode = this.editModel.skinCode ? this.editModel.skinCode : '';
                this.editModel.name = this.editModel.name ? this.editModel.name : '';
            } else if (type == 'editPoint') {
                if (dataZoom && dataZoom.offsetX) {
                    this.updtModel.origin.x = Number.parseInt(dataZoom.offsetX);
                    this.updtModel.origin.y = Number.parseInt(dataZoom.offsetY);
                    this.updtModel.scaling = dataZoom.scaleRate;
                }
            }

            this.dialogShow = true;
        },
        close() {
            if (this.basicInfo) {
                this.$refs.edit.resetFields();
            } else {
                this.$refs.updt.resetFields();
            }

            this.dialogShow = false;
        },
        handleClose() {
            this.close();
        },
        save() {
            this.loading = true;
            if (this.basicInfo) {
                // this.editModel.id = this.$route.params.mapId;
                this.$refs['edit'].validate((valid) => {
                    if (valid) {
                        updateMap(this.editModel).then(response => {
                            this.loading = false;
                            if (this.isUpdate && this.$route.params.mapId) {
                                getMapDetail(this.$route.params.mapId).then(response => {
                                    this.$store.dispatch('map/setMapData', response.data);
                                });
                            }
                            this.$message.success(this.$t('map.mapUpdateSuccessful'));
                            this.$emit('refresh');
                            this.close();
                        }).catch(error => {
                            this.loading = false;
                            this.$message.error(this.$t('map.operationUnusual') + error.message);
                        });
                    } else {
                        this.loading = false;
                    }
                });
            } else {
                this.updtModel.code = this.skinCode;
                const map = this.$store.state.map.map;
                this.$refs['updt'].validate((valid) => {
                    if (valid) {
                        this.$store.dispatch('map/saveMapDeviceDefaultRelations').then(() => {
                            const param = {
                                mapId: this.$route.params.mapId,
                                skinVO: {
                                    code: this.$store.state.map.map.skinVO.code,
                                    name: this.$store.state.map.map.skinVO.name,
                                    origin: {
                                        x: this.updtModel.origin.x,
                                        y: this.updtModel.origin.y
                                    },
                                    scaling: this.updtModel.scaling
                                }
                            };
                            saveMap(Object.assign(map, param)).then(response => {
                                this.loading = false;
                                this.close();
                                this.$message.success(this.$t('map.updateSuccessfully'));
                            }).catch(() => {
                                this.loading = false;
                                this.$messageBox(this.$t('map.updateFailed'));
                            });
                        });
                    } else {
                        this.loading = false;
                    }
                });
            }
        },
        initLoadData() {
            this.cityList = [];
            this.$Dictionary.cityType().then(list => {
                this.cityList = list;
            }).catch(() => {
                this.$messageBox(this.$t('map.failedLoadCityList'));
            });

            this.skinCodeList = [];
            getLineCodeList().then(response => {
                this.skinCodeList = response.data;
            });
        }
    }
};
</script>
