<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-select
          v-model="query.buildId"
          filterable
          size="small"
          placeholder="请选择建筑名称"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.Build"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="query.areaName"
          clearable
          size="small"
          placeholder="输入区域名称"
          style="width: 160px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.riskLevel"
          filterable
          clearable
          size="small"
          placeholder="请选择区域风险等级"
          class="filter-item"
          style="width: 180px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.RiskLevel"
            :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="PositioningBuildId">
              <el-select
                v-model="form.positioningBuildId"
                filterable
                size="small"
                placeholder="请选择建筑名称"
                class="filter-item"
                style="width: 280px"
                @change="handleChangeBuildId"
              >
                <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="areaName">
              <el-input
                v-model="form.areaName"
                size="small"
                class="filter-item"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="区域风险等级" prop="riskLevel">
              <el-select
                v-model="form.riskLevel"
                filterable
                clearable
                size="small"
                placeholder="请选择区域风险等级"
                class="filter-item"
                style="width: 280px"
              >
                <el-option
                  v-for="item in optionsObj.RiskLevel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </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="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>
            <el-row>
              <el-col
                :span="8"
                style="
                  font-size: 14px;
                  color: #606266;
                  font-weight: 600;
                  text-align: center;
                  padding-top: 6px;
                "
              >
                围栏选择
              </el-col>
              <el-col :span="16">
                <el-form-item prop="railIds">
                  <el-checkbox-group v-model="form.railIds">
                    <el-checkbox
                      style="
                        font-size: 14px;
                        color: #606266;
                        font-weight: 600;
                        text-align: center;
                        padding-top: 6px;
                      "
                      v-for="item in railList"
                      :key="item.id"
                      :label="item.id"
                      @change="(checked) => railsChangeHandle(checked, item)"
                      >{{ item.railName }}</el-checkbox
                    >
                  </el-checkbox-group>
                </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"
            :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 areaTableOptions"
        :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 crudArea from '@/api/positioning/area'
import { getOptions } from '@/api/positioning/public'
import { initData } from '@/api/data'
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 { areaTableOptions } from '../tableConfig'
// import AreaMap from './areaMap.vue'
import RelativeMap from '@/components/RelativeMap'

const defaultForm = {
  id: null,
  positioningBuildId: '',
  floorNo: '',
  areaName: '',
  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,
  effectiveTimeJson: '',
  rails: [],
  railIds: [],
  effectiveTimes: [{ timeRange: ['00:00', '23:59'], weekday: [1, 2, 3, 4, 5, 6, 7] }],
}

export default {
  name: 'Area',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, DateRangePicker, RelativeMap },
  cruds() {
    return CRUD({
      title: '区域',
      url: 'positioning/area/getPageListJson',
      listOrder: [],
      crudMethod: { ...crudArea },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    defaultBuildId() {
      let did = null
      if (this.$setting) {
        let buildNo = this.$setting.DefaultBuild
        if (this.$setting.BuildList && this.$setting.BuildList[buildNo]){
          did = this.$setting.BuildList[buildNo].BuildId
        }
      }
      return did
    }
  },
  data() {
    return {
      areaTableOptions,
      permission: {
        add: ['admin', 'area:add'],
        edit: ['admin', 'area:edit'],
        del: ['admin', 'area:del'],
      },
      rules: {
        positioningBuildId: [{ required: true, message: '请选择建筑名称', trigger: 'blur' }],
        areaName: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
        railIds: [{ required: true, message: '请选择围栏', trigger: 'blur' }],
      },
      optionsObj: { Build: [], RiskLevel: [] },
      railList: [],
      mapData: [],
      buildFloor: {},
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      // console.log(areaRailList);
      this.form.effectiveTimes.forEach((item) => {
        if (Array.isArray(item.timeRange) && item.timeRange.length) {
          item.startTime = item.timeRange[0]
          item.endTime = item.timeRange[1]
        }
      })
    },
    [CRUD.HOOK.beforeToAdd]() {
      if (this.form.id) delete this.form.id
      this.mapData = []
      this.buildFloor = {}
      this.form.railIds = []
      this.railList = []
      this.form.positioningBuildId = this.defaultBuildId
      if (this.form.positioningBuildId) this.getRailData(this.form.positioningBuildId)
      // console.log(this.form)
    },
    // 打开
    [CRUD.HOOK.beforeToEdit]() {
      this.railList = []
      if (this.form.positioningBuildId) this.getRailData(this.form.positioningBuildId)
      if (this.form.rails === null) {
        this.form.rails = []
      }
      if (this.form.railIds === null) {
        this.form.railIds = []
      }
      if (this.form.rails.length > 0) {
        let frist = true
        this.mapData = []
        this.form.rails.forEach((r) => {
          if (frist) {
            this.buildFloor = {
              buildId: r.positioningBuildId,
              floorNo: r.floorNo,
            }
            frist = false
          }
          this.mapData.push({
            buildId: r.positioningBuildId,
            floorNo: r.floorNo,
            geometries: [
              {
                type: 'Polygon',
                points: r.points,
              },
            ],
          })
        })
      }

      this.form.effectiveTimes.forEach((item) => {
        let timer = []
        if (item.startTime && item.endTime) {
          timer = [item.startTime, item.endTime]
          item.timeRange = timer
        }
      })
      // this.form.points = this.form.ponits
      // console.log(this.form)
    },
    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]
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) {
            this.optionsObj[key] = res.data.content
            if (key == 'Build') {
              this.query.buildId = this.optionsObj.Build[0].value
              this.crud.toQuery()
            }
          }
        } catch (error) {
          console.log(error)
        }
      })
    },
    railsChangeHandle(checked, rail) {
      if (checked) {
        this.buildFloor = {
          buildId: rail.buildId,
          floorNo: rail.floorNo,
        }
      }
      let data = []
      if (this.form.railIds.length > 0) {
        this.form.railIds.forEach((rId) => {
          let rail = this.railList.find((a) => a.id == rId)
          if (rail) {
            data.push({
              buildId: rail.buildId,
              floorNo: rail.floorNo,
              geometries: [
                {
                  type: 'Polygon',
                  points: rail.points,
                },
              ],
            })
          }
        })
      }
      console.log(data)
      this.mapData = data
    },
    //获取弹窗内的围栏信息
    async getRailData(buildId) {
      try {
        let res = await initData('positioning/rail/getPageListJson', {
          buildId: buildId,
          PageIndex: 0,
          PageSize: 0,
        })
        this.railList = res.data.content
        //console.log(this.railList)
      } catch (error) {
        console.log(error)
      }
    },
    async handleChangeBuildId(val) {
      this.form.railIds = []
      if (val) await this.getRailData(val)
    }
  },
}
</script>

<style></style>
