<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"
        />
        <el-select
          v-model="query.type"
          filterable
          clearable
          size="small"
          placeholder="请选择控制点类型"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.ControlpointType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <treeselect
          v-model="query.network"
          :load-options="loadNetworkChildren"
          :options="networkOptions"
          style="width: 160px"
          placeholder="请选择隶属管网"
        />
        <el-select
          v-model="query.inPipeLineType"
          filterable
          clearable
          size="small"
          placeholder="请选择进管类型"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.LineType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.parentId"
          filterable
          clearable
          size="small"
          placeholder="请选择前一控制点"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.Controlpoint"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <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="parentId">
              <el-select
                v-model="form.parentId"
                clearable
                filterable
                size="small"
                class="filter-item"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsObj.Controlpoint"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select
                v-model="form.type"
                filterable
                size="small"
                class="filter-item"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsObj.ControlpointType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="隶属管网" prop="network">
              <treeselect
                v-model="form.network"
                :load-options="loadNetworkChildren"
                :options="networkOptions"
                style="width: 280px; font-size: 12px"
                placeholder="请选择隶属管网"
              />
            </el-form-item>
            <el-form-item label="经度" prop="longitude">
              <el-input-number
                v-model="form.longitude"
                size="small"
                :min="-180"
                :max="180"
                :step="0.0001"
                controls-position="right"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input-number
                v-model="form.latitude"
                size="small"
                :min="-90"
                :max="90"
                :step="0.0001"
                controls-position="right"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="埋深" prop="buriedDepth">
              <el-input
                v-model="form.buriedDepth"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="里程" prop="mileage">
              <el-input
                v-model="form.mileage"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="进管管线号" prop="inPipeLineCode">
              <el-input
                v-model="form.inPipeLineCode"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="进管类型" prop="inPipeLineType">
              <el-select
                v-model="form.inPipeLineType"
                clearable
                filterable
                size="small"
                class="filter-item"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsObj.LineType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="进管管线管径" prop="inPipeLineDiameter">
              <el-input
                v-model="form.inPipeLineDiameter"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="进管管线长度" prop="inPipeLineLength">
              <el-input
                v-model="form.inPipeLineLength"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="进管管线设计压力" prop="inPipeLineDesignPressure">
              <el-input
                v-model="form.inPipeLineDesignPressure"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="16">
          <gps-map
            v-if="crudCU"
            ref="GPSMap"
            v-model="mapData"
            drawShow
            drawMode="Point"
            :symbols="pointSymbols"
            :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 controlpointTableOptions"
        :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:controlpoint:edit', 'pipe:controlpoint: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 crudControlpoint from '@/api/pipe/controlpoint'
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 { controlpointTableOptions } from '../tableConfig'

// 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'

import {
  isPosNumber,
  isNegNumber,
  isNumber,
  isPosInteger,
  isNegInteger,
  isInteger,
} from '@/utils/validate'

const defaultForm = {
  id: '0',
  code: '', //编号
  name: '', //名称
  parentId: '', //前一控制点
  type: '', //类型
  network: undefined, //隶属管网
  longitude: 0, //绝对坐标经度
  latitude: 0, //绝对坐标纬度
  buriedDepth: '', //埋深
  mileage: '', //里程
  inPipeLineCode: '', //进管管线号
  inPipeLineType: '', //进管类型
  inPipeLineDiameter: '', //进管管线管径
  inPipeLineLength: '', //进管管线长度
  inPipeLineDesignPressure: '', //进管管线设计压力
}

export default {
  name: 'PipeControlpoint',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, DateRangePicker, Treeselect, GpsMap },
  cruds() {
    return CRUD({
      title: '控制点',
      url: 'pipe/controlpoint/getList',
      listOrder: [],
      crudMethod: { ...crudControlpoint },
      optShow: { add: true, edit: true, del: true, reset: true, import: true, export: true },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    pointSymbols() {
      let p = null
      let item = this.optionsObj.ControlpointType.find((a) => a.value == this.form.type)
      if (item && item.aux1) {
        p = {
          markerFile: this.VUE_APP_BASE_API + item.aux1,
          markerWidth: 40,
          markerHeight: 40,
          markerDx: 0,
          markerDy: 20,
        }
      }
      return {
        Point: p,
      }
    },
    mapData: {
      get: function () {
        //console.log(this.form.id)
        let data = null
        if (this.form.id) {
          data = [
            {
              geometries: [
                { type: 'Point', points: [{ x: this.form.longitude, y: this.form.latitude }] },
              ],
            },
          ]
          if (this.form.longitude && this.form.latitude && this.parentEntity && this.parentEntity.longitude && this.parentEntity.latitude) {
            data[0].geometries.unshift({
              type: 'LineString',
              points: [
                { x: this.form.longitude, y: this.form.latitude },
                { x: this.parentEntity.longitude, y: this.parentEntity.latitude },
              ],
            })
          }
        }
        return data
      },
      set: function (newValue) {
        if (newValue) {
          this.form.longitude = newValue[0].geometries[newValue[0].geometries.length-1].points[0].x
          this.form.latitude = newValue[0].geometries[newValue[0].geometries.length-1].points[0].y
        }
      },
    },
  },
  watch: {
    'form.parentId': async function (newValue, oldValue) {
      let background = null
      if (newValue) {
        let entity = await crudControlpoint.getEntityFromCache({ id: newValue })
        if ((entity.code = 20000)) this.parentEntity = entity.data
        else this.parentEntity = null
        if (this.parentEntity) {
          if (this.parentEntity.typeIconPath) {
            background = [
              {
                geometries: [
                  {
                    type: 'Point',
                    points: [{ x: this.parentEntity.longitude, y: this.parentEntity.latitude }],
                    symbol: {
                      markerFile: this.VUE_APP_BASE_API + this.parentEntity.typeIconPath,
                      markerWidth: 40,
                      markerHeight: 40,
                      markerDx: 0,
                      markerDy: 20,
                      textName: this.parentEntity.name,
                      textDx: 0,
                      textDy: 30,
                    },
                  },
                ],
              },
            ]
          } else {
            background = [
              {
                geometries: [
                  {
                    type: 'Point',
                    points: [{ x: this.parentEntity.longitude, y: this.parentEntity.latitude }],
                    symbol: {
                      markerType: 'ellipse',
                      markerFill: '#00FA9A',
                      markerFillOpacity: 1,
                      markerLineColor: '#000',
                      markerLineWidth: 1,
                      markerLineOpacity: 1,
                      markerLineDasharray: [],
                      markerWidth: 20,
                      markerHeight: 20,
                      markerDx: 0,
                      markerDy: 0,
                      textName: this.parentEntity.name,
                      textDx: 0,
                      textDy: 20,
                    },
                  },
                ],
              },
            ]
          }
        }
      } else this.parentEntity = null
      this.mapBackground = background
    },
  },
  data() {
    var chackNumber = (rule, value, callback) => {
      if (value && !isNumber(value)) return callback(new Error('请输入数字'))
      return callback()
    }
    var chackPosNumber = (rule, value, callback) => {
      if (value && !isPosNumber(value)) return callback(new Error('请输入正数'))
      return callback()
    }
    var chackLineType = (rule, value, callback) => {
      if (this.form.parentId && !value) return callback(new Error('请选择进管类型'))
      return callback()
    }
    return {
      controlpointTableOptions,
      permission: {
        add: ['admin', 'pipe:controlpoint:add'],
        edit: ['admin', 'pipe:controlpoint:edit'],
        del: ['admin', 'pipe:controlpoint:del'],
      },
      rules: {
        code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        network: [{ required: true, message: '请选择隶属管网', trigger: 'blur' }],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
        buriedDepth: [{ validator: chackNumber, trigger: 'blur' }],
        mileage: [{ validator: chackPosNumber, trigger: 'blur' }],
        inPipeLineType: [{ validator: chackLineType, trigger: 'blur' }],
        inPipeLineDiameter: [{ validator: chackPosNumber, trigger: 'blur' }],
        inPipeLineLength: [{ validator: chackPosNumber, trigger: 'blur' }],
        inPipeLineDesignPressure: [{ validator: chackPosNumber, trigger: 'blur' }],
      },
      optionsObj: {
        LineType: [],
        ControlpointType: [],
        Controlpoint: [],
      },
      networkOptions: [],
      parentEntity: {},
      mapBackground: [],
    }
  },
  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
      })
    },
    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)
        }
      })
    },
  },
}
</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>