<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-select
          v-model="query.buildId"
          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"
          clearable
          size="small"
          placeholder="请选择楼层"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.Floor"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="query.railName"
          clearable
          size="small"
          placeholder="输入围栏名称"
          style="width: 160px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <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="buildId">
              <el-select
                v-model="form.buildId"
                clearable
                size="small"
                placeholder="请选择建筑名称"
                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="railName">
              <el-input
                v-model="form.railName"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </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>
            <el-row>
              <el-col :span="24">
                <el-form-item label="立体围栏" prop="solidRail">
                  <el-switch
                    v-model="form.solidRail"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="进出记录" prop="enableLog">
                  <el-switch
                    v-model="form.enableLog"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="越界报警" prop="crossAlarm">
                  <el-switch
                    v-model="form.crossAlarm"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="滞留报警" prop="overstayAlarm">
                  <el-switch
                    v-model="form.overstayAlarm"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col v-if="form.overstayAlarm" :span="13">
                <el-form-item label="滞留时间" prop="overstayTime">
                  <el-input-number controls-position="right" v-model="form.overstayTime" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="超员报警" prop="overmanAlarm">
                  <el-switch
                    v-model="form.overmanAlarm"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col v-if="form.overmanAlarm" :span="13">
                <el-form-item label="超员人数" prop="overmanCount">
                  <el-input-number controls-position="right" v-model="form.overmanCount" />
                </el-form-item>
                <el-form-item label="超员时间" prop="overmanTime">
                  <el-input-number controls-position="right" v-model="form.overmanTime" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="缺员报警" prop="undermanAlarm">
                  <el-switch
                    v-model="form.undermanAlarm"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col v-if="form.undermanAlarm" :span="13">
                <el-form-item label="缺员人数" prop="undermanCount">
                  <el-input-number controls-position="right" v-model="form.undermanCount" />
                </el-form-item>
                <el-form-item label="缺员时间" prop="undermanTime">
                  <el-input-number controls-position="right" v-model="form.undermanTime" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="静止报警" prop="actionlessAlarm">
                  <el-switch
                    v-model="form.actionlessAlarm"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="true"
                    :inactive-value="false"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col v-if="form.actionlessAlarm" :span="13">
                <el-form-item label="静止时间" prop="actionlessTime">
                  <el-input-number controls-position="right" v-model="form.actionlessTime" />
                </el-form-item>
              </el-col>
            </el-row>
            <div v-for="(item, index) in form.effectiveTimes" :key="index" style="margin-top: 10px">
              <el-form-item :label="'作用时间' + (index + 1)" prop="timeRange">
                <el-time-picker
                  is-range
                  v-model="item.timeRange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  style="width: 280px"
                  format="HH:mm"
                  value-format="HH:mm"
                  @change="handleChangeTime($event, index)"
                >
                </el-time-picker>
              </el-form-item>
              <el-form-item label="" prop="weekday" label-width="30px">
                <el-checkbox-group v-model="item.weekday" style="width: 340px">
                  <el-checkbox :label="1">周一</el-checkbox>
                  <el-checkbox :label="2">周二</el-checkbox>
                  <el-checkbox :label="3">周三</el-checkbox>
                  <el-checkbox :label="4">周四</el-checkbox>
                  <el-checkbox :label="5">周五</el-checkbox>
                  <el-checkbox :label="6">周六</el-checkbox>
                  <el-checkbox :label="7">周日</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <div style="width: 360px; text-align: right">
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteActionTime(index)"
                  v-if="form.effectiveTimes.length > 1 || index > 0"
                >
                  删除
                </el-button>
                <el-button
                  v-if="index == form.effectiveTimes.length - 1"
                  type="primary"
                  size="mini"
                  @click="addActionTime"
                >
                  增加
                </el-button>
              </div>
            </div>
          </el-form>
        </el-col>
        <el-col :span="16">
          <relative-map
            v-if="crudCU"
            ref="relativeMap"
            v-model="mapData"
            drawShow
            :buildFloor="buildFloor"
            drawMode="Polygon"
          />
        </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 railTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      ></el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'rail:edit', 'rail: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 crudRail from '@/api/positioning/rail'
import { getOptions } from '@/api/positioning/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 { railTableOptions } from '../tableConfig'
// import RailMap from './railMap.vue'
import RelativeMap from '@/components/RelativeMap'

const defaultForm = {
  // id: null,
  buildId: '',
  floorNo: '',
  railName: '',
  remark: '',
  riskLevel: null,
  enableLog: false,
  crossAlarm: false,
  overstayAlarm: false,
  overstayTime: 1,
  overmanAlarm: false,
  overmanCount: 0,
  overmanTime: 0,
  undermanAlarm: false,
  undermanCount: 0,
  undermanTime: 0,
  actionlessAlarm: false,
  actionlessTime: 1,
  effectiveTimes: [{ timeRange: ['00:00', '23:59'], weekday: [1, 2, 3, 4, 5, 6, 7] }],
  points: [],
  solidRail: false,
}

export default {
  name: 'Rail',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, DateRangePicker, RelativeMap },
  cruds() {
    return CRUD({
      title: '围栏',
      url: 'positioning/rail/getPageListJson',
      listOrder: [],
      crudMethod: { ...crudRail },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  data() {
    return {
      mapData: [],
      buildFloor: {},
      railTableOptions,
      permission: {
        add: ['admin', 'rail:add'],
        edit: ['admin', 'rail:edit'],
        del: ['admin', 'rail:del'],
      },
      rules: {
        buildId: [{ required: true, message: '请选择建筑名称', trigger: 'blur' }],
        floorNo: [{ required: true, message: '请输入楼层', trigger: 'blur' }],
        railName: [{ required: true, message: '请输入围栏名称', trigger: 'blur' }],
      },
      optionsObj: { Build: [], Floor: [] },
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    [CRUD.HOOK.beforeToAdd]() {
      if (this.form.id) delete this.form.id
      this.mapData = []
      this.buildFloor = {}
      // console.log(this.form)
    },
    // 打开
    [CRUD.HOOK.beforeToEdit]() {
      this.form.effectiveTimes.forEach((item) => {
        let timer = []
        if (item.startTime && item.endTime) {
          timer = [item.startTime, item.endTime]
          item.timeRange = timer
        }
      })
      this.mapData = [
        {
          buildId: this.form.buildId,
          floorNo: this.form.floorNo,
          geometries: [
            {
              type: 'Polygon',
              points: this.form.points,
            },
          ],
        },
      ]
      this.buildFloor = {
        buildId: this.form.buildId,
        floorNo: this.form.floorNo,
      }
      // this.form.points = this.form.ponits
      // console.log(this.form)
    },
    //验证前处理
    [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 > 3
      ) {
        this.form.buildId = this.mapData[0].buildId
        this.form.floorNo = this.mapData[0].floorNo
        this.mapData[0].geometries[0].points.pop()
        this.form.points = this.mapData[0].geometries[0].points
      } else {
        this.$message.error('请绘制正确的围栏图形')
        return false
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      this.form.effectiveTimes.forEach((item) => {
        if (Array.isArray(item.timeRange) && item.timeRange.length) {
          item.startTime = item.timeRange[0]
          item.endTime = item.timeRange[1]
        }
      })

      if (this.form.solidRail) {
        this.form.floorNo = 0
      }
    },
    addActionTime() {
      const obj = { timeRange: null, weekday: [] }
      this.form.effectiveTimes.push(obj)
    },
    deleteActionTime(index) {
      this.form.effectiveTimes.splice(index, 1)
    },
    handleChangeTime(val, index) {
      this.form.effectiveTimes[index].startTime = val[0]
      this.form.effectiveTimes[index].endTime = val[1]
    },
    async handleChangeBuildId(val) {
      await this.getFloorNoOption(val)
      this.crud.toQuery()
    },
    async getOptions() {
      try {
        let res = await getOptions('Build')
        if (res.code === 20000) {
          this.optionsObj.Build = res.data.content
          this.query.buildId = this.optionsObj.Build[0].value
          this.crud.toQuery()
          await this.getFloorNoOption(this.query.buildId)
        }
      } catch (error) {
        console.log(error)
      }
    },
    async getFloorNoOption(buildId) {
      try {
        let res = await getOptions('FloorNo', { buildId: buildId })
        if (res.code === 20000) {
          this.optionsObj.Floor = res.data.content
          this.query.floorNo = null
        }
      } catch (error) {}
    },
  },
}
</script>

<style></style>
