<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.code"
          clearable
          size="small"
          placeholder="输入高后果区编号"
          style="width: 160px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="输入高后果区名称"
          style="width: 160px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <treeselect
          v-model="query.networkId"
          :load-options="loadNetworkChildren"
          :options="networkOptions"
          style="width: 160px"
          placeholder="请选择隶属管网"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!-- 表单组件 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="1200px"
    >
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
            <el-form-item label="编号" prop="code">
              <el-input v-model="form.code" size="small" class="filter-item" style="width: 280px" />
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" size="small" class="filter-item" style="width: 280px" />
            </el-form-item>
            <el-form-item label="隶属管网" prop="networkId">
              <treeselect
                v-model="form.networkId"
                :load-options="loadNetworkChildren"
                :options="networkOptions"
                style="width: 280px; font-size: 12px"
                placeholder="请选择隶属管网"
                @input="handleChangeNetworkId"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                autosize
                clearable
                style="width: 280px"
              />
            </el-form-item>
            <el-table :data="form.points" style="width: 100%">
              <el-table-column prop="longitude" label="经度" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`points[${scope.$index}].longitude`"
                    :rules="{ required: true, trigger: 'blur' }"
                    style="margin-bottom: 0px"
                  >
                    <el-input-number
                      v-model="scope.row.longitude"
                      size="small"
                      :min="-180"
                      :max="180"
                      :step="0.0001"
                      controls-position="right"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="latitude" label="纬度" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`points[${scope.$index}].latitude`"
                    :rules="{ required: true, trigger: 'blur' }"
                    style="margin-bottom: 0px"
                  >
                    <el-input-number
                      v-model="scope.row.latitude"
                      size="small"
                      :min="-180"
                      :max="180"
                      :step="0.0001"
                      controls-position="right"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="operation" label="删除" align="center" width="60px">
                <template slot-scope="scope">
                  <el-popconfirm title="确定删除此数据吗？" @confirm="handleDelPoint(scope)">
                    <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference" />
                  </el-popconfirm>
                </template>
              </el-table-column>
              <template slot="append">
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-circle-plus-outline"
                  @click="handleAddPoint()"
                  style="width: 100%"
                />
              </template>
            </el-table>
          </el-form>
        </el-col>
        <el-col :span="16">
          <gps-map
            v-if="crudCU"
            ref="GPSMap"
            v-model="mapData"
            drawShow
            drawMode="Polygon"
            :background="mapBackground"
          />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU"> 取消 </el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">
          确认
        </el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        v-for="item in hcaTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
        <template slot-scope="scope">
          <img
            style="width: 32px; height: 32px"
            v-if="item.prop === 'typeIconPath'"
            v-show="scope.row.typeIconPath"
            :src="VUE_APP_BASE_API + scope.row.typeIconPath"
            alt=""
          />
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'pipe:hca:edit', 'pipe:hca:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation :data="scope.row" :permission="permission" />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudHca from '@/api/pipe/hca'
import crudNetwork from '@/api/pipe/network'
import { getOptions } from '@/api/pipe/public'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import DateRangePicker from '@/components/DateRangePicker'
import { hcaTableOptions } from '../tableConfig'
import { initData } from '@/api/data'

// vue-treeselect
import Treeselect from '@riophae/vue-treeselect'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import GpsMap from '@/components/GpsMap'

const defaultForm = {
  id: '0',
  code: '', //编号
  name: '', //名称
  networkId: undefined, //隶属管网
  points: [], //多边形点
  remark: null, //备注
}

export default {
  name: 'PipeHca',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, DateRangePicker, Treeselect, GpsMap },
  cruds() {
    return CRUD({
      title: '高后果区',
      url: 'pipe/hca/getList',
      listOrder: [],
      crudMethod: { ...crudHca },
      optShow: { add: true, edit: true, del: true, reset: true, import: false, export: false },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    mapData: {
      get: function () {
        let data = null
        if (this.form.id && this.form.id > 0 && this.form.points && this.form.points.length > 2) {
          data = [
            {
              geometries: [
                {
                  type: 'Polygon',
                  points: this.form.points.map((p) => {
                    return { x: p.longitude, y: p.latitude }
                  }),
                },
              ],
            },
          ]
        }
        return data
      },
      set: function (newValue) {
        if (newValue) {
          const ps = newValue[0].geometries[newValue[0].geometries.length - 1].points
            .map((p) => {
              return { longitude: p.x, latitude: p.y }
            })
          ps.pop()
          this.form.points = ps
        }
      },
    },
  },
  watch: {
  },
  data() {
    return {
      hcaTableOptions,
      permission: {
        add: ['admin', 'pipe:hca:add'],
        edit: ['admin', 'pipe:hca:edit'],
        del: ['admin', 'pipe:hca:del'],
      },
      rules: {
        code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        networkId: [{ required: true, message: '请选择隶属管网', trigger: 'blur' }],
      },
      optionsObj: {
        LineType: [],
        ControlpointType: [],
        Controlpoint: [],
      },
      networkOptions: [],
      mapBackground: null,
    }
  },
  created() {
    //this.getOptions()
    this.loadNetworkRoot()
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.parentId == '0') {
        form.parentId = null
      }
      crudNetwork.getParentTree({ id: form.network }).then((res) => {
        this.networkOptions = res.data.content
      })
      this.refreshBackground(this.form.networkId)
    },
    //验证前处理
    [CRUD.HOOK.beforeValidateCU]() {
      if (!this.form.points || this.form.points.length < 3) {
        this.$message.error('请绘制正确的多边形')
        return false
      }
    },
    refreshBackground(networkId) {
      console.log(networkId)
      if (networkId && networkId > 0) {
        this.mapBackground = []
        initData('pipe/controlpoint/getListFromCache', { network: networkId }).then((res) => {
          console.log(res)
          if (res.code == 20000 && res.data.content && res.data.content.length > 0) {
            const point = []
            const line = []
            res.data.content.forEach((p) => {
              point.push({
                type: 'Point',
                points: [{ x: p.longitude, y: p.latitude }],
                symbol: {
                  markerFile: p.typeIconPath ? this.VUE_APP_BASE_API + p.typeIconPath : null,
                  markerWidth: 20,
                  markerHeight: 20,
                  markerDx: 0,
                  markerDy: 10,
                  textName: p.name,
                  textDx: 0,
                  textDy: 20,
                  textFill : '#e0e0e0',
                },
              })
              if (
                p.inPipeLineStartLocation_Latitude &&
                p.inPipeLineStartLocation_Longitude &&
                p.inPipeLineTypeColor &&
                p.latitude &&
                p.longitude
              ) {
                line.push({
                  type: 'LineString',
                  points: [
                    {
                      x: p.inPipeLineStartLocation_Longitude,
                      y: p.inPipeLineStartLocation_Latitude,
                    },
                    { x: p.longitude, y: p.latitude },
                  ],
                  symbol: {
                    lineColor: p.inPipeLineTypeColor,
                    lineWidth: 1,
                    lineOpacity: 1,
                  },
                })
              }
            })

            this.mapBackground.push({ geometries: line }, { geometries: point })
          } else {
            this.mapBackground = null
          }
        })
      }
    },
    loadNetworkRoot() {
      crudNetwork.getChildren({ id: 0 }).then((res) => {
        this.networkOptions = res.data.content
      })
    },
    loadNetworkChildren({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudNetwork.getChildren({ id: parentNode.id }).then((res) => {
          parentNode.children = res.data.content
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    handleDelPoint(scope) {
      this.form.points.splice(scope.$index, 1)
    },
    handleAddPoint() {
      this.form.points.push({
        longitude: 0,
        latitude: 0,
      })
    },
    handleChangeNetworkId(nid) {
      //console.log(nid)
      this.refreshBackground(nid)
    }
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect {
  font-size: 13px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 10px 10px 0;
}
::v-deep .vue-treeselect .vue-treeselect__control {
  height: 30.5px;
}
</style>