<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"
        >
          <el-option
            v-for="item in buildList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <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.single"
          clearable
          size="small"
          placeholder="是否单楼层"
          class="filter-item"
          style="width: 150px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in 2"
            :key="item"
            :label="item == '1' ? '是' : '否'"
            :value="item == '1' ? true : false"
          />
        </el-select>
        <el-select
          v-model="query.visibleInList"
          clearable
          size="small"
          placeholder="列表可见状态"
          class="filter-item"
          style="width: 150px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in 2"
            :key="item"
            :label="item == '1' ? '是' : '否'"
            :value="item == '1' ? true : false"
          />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission"></crudOperation>
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible="crud.status.cu > 0"
      :title="crud.status.title"
      width="500px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
        <el-form-item label="建筑" prop="buildId">
          <el-select
            v-model="form.buildId"
            filterable
            size="small"
            placeholder="请选择建筑"
            class="filter-item"
            style="width: 320px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in buildList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层名称" prop="name">
          <el-input v-model="form.name" style="width: 320px;" />
        </el-form-item>
        <el-form-item label="楼层序号" prop="sort">
          <el-input v-model="form.sort" style="width: 320px;" />
        </el-form-item>
        <el-form-item label="模型" prop="model">
          <el-select
            v-model="form.model"
            filterable
            size="small"
            placeholder="请选择模型"
            class="filter-item"
            style="width: 320px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in optionsObj.IocnType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单楼层" prop="single">
          <el-switch
            v-model="form.single"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否"
            :active-value="true"
            :inactive-value="false"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="楼层列表可见" prop="visibleInList">
          <el-switch
            v-model="form.visibleInList"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否"
            :active-value="true"
            :inactive-value="false"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="楼层图片上传" prop="mapPath">
          <el-upload
            class="avatar-uploader"
            :action="VUE_APP_BASE_API + '/file/uploadFile'"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-error="handleUploadError"
            :on-remove="handleUploadRemove"
            :data="{ fileModule: 1 }"
            :file-list="fileList"
            :headers="{ token }"
            accept=".jpg,.jpeg,.gif,.png"
          >
            <img v-if="form.path" :src="VUE_APP_BASE_API + form.mapPath" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传 jpg / jpeg / gif / png 文件，且不超过 5 MB
            </div>
          </el-upload>
        </el-form-item>
      </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 floorTableOptions"
        :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 == 'single'">
            {{ scope.row.single? '是' : '否' }}
          </span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'floor:edit', 'floor: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 crudFloor from '@/api/system/floor'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { getOptions } from '@/api/system/public'

// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { floorTableOptions } from '../tableConfig'
import { getToken } from '@/utils/auth'
import getters from '@/store/getters'
import { initData } from '@/api/data'

const defaultForm = {
  id: '',
  buildId: '', //建筑ID
  name:"",//建筑名称
  mapPath: '', //地图路径
  model:"",//模型名称
  modelId:"",//模型id
  noList:[{no: 0, altitude: 0}],
  single:false,
  sort:1,
  visibleInList:false
}

export default {
  name: 'Floor',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps },
  cruds() {
    return CRUD({
      title: '楼层',
      url: 'system/floor/getList',
      listOrder: [],
      crudMethod: { ...crudFloor }
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    }
  },
  data() {
    return {
      floorTableOptions,
      viewLoading: false,
      permission: {
        add: ['admin', 'floor:add'],
        edit: ['admin', 'floor:edit'],
        del: ['admin', 'floor:del']
      },
      rules: {
        buildId: [{ required: true, message: '请选择建筑Id', trigger: 'blur' }],
        name: [{ required: true, message: '请输入楼层名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入楼层序号', trigger: 'blur' }],
        // mapPath: [{ required: true, message: '请上传楼层图片', trigger: 'blur' }]
      },
      optionsObj: {
        // Build: [],
        IocnType: []
      },
      token: getToken() ?? '',
      buildList: [],
      modelList: [],
      fileList: [],
    }
  },
  created() {
    this.getOptions()
    this.getBuildData()
    // this.getModelData()
  },
  methods: {
    getOptions() {
      Object.keys(this.optionsObj).forEach(async key => {
        try {
          let res
          if (key === 'Label') {
            res = await getOptions(key, { id: null })
          } else {
            res = await getOptions(key)
          }
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    //获取弹窗内的建筑信息
    async getBuildData() {
      try {
        const res = await initData('system/build/getList', {
          PageIndex: 0,
          PageSize: 0,
        })
        const data = res.data.content
        // console.log(data);
        this.buildList = data.map((item) => {
          return {
            id: item.id,
            name: item.name,
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    //获取弹窗内的模型信息
    async getModelData() {
      try {
        const res = await initData('model/library/getList', {
          PageIndex: 0,
          PageSize: 0,
        })
        const data = res.data.content
        this.modelList = data.map((item) => {
          return {
            id: item.id,
            modelName: item.name,
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    beforeUpload(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()
      const whiteList = ['jpg', 'jpeg', 'gif', 'png']
      if (!whiteList.includes(fileExtension)) {
        this.$message.warning(`只能上传扩展名为 ${whiteList.join(' / ')} 的文件`)
        return false
      }
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 20000) {
        this.form.mapPath = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },
    handleUploadError(err, file, fileList) {
      console.log(err)
      this.$message.error('上传失败')
    },
    handleUploadRemove(file, fileList) {
      if (fileList.length == 0) {
        this.form.mapPath = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
::v-deep .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
