<template>
  <div>
    <div class="config-item">
      <div class="config-item-main">
        <span class="data-title">地图DataV</span>
        <el-form ref="areaForm" class="areaForm" :model="areaForm" size="small" label-width="100px">
          <el-form-item class="geoInput" label="GeoJSON" prop="map_data">
            <el-tooltip v-if="!editStatus.areaForm.map_data" class="item" effect="dark" content="双击输入框进行编辑" placement="top">
              <span
                class="edit-readonly"
                style="padding: 4px 15px;"
                @dblclick="handleDblClick('areaForm', 'map_data')"
              >
                {{ areaForm.map_data || '' }}
              </span>
            </el-tooltip>
            <el-input
              v-else
              ref="areaFormmap_data"
              v-model="areaForm.map_data"
              type="textarea"
              rows="5"
              @blur="handleBlur('areaForm', 'map_data')"
              @keyup.enter="handleBlur('areaForm', 'map_data')"
            />
          </el-form-item>
          <div class="config-remarks" style="margin-left: 100px; margin-bottom: 20px;">双击输入框可进行编辑。数据将用于“区域屏”，显示区域地图。<i class="iconfont icon-zhuyi-lan" @click="geoJsonVisible=true" /></div>

          <el-form-item label="地图边距微调" class="padding-style-input" prop="map_spacing">
            <el-tooltip v-if="!editStatus.areaForm.map_spacing" class="item" effect="dark" content="双击输入框进行编辑" placement="top">
              <div style="display: flex; justify-content: flex-start; width: 340px; height: 32px; align-items: flex-start;">
                <span
                  class="edit-readonly"
                  @dblclick="handleDblClick('areaForm', 'map_spacing')"
                >
                  {{ areaForm.map_spacing || '' }}
                </span>

                <span class="edit-slot">像素</span>
              </div>
            </el-tooltip>
            <el-input
              v-else
              ref="areaFormmap_spacing"
              v-model="areaForm.map_spacing"
              @blur="handleBlur('areaForm', 'map_spacing')"
              @keyup.enter="handleBlur('areaForm', 'map_spacing')"
            ><template slot="append">像素</template></el-input>
          </el-form-item>
          <div class="config-remarks" style="margin-left: 100px;">双击输入框可进行编辑。由于地图形状各异，如果需要调整地图垂直位置（让显示更居中），可通过次参数微调，保存后在预览页面查看最终效果！</div>
        </el-form>
      </div>

    </div>
    <div class="config-item">
      <div class="config-item-main">
        <span class="data-title">总分馆管理</span>
        <div class="upload-item" style="align-items: flex-start;">
          <p>总分馆列表</p>
          <el-card class="box-card" style="padding: 20px;">
            <el-table
              ref="table"
              :data="tableData"
              style="width: 100%"
              max-height="360"
              @selection-change="selectionChangeHandler"
              @row-click="clickRowHandler"
            >
              <el-table-column type="selection" align="center" width="55" />
              <el-table-column prop="name" label="名称" width="150" />
              <el-table-column prop="libcode" label="馆代码" width="100">
                <template slot-scope="scope">
                  <span v-if="scope.row.branchType === 1|| scope.row.branchType === '1'">{{ scope.row.libcode }}</span>
                  <span v-else>{{ scope.row.tcId }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="mapX" label="坐标" width="200">
                <template slot-scope="scope">
                  {{ scope.row.mapX }},{{ scope.row.mapY }}
                </template>
              </el-table-column>
              <el-table-column prop="promotions" label="宣传图片" width="80">
                <template slot-scope="scope">
                  {{ scope.row.promotions.length }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                  <el-button style="padding: 5px 6px !important;" @click="initForm('edit',scope.row)"><i class="iconfont icon-bianji" />编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-if="tableData.length !== 0"
              style="margin: 34px 0 10px 0 !important;"
              :current-page="page.page"
              :total="page.total"
              :page-size="page.size"
              :pager-count="5"
              layout="total, prev, pager, next, sizes"
              @size-change="handleSizeChange"
              @current-change="handleCurrentPage"
            />
          </el-card>
          <div style="display: flex; flex-direction: column; justify-content: flex-start; margin-left: 15px;">
            <el-button size="mini" @click="initForm('add')">
              <i class="iconfont icon-xinzeng" />
              新增
            </el-button>
            <el-button :loading="deleteLoading" size="mini" style="margin-left: 0; margin-top: 14px;" :disabled="selections.length === 0" @click="toDelete(selections)">
              <i class="iconfont icon-shanchu" />
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <el-dialog class="geoJson-dialog" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :before-close="handleClose" :visible.sync="geoJsonVisible" title="地图GeoJSON获取方法">
      <div class="setting-dialog geo-remarks">
        <p>1.开发网址：
          <a
            :href="link"
            target="_blank"
            rel="noopener noreferrer"
            class="external-link"
          >
            {{ link }}
          </a>
          <!-- <i class="iconfont" :class="copied ? 'icon-fuzhichenggong1' : 'icon-fuzhi'" @click="copyLink" /> -->
        </p>
        <p style="padding: 15px 0;">2.在地图上找到并选择正确的区域（区域最小单位是：区/县）</p>
        <div style="display: flex; justify-content: space-between;">
          <p>3.在右侧工具栏中找到：<br>
            “其他类型（GeoJSON、SVG）”<br>
            点击下方的“GeoJSON”后面的按钮<br>
            复制代码，粘贴到此处即可。</p>
          <img src="@/assets/images/screen/geo.png" alt="">
        </div>
      </div>
    </el-dialog>

    <el-dialog class="auto-dialog" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :before-close="handleClose" :visible.sync="libDialogVisible" :title="formTitle">
      <div class="setting-dialog">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="90px">
          <div style="width: 696px;">
            <div>
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" style="width: 586px;" />
              </el-form-item>
            </div>
            <el-form-item label="类型" prop="branchType">
              <el-radio-group v-model="form.branchType" v-removeAriaHidden @change="changeBranchType">
                <el-radio label="1">总馆</el-radio>
                <el-radio label="2">分馆</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.branchType === '1'" label="馆代码" prop="libcode" style="margin-left: 30px; margin-right: 0 !important;">
              <el-input v-model="form.libcode" placeholder="请输入" />
            </el-form-item>
            <el-form-item v-else label="馆代码" prop="tcId" style="margin-left: 30px; margin-right: 0 !important;">
              <el-input v-model="form.tcId" placeholder="请输入" />
            </el-form-item>
            <div>
              <el-form-item label="面积" prop="occupationArea">
                <el-input v-model="form.occupationArea" placeholder="请输入" style="width: 586px;">
                  <template slot="append">平方米</template>
                </el-input>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入" style="width: 586px;" />
              </el-form-item>
            </div>
            <div class="location-item">
              <el-form-item label="坐标" prop="location">
                <el-input v-model="form.mapX" placeholder="请输入">
                  <template slot="prepend">X</template>
                </el-input>
                <el-input v-model="form.mapY" placeholder="请输入">
                  <template slot="prepend">Y</template>
                </el-input>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="简介" prop="explains">
                <el-input v-model="form.explains" type="textarea" rows="4" placeholder="请输入" style="width: 586px;" />
              </el-form-item>
            </div>
            <div>
              <el-form-item label="宣传图片" prop="remarks">
                <div style="display: flex; justify-content: flex-start; flex-wrap: wrap;">
                  <div class="libImg-list">
                    <div v-for="(item,index) in libImgList" :key="index" class="libImg-item">
                      <img :src="item.imgPath" alt="">
                      <i class="iconfont icon-shanchu" @click="handleDelete(index)" />
                    </div>
                  </div>
                  <UploadCover upload-type="other-digital" :limit-num="libImgList.length" @childCover="handleCover" />
                </div>
                <div style="font-size: 12px; color: #9098a4;">点击上传图片，最多可上传 3 张</div>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="handleClose">取消</el-button>
          <el-button :loading="btnLoading" type="primary" @click="handleComfired">确定</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { FetchEditScreenSetting, FetchInitScreenBranch, FetchEditScreenBranch, FetchDeleteScreenBranch } from '@/api/digitalScreen/index'
import UploadCover from '@/views/components/upload.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'AreaSetting',
  components: { UploadCover },
  props: {
    mapData: {
      type: String,
      default: null
    },
    mapSpacing: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      formTitle: '新增分馆',
      btnLoading: false,
      deleteLoading: false,
      areaForm: {
        map_data: null,
        map_spacing: null
      },
      editStatus: {
        areaForm: {
          map_data: false,
          map_spacing: false
        }
      },
      originalValues: {
        areaForm: {}
      },
      geoJsonVisible: false,
      link: 'https://datav.aliyun.com/portal/school/atlas/area_selector',
      copied: false,
      tableData: [],
      page: {
        page: 0,
        size: 10,
        total: 0
      },
      libDialogVisible: false,
      form: {
        name: '',
        branchType: '1',
        libcode: '',
        occupationArea: '',
        address: '',
        mapX: '',
        mapY: '',
        explains: '',
        tcId: ''
      },
      selections: [],
      rules: {
        name: [
          { required: true, message: '名称不可为空', trigger: 'blur' }
        ],
        branchType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        tcId: [
          { required: true, message: '馆代码不可为空', trigger: 'blur' }
        ],
        libcode: [
          { required: true, message: '馆代码不可为空', trigger: 'blur' }
        ]
      },
      libImgList: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'user'
    ])
  },
  watch: {
    mapData(newVal) {
      if (newVal !== this.areaForm.map_data) {
        this.areaForm.map_data = newVal
        this.originalValues.areaForm.map_data = newVal
      }
    },
    mapSpacing(newVal) {
      if (newVal !== this.areaForm.map_spacing) {
        this.areaForm.map_spacing = newVal
        this.originalValues.areaForm.map_spacing = newVal
      }
    }
  },
  created() {
    this.areaForm.map_data = this.mapData
    this.areaForm.map_spacing = this.mapSpacing
  },
  mounted() {
    this.$emit('ready')
  },
  methods: {
    initScreenBranch() {
      const params = {
        'libcode': this.user.fonds.fondsNo,
        'page': this.page.page,
        'size': this.page.size
      }
      FetchInitScreenBranch(params).then((res) => {
        console.log('initScreenBranch', res.content)
        if (res.content.length !== 0) {
          this.tableData = res.content
          this.page.total = res.totalElements
        } else {
          this.tableData = []
          this.page.total = 0
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleDblClick(formName, field) {
      this.originalValues[formName][field] = this[formName][field]
      this.editStatus[formName][field] = true
      this.$nextTick(() => {
        const input = this.$refs[`${formName}${field}`]
        if (input) input.focus()
      })
    },
    handleBlur(formName, field) {
      this.editStatus[formName][field] = false
      if (this[formName][field] !== this.originalValues[formName][field]) {
        this.submitMapData(formName, field)
      }
    },
    submitMapData(formName, field) {
      const value = this[formName][field]
      if (!value) {
        this.$message.warning(`${this.getFieldLabel(formName, field)}不能为空`)
        this[formName][field] = this.originalValues[formName][field]
        return
      }

      const param = {
        'code': field,
        'context': value,
        'libcode': this.user.fonds.fondsNo,
        'remarks': null
      }
      FetchEditScreenSetting(param)
        .then((res) => {
          if (res.code !== 500) {
            this.$message.success(`${this.getFieldLabel(formName, field)}更新成功`)
            this.$emit('update:mapData', value)
            this.$emit('triggerInit')
          } else {
            this.$message.error(`${this.getFieldLabel(formName, field)}更新失败`)
          }
        })
        .catch(() => {
          this.$message.error(`${this.getFieldLabel(formName, field)}更新失败`)
        })
    },
    getFieldLabel(formName, field) {
      const labels = {
        areaForm: {
          map_data: 'GeoJSON',
          map_spacing: '地图边距微调'
        }
      }
      return labels[formName][field] || field
    },
    handleCover(value) {
      if (value) {
        const imgUrl = this.baseApi + '/api/fileRelevant/getImg?imgType=1&imgId=' + value
        this.libImgList.push({ imgPath: imgUrl })
      } else {
        this.libImgList = []
      }
    },

    initForm(type, branchData) {
      if (type === 'add') {
        this.formTitle = '新增分馆'
        if (this.form.branchType === '1') {
          this.form.name = this.user.fonds.fondsName
          this.form.libcode = this.user.fonds.fondsNo
        } else {
          this.form.name = ''
          this.form.libcode = ''
        }
      } else {
        this.formTitle = '编辑分馆'
        this.form = branchData
        this.form.branchType = branchData.branchType === 1 || branchData.branchType === '1' ? '1' : '2'
        this.libImgList = branchData.promotions
        this.form.explains = branchData.explains.replace(/<br\/?>/g, '\n')
      }
      this.libDialogVisible = true
    },
    changeBranchType(val) {
      if (val === '1') {
        this.form.name = this.user.fonds.fondsName
        this.form.libcode = this.user.fonds.fondsNo
      } else {
        this.form.name = ''
        this.form.libcode = ''
      }
    },
    selectionChangeHandler(val) {
      this.selections = val
    },
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
    },
    toDelete(selections) {
      this.deleteLoading = true

      this.$confirm(`确定要删除所选的数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        selections.forEach(book => {
          ids.push(book.id)
        })
        console.log('ids', ids)
        FetchDeleteScreenBranch(ids).then((res) => {
          console.log('res', res)
          if (res.code !== 500) {
            this.$message({ message: '删除成功', type: 'success', offset: 8 })
            this.initScreenBranch()
          } else {
            this.$message({ message: '删除失败', type: 'error', offset: 8 })
          }
          this.deleteLoading = false
        }).catch(err => {
          console.log(err)
          this.deleteLoading = false
        })
      }).catch(() => {
        this.deleteLoading = false
      })
    },
    handleDelete(index) {
      this.libImgList.splice(index, 1)
    },

    handleComfired() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          if (this.libImgList.length !== 0) {
            this.form.promotions = this.libImgList
          }
          if (this.form.branchType === '2') {
            this.form.libcode = this.user.fonds.fondsNo
          }
          this.form.explains = this.form.explains.replace(/\n/g, '<br>')
          console.log('FetchEditScreenBranch', this.form)
          FetchEditScreenBranch(this.form).then((res) => {
            console.log('res', res)
            if (res.code !== 500) {
              this.$message({ message: '新增成功', type: 'success', offset: 8 })
              this.initScreenBranch()
            } else {
              this.$message({ message: res.message, type: 'error', offset: 8 })
            }
            this.handleClose()
          }).catch(err => {
            console.log(err)
            this.handleClose()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose() {
      this.geoJsonVisible = false
      this.libDialogVisible = false
      this.$refs['form'].resetFields()
      this.$refs['form'].clearValidate()
      this.form = {
        name: '', branchType: '1', libcode: '', tcId: '', occupationArea: '', address: '', mapX: '', mapY: '', explains: ''
      }
      this.libImgList = []
      this.btnLoading = false
    },
    handleSizeChange(size) {
      this.page.size = size
      this.page.page = 0
      this.initScreenBranch()
    },
    handleCurrentPage(val) {
      this.page.page = val
      this.initScreenBranch()
    },
    copyLink() {
      navigator.clipboard.writeText(this.link)
        .then(() => {
          this.copied = true
          // 2秒后恢复复制图标
          setTimeout(() => {
            this.copied = false
          }, 2000)
        })
        .catch(err => {
          console.error('无法复制内容: ', err)
          this.fallbackCopyText()
        })
    },
    fallbackCopyText() {
      const textArea = document.createElement('textarea')
      textArea.value = this.link
      textArea.style.position = 'fixed'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      try {
        const successful = document.execCommand('copy')
        this.copied = successful
        if (successful) {
          setTimeout(() => {
            this.copied = false
          }, 2000)
        }
      } catch (err) {
        console.error('复制失败: ', err)
      }

      document.body.removeChild(textArea)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/digitalScreen.scss";
.geoInput{
  .edit-readonly{
    width: 800px !important;
    height: 110px !important;
    line-height: 20px !important;
    overflow: hidden;
    overflow-y: scroll;
  }
}

.areaForm{
  ::v-deep .geoInput{
    .el-form-item__content {
      width: 800px !important;
      height: 110px !important;
    }
  }
}

.icon-zhuyi-lan{
  font-size: 20px;
  color: #0348f3;
  cursor: pointer;
}
.geoJson-dialog{
  ::v-deep .el-dialog{
    width: 850px;
    .el-dialog__body{
      padding: 10px 0 20px 0;
    }
  }

}
.geo-remarks{
  font-size: 14px;
  line-height: 30px;
  .external-link {
    color: #0348f3; /* Vue的默认主题色 */
    text-decoration: none;
  }
  .external-link:hover {
    text-decoration: underline;
  }
  .iconfont{
    cursor: pointer;
    margin-left: 6px;
    font-size: 18px;
  }
  .icon-fuzhichenggong1{
    font-size: 20px;
  }
}
::v-deep .el-table tr .el-table__cell{
  padding: 8px 0 !important;
}
.location-item{
  ::v-deep .el-form-item{
    display: flex;
    justify-content: flex-start;
    margin-right: 0 !important;
    .el-form-item__content{
      width: 586px !important;
      display: flex;
      justify-content: space-between;
      .el-input:first-child{
        margin-right: 20px;
      }
    }
  }
}

.libImg-list{
  display: flex;
  justify-content: flex-start;
  width: 600px;
  margin-bottom: 10px;
  .libImg-item{
    position: relative;
    display: flex;
    justify-content: flex-start;
    height: 96px;
    margin-right: 10px;
    img{
      display: block;
      height: 100%;
    }
    i{
      // position: absolute;
      // left: 4px;
      // top: 0;
      color: red;
      cursor: pointer;
      margin: 76px 0 0 5px;
    }
  }
}
.padding-style-input{
  .edit-readonly{
    width: 289px !important;
    border-right: none !important;
    margin-right: 0 !important;
    border-radius: 4px 0 0 4px !important;
  }
}
.edit-slot {
  background-color: #f5f7fa;
  color: #909399;
  display: block;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 0 4px 4px 0;
  padding: 0 20px;
  white-space: nowrap;
  height: 32px;
}
</style>
