<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="设备名称：">
          <el-input
            type="text"
            clearable
            v-model="search.deviceName"
          ></el-input>
        </el-form-item>
        <el-form-item label="过期时间：">
          <el-date-picker
            clearable
            v-model="search.time"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="initList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="doAdd(1)">
            新增</el-button
          >
          <!-- <el-button type="primary" class="el-icon-upload2"> 导入</el-button> -->
          <!-- <el-button type="primary" class="el-icon-download"> 导出</el-button> -->
          <el-button
            type="primary"
            class="el-icon-delete"
            @click="doBatchDelete"
          >
            删除</el-button
          >
        </div>
        <div>
          <right-toolbar
            @queryTable="initList"
            :search="true"
            @update:showSearch="isSearch = !isSearch"
          ></right-toolbar>
        </div>
      </div>

      <el-table
        :data="list"
        height="calc(100% - 200px)"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="80" />
        <el-table-column label="序号" align="center" width="100">
          <template slot-scope="scope">
            <span> {{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="工程车编号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deviceCode || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工程车名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deviceName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工程车状态" align="center">
          <template slot-scope="scope">
            <span>{{ initStatus(scope.row.status) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工程车类型" align="center">
          <template slot-scope="scope">
            <span>{{ initDevice(scope.row.deviceType) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入场时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.expirationDate || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" align="center" width="120">
          <template #default="{ row }">
            <el-button type="text" size="mini" @click="doAdd(2, row)">
              编辑
            </el-button>
            <el-button type="text" size="mini" @click="doDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="initList"
      />
    </el-main>

    <!-- 新增/编辑 的dialog -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="700px"
      :title="isEdit"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="工程车名称：" prop="deviceName">
          <el-input
            type="text"
            v-model="ruleForm.deviceName"
            style="width: 70%"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="设备编号：" prop="deviceCode">
          <el-input
            type="text"
            v-model="ruleForm.deviceCode"
            style="width: 70%"
            clearable
          ></el-input>
        </el-form-item> -->
        <el-form-item label="工程车状态：" prop="status">
          <el-select v-model="ruleForm.status" style="width: 70%" clearable>
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in statusOption"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经纬度：" prop="areaCode">
          <el-button type="primary" @click="openMapAddressDialog">
            地图选址
          </el-button>
        </el-form-item>
        <el-form-item label="经度：" prop="longitude" v-if="ruleForm.longitude">
          <el-input
            v-model="ruleForm.longitude"
            disabled
            maxlength="100"
            style="width: 70%"
          ></el-input>
        </el-form-item>
        <el-form-item label="纬度：" prop="latitude" v-if="ruleForm.latitude">
          <el-input
            v-model="ruleForm.latitude"
            disabled
            maxlength="100"
            style="width: 70%"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备类型：" prop="deviceType">
          <el-select v-model="ruleForm.deviceType" style="width: 70%" clearable>
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in deviceOption"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入场时间：">
          <el-date-picker
            v-model="ruleForm.expirationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            style="width: 70%"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图标：" ref="loadFlag">
          <el-upload
            :before-upload="beforeUpload"
            ref="uploadRef"
            action="#"
            list-type="picture-card"
            :http-request="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="ruleForm.imgFileList"
            :on-change="handleChange"
            accept=".jpg,.jpeg,.png,.gif,.tif,.bmp,.svg,.jpg,"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogLookImg" v-if="dialogLookImg">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog
      v-if="mapDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="地图选址"
      width="90%"
      :visible.sync="mapDialogVisible"
    >
      <mapDialog
         :ruleForm="ruleForm"
        @setPosition="setPosition"
        @setAddress="setAddress"
        @closeMapaddressDialog="closeMapaddressDialog"
      ></mapDialog>
    </el-dialog>
  </el-container>
</template>

<script>
import mapDialog from '../risk/map'

import {
  deviceList,
  areaTree,
  deptTree,
  saveDevice,
  editDevice,
  delDevice,
  upload,
  deviceDetail
} from '@/api/risk/facility.js'
export default {
  name: 'RuoyiControlObject',
  components: {
    mapDialog
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,

      mapDialogVisible: false,

      isSearch: false, //控制搜索框是否显示
      search: {
        deviceName: '',
        time: ''
      },
      areaTreeList: [], // 所属区域列表
      loaderList: [], //区域负责人
      list: [],
      treeList: [],
      deptTreeList: [], // 所属部门的树形
      total: 1,
      pageNum: 1,
      pageSize: 10,
      ansUrl: require("@/assets/images/dingwei.png"),
      multipleSelectionIdList: [], // 删除需要的参数

      dialogVisible: false, //新增/修改的dialog
      isEdit: '',
      ruleForm: {
        deviceName: '',
        deviceType: '',
        expirationDate: '',
        status: '',
        longitude: '',
        latitude: '',
        imgFileList: [],
        deviceImg: ''
      },
      imgFileList: 'imgFileList',
      dialogImageUrl: '',
      dialogLookImg: '',
      // 图片的限制格式
      whiteList: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'bmp', 'svg', 'jpg'],
      deviceOption: [
        { label: '视频监控', value: 1 },
        { label: '应急物资', value: 2 },
        { label: '安全仪表', value: 3 },
        { label: '安全阀', value: 4 },
        { label: '可燃有毒气体检测报警器', value: 5 },
        { label: '特种设备', value: 6 },
        { label: '消防设施', value: 7 },
        { label: '其他', value: 8 }
      ],
      statusOption: [
        { label: '启动', value: 0 },
        { label: '停用', value: 1 },
        { label: '保养', value: 2 },
        { label: '保障', value: 3 },
        { label: '维修', value: 4 },
        { label: '报废', value: 5 }
      ],
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        deviceType: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择设备状态', trigger: 'change' }
        ],
        expirationDate: [
          { required: true, message: '请选择过期时间', trigger: 'change' }
        ],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }]
      }
    }
  },

  mounted() {
    this.initList() // 列表初始化
    this.initAreaTree() // 所属区域跟区域负责人的下拉内容
    this.initDeptTree() // 所属部门的下拉内容
  },

  methods: {
    // 列表初始化
    initList() {
      const obj = {
        deviceName: this.search.deviceName,
        startExpirationDate: this.search.time[0] || null,
        endExpirationDate: this.search.time[1] || null
      }
      deviceList({
        ...obj,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then((res) => {
        if (res.code === 200) {
          this.list = res.rows
          this.total = res.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    initRisk(val) {
      switch (val) {
        case 1:
          return '低'
        case 2:
          return '一般'
        case 3:
          return '较大'
        case 4:
          return '重大'
      }
    },
    initTree(params) {
      params.forEach((item) => {
        this.treeList.push(item)
        if (item.childList.length > 0) {
          this.initTree(item.childList)
        }
      })
    },
    initAreaId(val) {
      return this.treeList.find((item) => item.id === val).areaName
    },
    // 设备类型初始化
    initDevice(type) {
      switch (type) {
        case 1:
          return '视频监控'
        case 2:
          return '应急物资'
        case 3:
          return '安全仪表'
        case 4:
          return '安全阀'
        case 5:
          return '可燃有毒气体检测报警器'
        case 6:
          return '特种设备'
        case 7:
          return '消防设施'
        case 8:
          return '其他'
      }
    },
    initStatus(type) {
      switch (type) {
        case 0:
          return '启动'
        case 1:
          return '停用'
        case 2:
          return '保养'
        case 3:
          return '保障'
        case 4:
          return '维修'
        case 5:
          return '报废'
      }
    },
    // 重置
    reset() {
      this.search.deviceName = ''
      this.search.time = ''
      this.initList()
    },
    // 所属区域跟区域负责人的下拉内容
    async initAreaTree() {
      const res = await areaTree()
      this.areaTreeList = res
      this.initTree(this.areaTreeList)
    },
    // 所属 部门的下拉内容
    async initDeptTree() {
      const res = await deptTree()
      this.deptTreeList = res.data
    },

    handleChange(file, fileList) {
      console.log('改变了')
      // 当上传图片成功时，即隐藏上传按钮
      if (fileList.length > 0) {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'none'
      } else {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'block'
      }
    },
    // 上传封面需要的参数
    handleRemove(file, fileList) {
      this.ruleForm.imgFileList = fileList
      this.ruleForm.deviceImg = ''
      this.dialogImageUrl = ''
      if (!fileList.length) {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'block'
        this.imgFileList = 'imgFileList'
      }
    },
    // 新增
    async doAdd(type, val) {
      if (type === 1) {
        console.log(1)
        this.ruleForm.imgFileList = []
        this.isEdit = '新增'
        this.ruleForm.deviceName = ''
        this.ruleForm.deviceType = ''
        this.ruleForm.expirationDate = ''
        this.ruleForm.status = ''
        this.ruleForm.longitude = ''
        this.ruleForm.latitude = ''
      } else {
        this.isEdit = '编辑'
        const { data: res } = await deviceDetail(val.id)
        this.ruleForm = { ...res, imgFileList: [] }
        if (res.deviceImg) {
            this.dialogImageUrl = this.baseUrl+ res.deviceImg
            this.ruleForm.imgFileList.push({
          uid: Date.now(),
          url:  this.baseUrl+ res.deviceImg,
          name: '封面'
        })
        }

      }
      this.dialogVisible = true
      this.$nextTick(()=>{
        if(this.ruleForm.imgFileList.length>0){
          this.$refs.uploadRef.$el.children[1].style.display = 'none'
        }else{
          this.$refs.uploadRef.$el.children[1].style.display = 'block'
        }
      })
    },
    // 提交
    submit() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          if (this.isEdit === '新增') {
            const obj = {
              deviceName: this.ruleForm.deviceName,
              longitude: this.ruleForm.longitude * 1,
              latitude: this.ruleForm.latitude * 1,
              deviceType: this.ruleForm.deviceType,
              expirationDate: this.ruleForm.expirationDate,
              status: this.ruleForm.status,
              deviceImg: this.ruleForm.deviceImg
            }
            const res = await saveDevice(obj)
            if (res.code !== 200) return this.$message.error(res.msg)
          } else {
        console.log(this.ruleForm.deviceImg)
            const obj = {
              deviceName: this.ruleForm.deviceName,
              longitude: this.ruleForm.longitude * 1,
              latitude: this.ruleForm.latitude * 1,
              deviceType: this.ruleForm.deviceType,
              expirationDate: this.ruleForm.expirationDate,
              status: this.ruleForm.status,
              id: this.ruleForm.id || null,
              deviceImg: this.ruleForm.deviceImg
            }
            const res = await editDevice(obj)
            if (res.code !== 200) return this.$message.error(res.msg)
          }

          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm.deviceName = ''
          this.ruleForm.longitude = ''
          this.ruleForm.latitude = ''
          this.ruleForm.deviceType = ''
          this.ruleForm.expirationDate = ''
          this.ruleForm.status = ''
          this.ruleForm.imgFileList = []
          this.dialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 全选/反选
    handleSelectionChange(val) {
      this.multipleSelectionIdList = val.map((item) => item.id)
    },
    // 删除
    doDelete(type) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delDevice(type.id)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 批量删除
    doBatchDelete() {
      if (!this.multipleSelectionIdList.length)
        return this.$message.info('请先选择需要删除的选项')
      this.$confirm('是否删除所有选中项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delDevice(this.multipleSelectionIdList.join())
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '批量删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    closeMapaddressDialog() {
      this.mapDialogVisible = false
    },
    // 获取详细地址
    setAddress(val) {
      console.log('这是 获取详细地址 val', val)
      if (val) {
        this.ruleForm.address = val
      } else {
        this.$message.warning('未定位到详细地址请手动输入')
      }
    },
    // 获取经纬度
    setPosition(val) {
      console.log('这是 获取经纬度 val', val)
      if (val.length && val.length == 2) {
        this.ruleForm.longitude = val[0]
        this.ruleForm.latitude = val[1]
      } else {
        this.$message.warning('未定位到经纬度坐标请手动输入')
      }
    },
    openMapAddressDialog() {
      console.log('这是地图选址弹窗组件打开')
      this.mapDialogVisible = true

    },
    // 封面上传格式校验
    beforeUpload(file) {
      if (file.size === 0) {
        this.$message.error('文件不能为空')
        return false
      }
      const end = file.name.split('.')[file.name.split('.').length - 1]
      if (!this.whiteList.includes(end)) {
        this.$message.error('文件格式错误')
        return false
      }
      return true
    },
    // 封面上传
    async handlePictureCardPreview(file) {
      try {
        if (!file) return this.$message.error('文件有误')
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await upload(formData)
        this.dialogImageUrl = res.fileName
        this.ruleForm.deviceImg = res.fileName
        this.$nextTick(() => {
          this.dialogVisible = true
        })
        if (res.code !== 200) {
          this.ruleForm.imgFileList = []
          return this.$message.error('文件格式不支持')
        }
        this.ruleForm.coverPhoto = res.fileName
      } catch (error) {
        this.ruleForm.imgFileList = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
