<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"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission"></crudOperation>
    </div>
    <!--批量地图-->
    <!-- <batch-map title="批量标注地图" ref="batchMap" dataType="patrolLabel" :crudDraw="crud" width="70%"/> -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelDr"
      :visible="crud.status.dr > 0"
      title="批量绘制"
      width="1350px"
    >
      <el-row>
        <el-col :span="13">
          <relative-map
            ref="batchMap"
            v-model="batchMapData"
            :buildFloor=buildFloor
            :drawShow=true
            drawMode="Polygon"
            width="60%"
            height="60%"
          />
        </el-col>
        <el-col :span="1">
          <el-button type="text" @click="saveDraw()">保存</el-button> 
        </el-col>
        <el-col :span="10">
          <batch-handle-label ref="batchLabelList" @getData="syncDataLabelAndMap"/>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeBatchMap()">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 大图 -->
    <el-dialog width="800" :visible.sync="dialogVisible">
      <img width="100%" height="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible="crud.status.cu > 0"
      :title="crud.status.title"
      width="950px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-row>
          <div class="info-title">
            <div></div>
            <span>基本信息：</span> 
          </div>
          <el-col :span="8">
            <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="name">
              <el-input 
              v-model="form.name"
              size="small"
              class="filter-item" />
            </el-form-item>
            <!-- <el-form-item label="所属位置" prop="location">
              <el-input 
              v-model="form.location"
              size="small"
              class="filter-item" />
            </el-form-item> -->
            <el-form-item label="描述" prop="description">
              <el-input 
              v-model="form.description"
              size="small"
              class="filter-item" />
            </el-form-item>
            <div class="info-title">
              <div></div>
              <span>定位方式：</span> 
            </div>
            <el-form-item label="定位围栏" prop="Rail">
              <el-input 
              v-model="form.Rail"
              placeholder="绘制图形后自动填充"
              size="small"
              class="filter-item"
              disabled/>
            </el-form-item>
            <el-form-item label="NFC卡号" prop="nfcCode">
              <el-input 
              v-model="form.nfcCode"
              size="small"
              class="filter-item" />
            </el-form-item>
            <el-form-item label="RFID卡号" prop="rfidCode">
              <el-input 
              v-model="form.rfidCode"
              size="small"
              class="filter-item" />
            </el-form-item>
            <el-form-item label="QR编码" prop="qrCode">
              <el-input 
              v-model="form.qrCode"
              size="small"
              class="filter-item" />
            </el-form-item>
            <el-form-item label="Bar编码" prop="barCode">
              <el-input 
              v-model="form.barCode"
              size="small"
              class="filter-item" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <relative-map
              v-if="crudCU"
              ref="relativeMap"
              :drawShow=true
              v-model="mapData"
              drawMode="Polygon"
              width="60%"
            />
          </el-col>
        </el-row>
      </el-form>
      <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 patrolLabelTableOptions"
        :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', 'patrolLabel:edit', 'patrolLabel: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 crudPatrolLabel from '@/api/patrolManage/patrolLabel'
import { getOptions } from '@/api/system/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 { patrolLabelTableOptions } from '../tableConfig'
import { getToken } from '@/utils/auth'
import { initData } from '@/api/data'
import RelativeMap from '@/components/RelativeMap'
import batchHandleLabel from './batchHandleLabel.vue'
import BatchMap from "@/views/common/batchMap";

const defaultForm = {
  id: null,
  code: '',
  name: '',
  description: '',

  buildId: "",
  buildName: "",
  floorNo: 0,
  floorStr: "",
  extent: {
    buildId: "",
    floor: [],
    points: []
  },

  nfcCode: '',
  rfidCode: '',
  qrCode: '',
  barCode:'',
  
  location:'',
  GPSRail: '',
  Rail: '',
  scenePicUrl:[],
}

export default {
  name: 'PatrolLabel',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {...crudComps, DateRangePicker,RelativeMap,batchHandleLabel,BatchMap },
  cruds() {
    return CRUD({
      title: '巡检标签',
      url: 'patrol/label/getList',
      listOrder: [],
      crudMethod: { ...crudPatrolLabel },
      optShow: { add: true, edit: true, del: true, reset: true, import: true, export: true , draw:true},
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
  },
  data() {
    return {
      mapData: [],
      batchMapData: [],
      buildFloor:{},
      patrolLabelTableOptions,
      viewLoading: false,
      permission: {
        add: ['admin', 'patrolLabel : add'],
        edit: ['admin', 'patrolLabel : edit'],
        del: ['admin', 'patrolLabel : del'],
        draw: ['admin', 'patrolLabel : draw'],
      },
      rules: {
        code: [{ required: true, message: '请输入标签编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
      },
      token: getToken() ?? '',
      dialogVisible: false,
      dialogImageUrl:'',
      innerVisible:false,
    }
  },
  created() {

  },
  watch:{
    batchMapData(newValue, oldValue) {
      // this.form.Rail = JSON.stringify(this.batchMapData[0].geometries[0])
      this.buildFloor = {
        buildId: this.batchMapData[0].buildId,
        floorNo: this.batchMapData[0].floorNo,
      }
      this.form.extent.points = this.batchMapData[0].geometries[0].points
      console.log(this.form.extent.points);
    },
  },
  methods: {
    //验证前处理
    [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.mapData[0].geometries[0].points.pop()
        this.form.buildId = this.mapData[0].buildId
        this.form.floorNo = this.mapData[0].floorNo
        this.form.extent.buildId = this.mapData[0].buildId
        this.form.extent.points = this.mapData[0].geometries[0].points
      } 
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {



    },
    [CRUD.HOOK.beforeToAdd]() {
      this.mapData = []
    },
    [CRUD.HOOK.beforeToEdit]() {
      this.form.Rail = JSON.stringify(this.form.extent.points)
      this.mapData = [
        {
          buildId: this.form.buildId,
          floorNo: this.form.floorNo,
          geometries: [
            {
              type: 'Polygon',
              points: this.form.extent.points,
            },
          ],
        },
      ]
    },
    beforeUpload(file) {
      console.log(file)
      if (file.size > 1024 * 1024 * 5) {
        this.$message.warning('文件最大限制为 5MB')
        return false
      }
      let fileName = file.name

      let fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
      console.log(fileExtension)
      const whiteList = ['jpg', 'jpeg', 'gif', 'png']
      if (!whiteList.includes(fileExtension)) {
        this.$message.warning(`只能上传扩展名为 ${whiteList.join(' / ')} 的文件`)
        return false
      }
    },
    handleSuccess(res, file, fileList) {
      console.log(fileList);
      if (res.code === 20000) {
        this.form.scenePicUrl = []
        for (let i = 0; i < fileList.length; i++) {
          const f = fileList[i];
          this.form.scenePicUrl.push(f.response.data.path)
        }
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.form.scenePicUrl = []
      for (let i = 0; i < fileList.length; i++) {
        const f = fileList[i];
        this.form.scenePicUrl.push(f.response.data)
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    openBatchMap(){
      // this.$refs.batchMap.openOrClose = true
      this.innerVisible = true
    },
    syncDataLabelAndMap(datas){
      console.log(datas);
      if (datas.reset) {
        this.batchMapData = []
      }else{
        this.batchMapData = [
          {
            buildId: datas.buildId,
            floorNo: datas.floorNo,
            geometries: [
              {
                type: 'Polygon',
                points: datas.points,
              },
            ],
          },
        ] 
      }
      //同步数据至当前form，用于后续提交
      console.log(this.batchMapData);
    },
    saveDraw(){
      //提交修改
      console.log(this.form.extent.points);
    },
    closeBatchMap(){
      // console.log(this.$refs.batchMap);
      // console.log(value);
      // if (this.$refs.batchMap.map) this.$refs.batchMap.map.remove()
      this.crud.cancelDr()
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .info-title {display: flex;margin-left: 0px;margin-bottom: 10px;}
::v-deep .info-title div{width: 4px; height: 15px;background: blue;margin-right: 8px;}
::v-deep .info-title span{font-size: 14px;font-weight: bold;}
</style>
