<template lang="pug">
    el-dialog.myDialog( width='60%'  :close-on-click-modal='false', :visible.sync='visible' append-to-body :modal-append-to-body='false')
        div(slot='title')
            span.title-bold {{!dataForm.id ? '新增站点' : '编辑站点'}}
        el-form(:model='dataForm', :rules='dataRule', ref='dataForm',  label-width='100px')
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="所属线路:" prop="lineName")
                        el-input(v-model='dataForm.lineName' disabled)
                el-col(:span='12')
                    el-form-item(label="站点名称:" prop="stationName")
                        el-input(v-model='dataForm.stationName' placeholder="请输入站点名称"  clearable )
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="车站排序:" prop="orderNum")
                        el-input-number.el-input(v-model='dataForm.orderNum' placeholder="请输入车站排序" controls-position="right" :min="1" :max="100" clearable )
                el-col(:span='12')
                    el-form-item(label="车站编码:" prop="code")
                        el-input(v-model='dataForm.code' placeholder="请输入车站编码"  clearable )
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="车站类型:" prop="type")
                        el-select(style='width:100%;' v-model='dataForm.type' placeholder="请选择车站类型" clearable)
                            el-option(v-for="(item,index) in typeList" :key="index" :label="item.name" :value="item.id")
                el-col(:span='12')
                    el-form-item(label="站点简称:" prop="shortName")
                        el-input(v-model='dataForm.shortName' placeholder="请输入站点简称"  clearable )
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="经度:" prop="x")
                        el-input(v-model='dataForm.x' placeholder="请输入经度"  clearable )
                el-col(:span='12')
                    el-form-item(label="纬度:" prop="y")
                        el-input(v-model='dataForm.y' placeholder="请输入纬度"  clearable )
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="主站/从站:" prop="isMaster")
                        el-select(style='width:100%;' v-model='dataForm.isMaster' placeholder="请选择主站/从站" clearable)
                            el-option(v-for="(item,index) in masterList" :key="index" :label="item.name" :value="item.id")
            el-row(:gutter='20')
                el-col(:span='24')
                    el-form-item(label="站点描述:" prop="remark")
                        el-input(v-model='dataForm.remark' type="textarea" :rows=4 resize="none" placeholder="请输入站点描述")
        span.dialog-footer(slot='footer')
            el-button(type='primary' size='medium' @click='cancel') 取消
            el-button(type='primary' size='medium' @click='dataFormSubmit()' v-prevent-re-click) 保存

</template>

<script>
import { mapState } from 'vuex'
import Vue from 'vue'

export default {
  computed: {
    ...mapState('d2admin/user', [
      'info'
    ])
  },
  data () {
    return {
      clickFlag: false,
      visible: false,
      dataList: [],
      urlPath: window.CONFIG.urlPath,
      dataListLoading: false,
      currentRow: {},
      fileList: [],
      imageUrl: '',
      logo: 'this.src="' + require('../../../../assets/images/videoImg.png') + '"',
      typeList: [
        { id: '1', name: '正线站点' },
        { id: '2', name: '换乘站点' }
      ],
      masterList: [
        { id: 1, name: '主站' },
        { id: 2, name: '从站' }
      ],
      lineId: '',
      lineName: '',
      lineCode: '',
      lineColor: '',
      dataForm: {
        isMaster: 1,
        id: '',
        lineId: '',
        lineName: '',
        lineCode: '',
        lineColor: '',
        stationName: '',
        orderNum: '',
        code: '',
        type: '',
        shortName: '',
        x: '',
        y: '',
        remark: ''
      },
      dataRule: {
        stationName: [
            { required: true, message: '站点名称不能为空', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        shortName: [
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '车站编码不能为空', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: '车站类型不能为空', trigger: 'change' }],
        isMaster: [{ required: true, message: '主站/从站不能为空', trigger: 'change' }],
        x: [{ pattern: /^-?((0|1?[0-7]?[0-9]?)(([.][0-9]{1,6})?)|180(([.][0]{1,6})?))$/, message: '请输入正确的经度,最多6位小数', trigger: 'blur' }],
        y: [{ pattern: /^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,6})?)|90(([.][0]{1,6})?))$/, message: '请输入正确的纬度,最多6位小数', trigger: 'blur' }],
        remark: [
          {
            min: 1,
            max: 300,
            message: '长度在 1 到 300 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    init (id, lineId, lineName, lineCode, lineColor) {
      this.visible = true
      this.clickFlag = false
      this.dataForm.id = id
      this.dataForm.lineId = lineId
      this.dataForm.lineName = lineName
      this.dataForm.lineCode = lineCode
      this.dataForm.lineColor = lineColor
      this.lineId = lineId
      this.initData()
      if (this.dataForm.id) {
        this.initDataFrom()
      } else {
        this.getOrderNum()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        // this.$refs['dataForm'].clearValidate()
      })
    },
    initDataFrom () {
      this.$http({
        url: this.$http.adornUrl(`/liStation/getId/${this.dataForm.id}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(data => {
        if (data && data.code === 0) {
          this.dataForm = data.bean
          // this.fileList = data.bean.mapList
        }
      })
    },
    //获取当前线路车站排序值
    getOrderNum () {
      this.$http({
        url: this.$http.adornUrl(`/liStation/getOrderNum`),
        method: 'get',
        params: this.$http.adornParams({
          lineId: this.lineId
        })
      }).then(data => {
        if (data && data.code === 0) {
          this.dataForm.orderNum = data.orderNum ? data.orderNum + 1 : 1
        }
      })
    },
    initData () {
      this.typeList = [
        { id: '1', name: '正线站点' },
        { id: '2', name: '换乘站点' }
      ]
      this.masterList = [
        { id: 1, name: '主站' },
        { id: 2, name: '从站' }
      ]
    },
    // 表单提交
    dataFormSubmit (id) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // let errorflag = false
          // this.fileList.forEach(e => {
          //   if (!e.name) {
          //     this.$message.error('请填写地图名称!')
          //     errorflag = true
          //     return false
          //   }
          // })
          // if (errorflag) {
          //   return
          // }

          this.clickFlag = true

          // for (var i in this.fileList) {
          //   this.fileList[i].orderNum = Number(i) + 1
          // }
          // this.dataForm.mapList = this.fileList
          this.dataForm.stationId = localStorage.getItem('stationId')
          this.$http({
            url: this.$http.adornUrl(
              `/liStation/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.dataForm
          }).then(data => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshdatalist')
                }
              })
            } else {
              this.clickFlag = false
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    fileClick () {
      document.getElementById('upload_file').click()
    },
    fileChange (el) {
      this.$showLoading()
      if (!el.target.files[0].size) return
      let file = el.target.files[0]

      if (this.beforeAvatarUpload(file)) {
        let fd = new FormData()
        fd.append('type', 'stationMap')
        // fd.append('stationId', this.dataForm.id)
        fd.append('file', file)
        this.$http({
          url: this.$http.adornUrl(`/liStationMap/uploadFile`),
          method: 'post',
          data: fd
        }).then(data => {
          if (data && data.code === 0) {
            this.currentRow = data.bean
            this.currentRow.readPath = this.urlPath + this.currentRow.filePath
            this.fileList.push(this.currentRow)
            console.log('上传图片后的fileList', this.fileList)
            this.$message.success('上传成功!')
          } else {
            this.$message.error('上传失败!')
          }
        })
      }
      el.target.value = ''
    },
    removeClick (item, index) {
      var ids = [item.id]
      this.$confirm(`确认删除地图?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: true
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/liStationMap/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then((data) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.fileList.splice(index, 1)
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
      })
    },
    leftClick (index, row) {
      let front = JSON.parse(JSON.stringify(this.fileList[index - 1]))

      Vue.set(this.fileList, index - 1, row)
      Vue.set(this.fileList, index, front)
      // console.log(this.fileList)
    },
    rightClick (index, row) {
      let after = JSON.parse(JSON.stringify(this.fileList[index + 1]))

      Vue.set(this.fileList, index + 1, row)
      Vue.set(this.fileList, index, after)
      // console.log(this.fileList)
    },
    //文件上传前的验证
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传图片只能是 jpg,jpeg,png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过10MB!')
      }
      return isJPG && isLt2M
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', !this.dataForm.id ? '新增站点' : '编辑站点', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.visible = false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    }
  }
}
</script>
<style lang='scss' scoped>
.fileDiv {
  height: 200px;
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 5px;

  .fileList {
    height: 130px;
    width: 100px;
    margin: 10px 0 0 10px;
    float: left;
    border-radius: 5px;
    overflow: hidden;

    .el-button {
      padding-left: 8px;
      font-size: 14px;
    }

    img {
      height: 100px;
      width: 100px;
    }

    .imgButton {
      position: relative;
      top: -30px;
      background: #ccc;
    }
  }

  .shangchuan {
    line-height: 100px;
    text-align: center;
    font-size: 30px;
    height: 100px;
    width: 100px;
    float: left;
    border: 1px solid #ccc;
    margin-top: 40px;
    margin-left: 10px;
    border-radius: 5px;
  }
}

.el-table__header {
  width: 100% !important;
}

.el-table__body {
  width: 100% !important;
}

.el-divider {
  margin-top: 0px;
}
.myDialog{
  /deep/.el-dialog{
    margin-top:4vh !important;
  }
}
</style>