<template>
  <div class="meta-container">
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="输入巡检对象名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-cascader
          v-model="query.departmentId"
          :options="departmentOptions"
          :props="{ checkStrictly: true, emitPath: false }"
          filterable
          clearable
          size="small"
          placeholder="请选择责任部门"
          style="width: 160px"
          class="filter-item"
        />
        <!-- <el-select
          v-model="query.areaId"
          filterable
          clearable
          size="small"
          placeholder="请输入所属区域"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in areaOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!-- 批量地图 -->
    <!-- <batch-map :mapData="mapData" :openOrClose="true"/> -->
    <!-- 巡检项目清单 -->
    <el-dialog
      class="patrol-item"
      width="50%"
      title="巡检项目清单"
      :visible.sync="patrolItem"
      >
      <patrol-item ref='patrolItems' />
      <span slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="patrolItem = false">保 存</el-button> -->
        <el-button @click="patrolItem = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 选择区域 -->
    <select-area title="选择区域" ref="selectArea" width="30%" @getData="selectArea" />
    <!-- 选择部门 -->
    <select-department title="选择部门" ref='selectDepartment' width="40%" @getData="selectDepartmentInCharge"/>
    <!-- 选择人员 -->
    <select-user title="选择人员" ref='selectUser' width="60%"  @getData="selectPersonInCharge" />
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="1150px"
    >
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
            <el-form-item label="巡检对象名称" prop="name">
              <el-input v-model="form.name" size="small" class="filter-item"  />
            </el-form-item>
            <el-form-item label="巡检对象编号" prop="code">
              <el-input v-model="form.code" size="small" class="filter-item" />
            </el-form-item>
            <el-form-item label="位置" prop="locationJson">
              <el-input v-model="form.locationJson" size="small" class="filter-item"  disabled/>
            </el-form-item>
            <el-form-item label="所属区域" prop="areaName">
              <el-input v-model="form.areaName" disabled style="width:160px"/>
              <el-button type="primary" style="margin-left:6px" @click="openSelectArea">选择</el-button>
            </el-form-item>
            <el-form-item label="责任部门" prop="departmentName">
              <el-input v-model="form.departmentName" disabled style="width:160px"/>
              <el-button type="primary" style="margin-left:6px" @click="openSelectDepartment">选择</el-button>
            </el-form-item>
            <el-form-item label="责任人" prop="personInChargeName">
              <el-input v-model="form.personInChargeName" disabled style="width:160px"/>
              <el-button type="primary" style="margin-left:6px" @click="openSelectUser">选择</el-button>
            </el-form-item>
            <el-form-item label="说明" prop="desc">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.desc"
                class="filter-item"
              />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14">
          <relative-map
            v-if="crudCU"
            ref="relativeMap"
            v-model="mapData"
            :drawShow=true
            :buildFloor="buildFloor"
            drawMode="Point"
          />
        </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 :selectable="checkboxT" type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in patrolObjectTableOptions"
        :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">
          <span v-if="item.prop == 'shapeType'">
            {{ shapeOptions.find(t => t.value === scope.row.shapeType).label }}
          </span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'patrolObject:edit', 'patrolObject:del'])"
        label="操作"
        width="200"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div style="display:flex;">
            <el-button type="primary" size="mini" @click="openPatrolItem(scope.row)" style="margin-right:5px">巡检项目</el-button>
            <udOperation :data="scope.row" :permission="permission" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { getOptions } from '@/api/patrolManage/options'
import DateRangePicker from '@/components/DateRangePicker'
import crudPatrolObject from '@/api/patrolManage/patrolObject'
import { patrolObjectTableOptions } from '../tableConfig'
// import RelativeMap from './RelativeMap'
import patrolItem from './item'
import selectUser from '@/views/common/selectUser'
import selectArea from '@/views/common/selectArea'
import selectDepartment from '@/views/common/selectDepartment'
import RelativeMap from '@/components/RelativeMap'
import { initData } from '@/api/data'
import BatchMap from "@/views/common/batchMap";

const defaultForm = {
  //主要参数
  id: 0,
  name: '',
  code: '',
  type: 0,
  typeStr: '',

  areaId: 0,
  areaName:'',

  departmentId: 0,
  departmentName: '',

  personInChargeId: 0,
  personInChargeName: '',

  desc:'',
  locationJson: '',
  
  buildId:'',
  buildName: '',
  floorNo:0,
  floorStr: '',
  points:[],
  location: {
    x: 0,
    y: 0,
    buildId: '',
    floorNo: 0
  },
}
export default {
  name: 'patrolObject',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    DateRangePicker,
    RelativeMap,
    patrolItem,
    selectArea,
    selectDepartment,
    selectUser,
    BatchMap
  },
  cruds() {
    return CRUD({
      title: '巡检对象',
      url: 'patrol/object/getList',
      crudMethod: { ...crudPatrolObject },
      optShow: { add: true, edit: true, del: true, reset: true, import: true, export: true, draw:true },
    })
  },
  data() {
    return {
      mapData:[],
      buildFloor:{},
      permission: {
        add: ['admin', 'patrolObject:add'],
        edit: ['admin', 'patrolObject:edit'],
        del: ['admin', 'patrolObject:del']
      },
      patrolObjectTableOptions,
      rules: {
        name: [{ required: true, message: '请输入巡检对象名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入巡检对象编号', trigger: 'blur' }],
      },
      shapeOptions: [
        // { label: '图片', value: 0, shapeType: 'image', mode: 'Point', max: 1, min: 1 },
        { label: '点', value: 2, shapeType: 'point', mode: 'Point', max: 1, min: 1 },
        // { label: '线', value: 3, shapeType: 'line', mode: 'LineString', max: 999, min: 2 },
        // // { label: '三角形', value: 4, shapeType: 'triangle', mode: 'Polygon', max: 3, min: 3 },
        // { label: '矩形', value: 5, shapeType: 'rectangle', mode: 'Rectangle', max: 4, min: 4 },
        // // { label: '正方形', value: 6, shapeType: 'square', mode: 'Rectangle', max: 4, min: 4 },
        // { label: '圆形', value: 7, shapeType: 'round', mode: 'Circle', max: 1, min: 1 },
        // { label: '多边形', value: 8, shapeType: 'polygon', mode: 'Polygon', max: 999, min: 3 }
      ],
      drawToolOption: [
        'Point',
        // 'LineString',
        // 'Polygon',
        // 'Circle',
        // 'Ellipse',
        // 'Rectangle',
        // 'FreeHandLineString',
        // 'FreeHandPolygon'
      ],
      departmentOptions: [],
      areaOptions: [],
      optionsObj: {
        Build: [],
        // FloorNo: [],
      },
      patrolItem:false,
    }
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    }
  },
  created() {
    this.getOptions()
    this.getDeptOptions()
    this.getAreaOptions()
  },
  watch:{
    mapData(newValue, oldValue) {
      this.form.points = this.mapData[0].geometries[0].points
      this.form.locationJson = JSON.stringify(this.form.points)
    },
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.beforeToAdd](crud, form) {
      if (!crud.query.layerID) {
        this.$message.warning('请先选择类型！')
        return false
      } else {
        form.type = crud.query.layerID
      }
    },
    [CRUD.HOOK.beforeToEdit]() {
      const point = {
        x:this.form.location.x,
        y:this.form.location.y,
      }
      this.mapData = [
        {
          buildId: this.form.buildId,
          floorNo: this.form.floorNo,
          geometries: [
            {
              type: 'Point',
              points: [point]
            },
          ],
        },
      ]
      // 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 == 1
      ) {
        this.form.buildId = this.mapData[0].buildId
        this.form.floorNo = this.mapData[0].floorNo
        this.form.location.x = this.mapData[0].geometries[0].points[0].x
        this.form.location.y = this.mapData[0].geometries[0].points[0].y
        this.form.location.buildId = this.mapData[0].buildId
        this.form.location.floorNo = this.mapData[0].floorNo
      } else {
        this.$message.error('请绘制正确的围栏图形')
        return false
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {

    },
    checkboxT(row, rowIndex) {
      return true
      // return row.id !== this.userInfo.id
    },
    openSelectArea(){
      this.$refs.selectArea.openOrClose = true
    },
    openSelectDepartment(){
      this.$refs.selectDepartment.openOrClose = true
    },
    openSelectUser(){
      this.$refs.selectUser.openOrClose = true
    },
    openPatrolItem(row){
      this.patrolItem = true
      setTimeout(() => {
        // console.log(this.$refs.patrolItems);
        this.$refs.patrolItems.objectId = row.id
        this.$refs.patrolItems.objectName = row.name
        this.$refs.patrolItems.objectTypeId = row.type
      }, 100);
    },
    backShow(){
      this.form.locationJson = this.mapData[0].geometries[0].points
    },
    async getDeptOptions(){
      try {
          let res = await initData('system/options/getDepartmentOptions')
          if (res.code === 20000) this.departmentOptions = res.data.content
          console.log(res);
        } catch (error) {
          console.log(error)
        }
    },
    async getAreaOptions(){
      try {
          let res = await initData('positioning/area/getListJson',{"buildId": this.optionsObj.Build.BuildId})
          if (res.code === 20000) res.data.content.forEach((a)=>{
            this.areaOptions.push({
              'label':a.areaName,'value':a.id
            })
          })
          console.log(res);
          console.log(this.areaOptions);
        } catch (error) {
          console.log(error)
        }
    },
    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)
        }
      })
    },
    //弹窗数据同步
    selectPersonInCharge(list){
      // console.log(list)
      this.form.personInChargeId = list[0].id
      this.form.personInChargeName = list[0].name
    },
    selectDepartmentInCharge(list){
      // console.log(list)
      this.form.departmentId = list[0].id
      this.form.departmentName = list[0].departmentName
    },
    selectArea(list){
      // console.log(list)
      this.form.areaId = list[0].id
      this.form.areaName = list[0].areaName
    },
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
