<template>
  <div class="h-100">
    <map-box ref="mapbox">
      <template #content>
        <el-row class="w-40 m-t-20 m-l-20" style="position: absolute;">
          <el-col :span="24">
            <el-container>
              <el-header height="42px" class="l-h-42 p-l-10 p-r-10 border border-b-n">
                <div class="l">
                  <i v-if="pageState === 'add'" class="el-icon-plus f-s-20"></i>
                  <i v-else class="el-icon-edit f-s-20"></i>
                  <font class="m-l-10 f-s-18 fb">{{ $route.meta.title }}</font>
                </div>
              </el-header>
              <el-main class="border p-20 mainBox bg-white">
                <el-form ref="form" :model="form" label-width="120px">
                  <el-form-item v-if="pageState === 'add'" label="所属商铺">
                    <SelectionShopId v-model="form.shop_id" />
                  </el-form-item>
                  <el-form-item label="航线标题">
                    <el-input v-model="form.name" placeholder="航线标题" />
                  </el-form-item>
                  <el-form-item label="航线文件上传">
                    <el-upload class="upload-demo" drag name="file" :action="action" :headers="myheader"
                      :on-success="handleUpSuccess" :on-exceed="handleExceed" :on-error="handleUpErr"
                      :on-remove="handleRemove" :limit="1" :file-list="fileList" :before-upload="beforeAvatarUpload">
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text"><em>点击上传</em></div>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="航线描述">
                    <el-input v-model="form.desc" type="textarea" placeholder="非必填" />
                  </el-form-item>
                  <el-form-item v-if="pageState == 'add' ? true : false">
                    <el-button type="primary" icon="el-icon-plus" @click="addRoute">创建</el-button>
                  </el-form-item>
                  <el-form-item v-else>
                    <el-button type="primary" icon="el-icon-edit" @click="saveRoute">更新</el-button>
                  </el-form-item>
                </el-form>
              </el-main>
            </el-container>
          </el-col>
        </el-row>
      </template>
    </map-box>
  </div>
</template>

<script>
import MapBox from '@/components/MapBox'
import SelectionShopId from '@/components/SelectionShopId'

export default {
  name: 'RouteAdd',
  data () {
    return {
      action: this.$store.state.settings.baseURL + this.$store.state.settings.apiPlanePath + 'upTxtFile',
      myheader: { token: this.$store.state.user.token },
      form: {
        shop_id: '',
        name: '',
        desc: '',
        upFile: '',
        route_data: ''
      },
      routeId: this.$route.params.id,
      fileList: [],
      pageState: 'add', // 页面状态
      route: null
    }
  },
  components: {
    MapBox,
    SelectionShopId
  },
  computed: {
    /**
     * @description: 获取航线列表
     */
    routeList () {
      return this.$store.state.routeList
    },
    /**
     * @description: 侧边栏显隐
     */
    isCollapse () {
      return this.$store.state.app.isCollapse
    }
  },
  methods: {
    /* 文件上传表单 */
    handleExceed () {
      this.$message.warning('需先删除之前上传文件')
    },
    handleRemove () {
      this.form.upFile = ''
    },
    handleUpSuccess (res) {
      this.$refs.mapbox.makeRoute(res.content)// 绘出航线
      if (res.status === 0) {
        this.fileList = []
        this.$message.error(res.msg)
      } else {
        this.form.upFile = res.data
        this.$message.success(res.msg)
      }
    },
    handleUpErr () {
      this.$message.error('接口访问失败')
    },
    beforeAvatarUpload (file) {
      const isTxt = file.type === 'text/plain' || file.type === 'application/json'
      if (!isTxt) {
        this.$message.error('航点文件仅支持txt或json格式!')
      }
      return isTxt
    },
    /* ED 文件上传表单 */
    // 设置表单
    setForm (data) {
      if (data.desc == null) {
        data.desc = ''
      }
      this.form.shop_id = data.shop_id
      this.form.name = data.name
      this.form.upFile = data.upFile
      this.form.desc = data.desc
      this.form.route_data = data.route_data
      if (Object.keys(data).length === 0) {
        this.$message.warning('清空表单')
      }
    },
    // 初始化页面 添加or编辑
    initPage () {
      if (this.routeId === undefined) {
        this.pageState = 'add'
      } else {
        this.pageState = 'edit'
        this.route = this.routeList.find((item) => item.id === this.routeId)
        if (this.route) {
          const data = {
            shop_id: this.route.shop_id,
            name: this.route.name,
            route_data: this.route.route_data,
            upFile: ''
          }
          this.setForm(data)
          setTimeout(() => {
            this.$refs.mapbox.makeRoute(JSON.parse(this.route.route_data))// 更新页面 绘出航线 初始化
          }, 0)
        }
      }
    },
    /**
     * @description: 创建新站点
     */
    async addRoute () {
      const res = await this.$store.dispatch('fetchAddRoute', this.form)
      if (res.data.status === 1) {
        this.$router.push('/route/index')
      }
    },
    /**
     * @description: 更新站点
     */
    async saveRoute () {
      this.form.id = this.routeId
      const res = await this.$store.dispatch('fetchSaveRoute', this.form)
      if (res.data.status === 1) {
        this.$router.push('/route/index')
      }
    }
  },
  watch: {
    routeList () {
      this.initPage()// 初始化页面
    },
    /**
     * @description: 侧边栏缩进有变化时 地图重新自适应
     */
    isCollapse: {
      handler (val) {
        if (val) {
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.mapbox.handleResize()
            })
          }, 500)
        }
      },
      deep: true
    }
  },
  created () {
    if (this.routeList.length > 0) {
      this.initPage()// 初始化页面
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}

.el-header,
.el-main {
  z-index: 1001;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
