<template lang="pug">
  el-container(style="padding:0px;height:77.6vh;")
    el-header( style="height:42px;line-height:42px;background: #f4f4f4;z-index:1001;border: 1px solid rgba(195, 195, 195, 1);" )
      span.title-bold.title-left-color 站点维护
    el-main.box_main
      el-card()
        el-form(:model='dataForm', :rules='dataRule', ref='dataForm',  label-width='100px')
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="站点名称:" prop="stationName")
                        el-input(disabled v-model='dataForm.stationName' placeholder=""  clearable )
                el-col(:span='12')
                    el-form-item(label="车站编码:" prop="code")
                        el-input(v-model='dataForm.code' placeholder=""  clearable  disabled)
            el-row(:gutter='20')
                el-col(:span='12')
                    el-form-item(label="站点简称:" prop="shortName")
                        el-input(v-model='dataForm.shortName' placeholder=""  clearable  disabled)
                el-col(:span='12')
                    el-form-item(label="站点排序:" prop="orderNum")
                        el-input(v-model.number='dataForm.orderNum' clearable disabled)
                el-col(:span='24')
                    el-form-item(label="站点描述:" prop="remark")
                        el-input(v-model='dataForm.remark' type="textarea" :rows=4 resize="none" placeholder="" disabled)
        el-row(style="padding-bottom:15px;" :span="24")
            el-col(:md='23' :sm="5")
                div.title-bold(style='line-height: 40px;') 站点地图
        //- el-divider(style='margin-top:0')
        <div class="fileDiv">
          <div class="fileList" v-for="(item,index) in fileList">
            <el-input size="mini" v-model='item.name' clearable></el-input>
            <img :src="item.readPath" :onerror="logo" @click="changeImage(item)">
            <div class="imgButton">
              <el-button type="text" size="mini" :disabled="index == 0" icon="el-icon-back" @click='leftClick(index,item)'></el-button>
              <el-button type="text" size="mini" icon="el-icon-delete" @click='removeClick(item,index)'></el-button>
              <el-button type="text" size="mini" :disabled="index == fileList.length-1" icon="el-icon-right" @click='rightClick(index,item)'></el-button>
            </div>
          </div>
          <div class="shangchuan" @click="fileClick" v-if="fileList.length < 5">
            <span class="el-icon-plus"></span>
          </div>
          <div>
            el-alert(title="上传图片格式仅支持jpg,jpeg,png,单个照片大小不超过10M" effect='light' :closable="false" style="margin-top:10px;")
          </div>
          <input @change="fileChange($event)" type="file" id="upload_file" style="display: none"/>
        </div>
        el-button(type='primary' size='medium' @click='dataFormSubmit()' v-if="isAuth('line:station:save')" v-prevent-re-click style="margin-top:10px;margin-left:900px;") 保存
</template>

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

export default {
  computed: {
    ...mapState('d2admin/user', ['info'])
  },
  data() {
    let validateNumber = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('只能输入正整数'))
      } else if (value > 10000) {
        callback(new Error('排序值超出范围'))
      } else {
        callback()
      }
    }
    return {
      clickFlag: false,
      dataList: [],
      dataListLoading: false,
      currentRow: {},
      urlPath: window.CONFIG.urlPath,
      cImage: '',
      fileList: [],
      stationId: localStorage.getItem('stationId'),
      imageUrl: '',
      logo: 'this.src="' + require('../../../assets/images/videoImg.png') + '"',
      typeList: [
        { id: '1', name: '正线站点' },
        { id: '2', name: '换乘站点' }
      ],
      masterList: [
        { id: 1, name: '主站' },
        { id: 2, name: '从站' }
      ],
      dataForm: {},
      dataRule: {
        // stationName: [
        //     { required: true, message: '站点名称不能为空', trigger: 'blur' },
        //     { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        // ],
        orderNum: [
          { required: true, message: '排序值不能为空' },
          { type: 'number', message: '排序值必须为数字' },
          { validator: validateNumber, trigger: ['blur', 'change'] }
        ],
        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: 'blur' }
        ],
        remark: [
          {
            min: 1,
            max: 300,
            message: '长度在 1 到 300 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.initDataFrom(this.stationId)
    this.cImage = ''
  },
  methods: {
    initDataFrom(id) {
      this.$http({
        url: this.$http.adornUrl(`/liStation/getId/${id}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataForm = data.bean
          this.fileList = data.bean.mapList
          this.fileList.forEach((element) => {
            element.readPath = this.urlPath + element.filePath
          })
        }
      })
    },
    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 && e.name.length > 10) {
              this.$message.warning('地图名称长度在1到10个字符之间')
              errorflag = true
              return false
            }
            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.$http({
            url: this.$http.adornUrl(
              `/liStation/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            // headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            data: this.dataForm
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
            } else {
              this.$message.error(data.msg)
            }
            this.clickFlag = false
          })
        }
      })
    },
    changeImage(item) {
      this.cImage = item.id
      // console.log('id:' + item.id)
      if (this.cImage) {
        document.getElementById('upload_file').click()
      }
    },
    fileClick() {
      this.cImage = ''
      if (
        this.cImage === '' ||
        this.cImage === null ||
        this.cImage === undefined
      ) {
        document.getElementById('upload_file').click()
      }
    },
    fileChange(el) {
      // console.log('上传图片后的cImage', this.cImage)
      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('id', this.cImage)
        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
            // console.log('上传图片后的currentRow', this.currentRow)
            var num = 0
            var flag = false
            var updateRes = {}
            this.fileList.forEach((res, index) => {
              if (res.id === this.currentRow.id) {
                num = index
                updateRes = res
                flag = true
                return false
              }
            })
            // console.log('上传图片后的updateRes', updateRes)
            if (flag) {
              updateRes.fileName = this.currentRow.fileName
              updateRes.filePath = this.currentRow.filePath
              updateRes.readPath = this.currentRow.readPath
              updateRes.updateTime = this.currentRow.updateTime
              updateRes.updateUserId = this.currentRow.updateUserId
              Vue.set(this.fileList, num, updateRes)
            } else {
              this.fileList.push(this.currentRow)
            }
            // console.log('上传图片后的fileList', this.fileList)
            this.$message.success('上传成功!')
          } else {
            this.$message.error('上传失败!')
          }
        })
      }
      this.cImage = ''
      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
    }
  }
}
</script>
<style lang="scss" scoped>
.fileDiv {
  height: 200px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f6f7fb;
  display: table-cell;
  vertical-align: middle;
  width: 1%;

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

    /deep/ .el-input--mini .el-input__inner {
      text-align: center !important;
    }

    .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;
  }

  /deep/ .el-alert--info.is-light {
    background-color: #f6f7fb;
  }
}
</style>