<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.buildId"
          filterable
          clearable
          size="small"
          placeholder="请选择建筑名称"
          class="filter-item"
          style="width: 160px"
          @change="handleChangeBuildId"
        >
          <el-option
            v-for="item in optionsObj.Build"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.floorNo"
          filterable
          clearable
          size="small"
          placeholder="请选择楼层"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.FloorNo"
            :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="buildId">
              <el-select
                v-model="form.buildId"
                size="small"
                class="filter-item"
                style="width: 280px"
                disabled
              >
                <el-option
                  v-for="item in optionsObj.Build"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="楼层" prop="floorNo">
              <el-input
                v-model="form.floorNo"
                size="small"
                class="filter-item"
                style="width: 280px"
                disabled
              />
            </el-form-item>
            <el-form-item label="所有楼层显示" prop="solidRail">
              <el-switch
                v-model="form.allFloor"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="true"
                :inactive-value="false"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <div v-for="(item, index) in form.segments" :key="index" style="margin-top: 40px">
              <el-form-item
                :label="'分段编号' + (index + 1)"
                :prop="'segments[' + index + '].code'"
                :rules="{ required: true, message: '请输入分段编号', trigger: 'blur' }"
              >
                <el-input
                  v-model="item.code"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item
                label="分段长度(米)"
                :prop="'segments[' + index + '].length'"
                :rules="{ required: true, validator: chackLength, trigger: 'blur' }"
              >
                <el-input
                  v-model="item.length"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="分段在线标签" prop="onlineTag">
                <el-input
                  v-model="item.onlineTag"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="在线报警类型" prop="onlineTagAlarmType">
                <el-select
                  v-model="item.onlineTagAlarmType"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                  clearable
                >
                  <el-option
                    v-for="item in optionsObj.DataAlarmType"
                    :key="item.value"
                    :label="item.label"
                    :value="+item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="分段警告标签" prop="warmTag">
                <el-input
                  v-model="item.warmTag"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="警告报警类型" prop="warmTagAlarmType">
                <el-select
                  v-model="item.warmTagAlarmType"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                  clearable
                >
                  <el-option
                    v-for="item in optionsObj.DataAlarmType"
                    :key="item.value"
                    :label="item.label"
                    :value="+item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="分段报警标签" prop="alarmTag">
                <el-input
                  v-model="item.alarmTag"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="报警报警类型" prop="alarmTagAlarmType">
                <el-select
                  v-model="item.alarmTagAlarmType"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                  clearable
                >
                  <el-option
                    v-for="item in optionsObj.DataAlarmType"
                    :key="item.value"
                    :label="item.label"
                    :value="+item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="分段报警位置标签" prop="alarmPositionTag">
                <el-input
                  v-model="item.alarmPositionTag"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="分段报警位置单位长度(米)" prop="alarmPositionLength">
                <el-input
                  v-model="item.alarmPositionLength"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <div v-for="(item2, index2) in item.cameras" :key="index2" style="margin-top: 40px">
                <el-form-item
                  :label="'绑定摄像头' + (index + 1)"
                  :prop="'segments[' + index + '].cameras[' + index2 + '].cameraId'"
                  :rules="{ required: true, message: '请选则摄像头', trigger: 'blur' }"
                >
                  <el-select
                    v-model="item2.cameraId"
                    size="small"
                    class="filter-item"
                    style="width: 280px"
                  >
                    <el-option
                      v-for="item in optionsObj.Camera"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="预置点" prop="presetIndex">
                  <el-select
                    v-model="item2.presetIndex"
                    size="small"
                    class="filter-item"
                    style="width: 280px"
                    clearable
                  >
                    <el-option
                      v-for="item in Array.from({ length: 255 }, (item, index) => index + 1)"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
                <div style="width: 360px; text-align: right">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deleteCamera(index, index2)"
                    v-if="form.segments[index].cameras"
                  >
                    删除摄像头
                  </el-button>
                  <el-button
                    v-if="index2 == form.segments[index].cameras.length - 1"
                    type="primary"
                    size="mini"
                    @click="addCamera(index)"
                  >
                    增加摄像头
                  </el-button>
                </div>
              </div>
              <div
                style="width: 360px; text-align: right; margin-top: 20px"
                v-if="!form.segments[index].cameras || form.segments[index].cameras.length == 0"
              >
                <el-button type="primary" size="mini" @click="addCamera(index)">
                  增加摄像头
                </el-button>
              </div>
              <div style="width: 360px; text-align: right; margin-top: 20px">
                <el-button
                  type="warning"
                  size="mini"
                  @click="simSegmentAlarm(index)"
                  v-if="form.segments.length > 1 || index > 0"
                >
                  模拟报警
                </el-button>

                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteSegment(index)"
                  v-if="form.segments.length > 1 || index > 0"
                >
                  删除分段
                </el-button>
                <el-button
                  v-if="index == form.segments.length - 1"
                  type="primary"
                  size="mini"
                  @click="addSegment"
                >
                  增加分段
                </el-button>
              </div>
            </div>
          </el-form>
        </el-col>
        <el-col :span="16">
          <relative-map
            v-if="crudCU"
            ref="RelativeMap"
            :buildFloor="buildFloor"
            v-model="mapData"
            :background="mapBackground"
            drawShow
            drawMode="LineString"
            :lineLengthShow="true"
          />
        </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 perimeterConfigTableOptions"
        :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 === 'iconPath'"
            :src="VUE_APP_BASE_API + scope.row.iconPath"
            alt=""
          />
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'perimeter:config:edit', 'perimeter:config: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 crudPerimeter from '@/api/perimeter/config'
import { getOptions } from '@/api/options'
import { getOptions as getOptions2 } from '@/api/perimeter/public'
import { simAlarm } from '@/api/perimeter/sim'
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 { perimeterConfigTableOptions } from '../tableConfig'
import { initData } from '@/api/data'

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

const defaultForm = {
  id: '0',
  code: '', //编号
  name: '', //名称
  buildId: '', //建筑ID
  floorNo: null, //楼层号
  points: [], //坐标
  segments: [{}],
  remark: '', //备注
}

export default {
  name: 'PerimeterConfig',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, DateRangePicker, RelativeMap },
  cruds() {
    return CRUD({
      title: '周界',
      url: 'perimeter/config/getPageListJson',
      listOrder: [],
      crudMethod: { ...crudPerimeter },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    VUE_APP_BASE_WS() {
      return 'ws://' + window.location.host + process.env.VUE_APP_BASE_API
    },
  },
  data() {
    return {
      perimeterConfigTableOptions,
      permission: {
        add: ['admin', 'perimeter:config:add'],
        edit: ['admin', 'perimeter:config:edit'],
        del: ['admin', 'perimeter:config:del'],
      },
      rules: {
        code: [{ required: true, message: '请选输入编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        buildId: [{ required: true, message: '请在地图上画点', trigger: 'blur' }],
        floorNo: [{ required: true, message: '请在地图上画点', trigger: 'blur' }],
        //'item.code': [{ required: true, message: '请输入分段编号', trigger: 'blur' }],
        //'item.length': [{ required: true, validator: chackLength, trigger: 'blur' }],
      },
      optionsObj: {
        Build: [],
        FloorNo: [],
        Camera: [],
        DataAlarmType: [],
      },
      iconOptions: [],
      mapData: [],
      buildFloor: {},
      mapBackground: [],
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    chackLength(rule, value, callback) {
      if (!isPosNumber(value)) return callback(new Error('请输入正确的分段长度'))
      return callback()
    },
    [CRUD.HOOK.beforeToAdd]() {
      this.mapData = []
      this.buildFloor = {}
      this.getMapBackground(0)
    },
    // 打开
    [CRUD.HOOK.beforeToEdit]() {
      this.mapData = [
        {
          buildId: this.form.buildId,
          floorNo: this.form.floorNo,
          geometries: [
            {
              type: 'LineString',
              points: this.form.points,
            },
          ],
        },
      ]
      this.buildFloor = {
        buildId: this.form.buildId,
        floorNo: this.form.floorNo,
      }
      this.getMapBackground(this.form.id)
    },
    //验证前处理
    [CRUD.HOOK.beforeValidateCU]() {
      if (
        this.mapData &&
        this.mapData.length > 0 &&
        this.mapData[0].geometries &&
        this.mapData[0].geometries.length > 0 &&
        this.mapData[0].geometries[0].points &&
        this.mapData[0].geometries[0].points.length > 1
      ) {
        this.form.buildId = this.mapData[0].buildId
        if (form.allFloor) this.form.floorNo = 0
        else this.form.floorNo = this.mapData[0].floorNo
        this.form.points = this.mapData[0].geometries[0].points
      } else {
        this.$message.error('请绘制正确的线段')
        return false
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {},
    async handleChangeBuildId(val) {
      await this.getFloorNoOption(val)
      this.crud.toQuery()
    },
    addSegment() {
      this.form.segments.push({})
    },
    deleteSegment(index) {
      this.form.segments.splice(index, 1)
    },
    addCamera(index) {
      if (this.form.segments[index].cameras) this.form.segments[index].cameras.push({})
      else this.form.segments[index].cameras = [{}]
    },
    deleteCamera(index, index2) {
      this.form.segments[index].cameras.splice(index2, 1)
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        if (key == 'FloorNo') return
        if (key == 'Camera' || key == 'DataAlarmType') {
          try {
            let res = await getOptions2(key)
            if (res.code === 20000) this.optionsObj[key] = res.data.content
          } catch (error) {
            console.log(error)
          }
        } else {
          try {
            let res = await getOptions(key)
            if (res.code === 20000) this.optionsObj[key] = res.data.content
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    async getFloorNoOption(buildId) {
      try {
        let res = await getOptions('FloorNo', { buildId: buildId })
        if (res.code === 20000) {
          this.optionsObj.FloorNo = res.data.content
          this.query.floorNo = null
        }
      } catch (error) {}
    },
    getMapBackground(id) {
      initData('perimeter/config/getPageListJson', {}).then((res) => {
        if (res.code == 20000 && res.data && res.data.content) {
          let back = []
          res.data.content.forEach((p) => {
            if (p.id != id) {
              back.push({
                buildId: p.buildId,
                floorNo: p.floorNo,
                geometries: [
                  {
                    type: 'LineString',
                    points: p.points,
                    symbol: {
                      lineColor: '#32CD32',
                      lineWidth: 2,
                      lineOpacity: 1,
                    },
                  },
                ],
              })
            }
          })
          this.mapBackground = back
        }
      })
    },
    simSegmentAlarm(index) {
      let simSegment = this.form.segments[index]
      // simSegment.buildId = this.form.buildId
      // simSegment.floorNo = this.form.floorNo
      if (!simSegment.id) {
        //未保存的不能模拟
        console.log('请先保存再进行模拟操作')
        return
      }
      try {
        const param = {
          buildId: this.form.buildId,
          floorNo: this.form.floorNo,
          segments: [this.form.segments[index]],
        }
        console.log(param)
        simAlarm(param)
      } catch (error) {}
    },
  },
}
</script>

<style></style>
