<template>
  <div class="hum-page-container">
    <div class="extra">
      <div class="extra-name">当前站点：{{ site.siteName }}</div>
      <div class="extra-actions">
        <el-upload :action="uploadAction" :on-success="importSection" name="file" :show-file-list="false">
          <el-button type="primary">导入</el-button>
        </el-upload>
        <el-button :disabled="!this.id" class="extra-action-export" @click="download">导出</el-button>
      </div>
    </div>
    <div class="hum-page-title" style="margin-top: 30px">断面图</div>
    <div class="hum-page-section">
      <SectionChart :sections="sections" />
    </div>
    <div class="hum-page-title" style="margin-top: 30px">断面表</div>
    <div class="hum-page-section">
      <el-form :model="form" :rules="rules" size="large" ref="form" label-position="top">
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="断面名称" prop="berthingName">
              <el-input
                v-model="form.berthingName"
                placeholder="请输入断面名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="loading" :data="tableSections" border height="400">
        <el-table-column label="起点距">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" size="mini" type="text" v-model="form.x" />
            <span v-else>{{ scope.row.x }}</span>
          </template>
        </el-table-column>
        <el-table-column label="高程">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" size="mini" type="text" v-model="form.y" />
            <span v-else>{{ scope.row.y }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isEdit" size="mini" type="text" icon="el-icon-circle-check" @click="saveSection(scope.row)">保存</el-button>
            <el-button v-else size="mini" type="text" icon="el-icon-edit" @click="editSection(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-top" @click="insertSection(scope.row, scope.$index)">向上插入</el-button>
            <el-button size="mini" type="text" icon="el-icon-bottom" @click="insertSection(scope.row, scope.$index + 1)">向下插入</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteSection(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="hum-page-form-action">
      <el-button @click="$router.back()">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
    </div>
  </div>
</template>

<script>
import { getSite } from '@/api/site/site'
import { addSection, getSection } from '@/api/site/berthing'
import SectionChart from './chart';

export default {
  components: {
    SectionChart,
  },
  data() {
    return {
      id: 0,
      siteId: 0,
      site: 0,
      loading: false,
      sections: [],
      tableSections: [],
      form: {
        x: 0,
        y: 0,
        berthingName: '',
      },
      rules: {
        berthingName: [
          {required: true, message: "断面名称不能为空", trigger: "blur"}
        ],
      },
      uploadAction: `${process.env.VUE_APP_BASE_API}/berthing/uploadFile`
    }
  },
  computed: {
    title() {
      return this.id ? '编辑断面' : '新增断面';
    }
  },
  methods: {
    loadSection() {
      getSection(this.id).then((res) => {
        const positions = JSON.parse(res.data.positions) || [];
        this.sections = positions;
        this.form.berthingName = res.data.berthingName;
        this.tableSections = positions.map(({ x, y }) => ({ x, y, isEdit: false }))
      })
    },
    loadSite() {
      getSite(this.siteId).then((res) => {
        this.site = { ...res.data };
      })
    },
    importSection(res) {
      this.sections = res.data || [];
      this.tableSections = (res.data || []).map(({ x, y }) => ({ x, y, isEdit: false }))
    },
    saveSection(s) {
      if (!/^-?\d+(\.\d+)?$/.test(this.form.x)) {
        return this.$message.error("起点距必须是数字")
      }
      if (!/^-?\d+(\.\d+)?$/.test(this.form.y)) {
        return this.$message.error("高程必须是数字")
      }
      s.x = this.form.x;
      s.y = this.form.y;
      s.isEdit = false;
      this.sections = this.tableSections.map(({ x, y }) => ({ x, y }));
    },
    editSection(s) {
      this.tableSections.forEach((r) => r.isEdit = false)
      this.form.x = s.x;
      this.form.y = s.y;
      s.isEdit = true;
    },
    insertSection(section, index) {
      this.tableSections.forEach((r) => r.isEdit = false)
      if (index < 0) {
        const { x, y } = section;
        this.form.x = x;
        this.form.y = y;
        this.sections = [
          { x, y },
          ...this.sections,
        ]
        this.tableSections = [
          { x, y, isEdit: true },
          ...this.tableSections,
        ]
      } else {
        const { x, y } = section;
        this.form.x = x;
        this.form.y = y;
        this.sections = [
          ...this.sections.slice(0, index),
          { x, y },
          ...this.sections.slice(index),
        ]
        this.tableSections = [
          ...this.tableSections.slice(0, index),
          { x, y, isEdit: true },
          ...this.tableSections.slice(index),
        ]
      }
    },
    deleteSection(index) {
      this.tableSections.splice(index, 1);
      this.sections = this.tableSections.map(({ x, y }) => ({ x, y }));
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        this.loading = true;
        addSection({ ...this.form, siteId: this.siteId, positions: this.sections }).then(response => {
          this.$modal.msgSuccess(this.id ? "编辑成功" : "新增成功");
          this.$router.back();
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    download() {
      window.open(`${process.env.VUE_APP_BASE_API}/berthing/downFile/${this.id}`, '_blank')
    },
  },
  mounted() {
    this.id = this.$route.params.id;
    this.siteId = this.$route.query.siteId;
    if (this.siteId) {
      this.loadSite();
    }
    if (this.id) {
      this.loadSection();
    }
  },
}
</script>

<style lang="scss" scoped>
.extra {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  &-name {
    font-size: 14px;
    font-weight: 500;
    color: #1D2738;
  }
  &-actions {
    display: flex;
  }
  &-action-export {
    margin-left: 16px;
  }
}
</style>
