<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['dataQuery:windTowerStatusInfo:add']"
          >新增
          </el-button>
        </el-col>
        <!--        <el-col :span="1.5">-->
        <!--          <el-button-->
        <!--            type="warning"-->
        <!--            plain-->
        <!--            icon="el-icon-download"-->
        <!--            size="mini"-->
        <!--            :on-change="handleExport"-->
        <!--            v-hasPermi="['dataQuery:windTowerStatusInfo:export']"-->
        <!--          >导出-->
        <!--          </el-button>-->
        <!--        </el-col>-->
        <!--        <el-upload-->
        <!--          action="http://localhost:9090/dataQuery/upload/uploads/"-->
        <!--          multiple-->
        <!--          :limit="10"-->
        <!--          ref="upload">-->
        <!--        -->

        <!--        </el-upload>-->
        <!--        <el-button size="mini" type="primary"  @click="dialogVisible = true" plain>文件上传</el-button>-->
        <!--        <el-dialog-->
        <!--          title="文件上传"-->
        <!--          :visible.sync="dialogVisible"-->
        <!--          width="30%"-->
        <!--          :close-on-click-modal = 'false'>-->

        <!--            <div class="uploadDiv">-->
        <!--              <span class="uploadText">测风塔：</span>-->
        <!--              <el-select  v-model="cftId" placeholder="请选择">-->
        <!--                <el-option-->
        <!--                  v-for="item in cftData"-->
        <!--                  :key="item.equipmentNo"-->
        <!--                  :label="item.name"-->
        <!--                  :value="item.equipmentNo"-->
        <!--                  >-->
        <!--                </el-option>-->
        <!--              </el-select>-->

        <!--              <el-upload-->
        <!--                ref="upload"-->
        <!--                name="file"-->
        <!--                align="left"-->
        <!--                :http-request="this.dataUpload"-->
        <!--                class="upload-demo"-->
        <!--                action=""-->
        <!--                multiple-->
        <!--              >-->
        <!--                <el-button size="small" type="primary" >点击上传</el-button>-->
        <!--              </el-upload>-->
        <!--            </div>-->


        <!--          <span slot="footer" class="dialog-footer">-->
        <!--      <el-button @click="dialogVisible = false">取 消</el-button>-->
        <!--      <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
        <!--  </span>-->
        <!--        </el-dialog>-->

      </el-row>

      <el-table v-loading="loading" border
                :data="tableAllData.slice((page.currentPage-1)*page.pageSize,page.currentPage*page.pageSize)">
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column label="名称" align="center" prop="name"/>
<!--        <el-table-column label="所属项目" align="center" prop="projectId" :formatter="formatProjectId"/>-->
<!--        <el-table-column label="型号" align="center" prop="modelNumber"/>-->
        <el-table-column label="设备编号" align="center" prop="equipmentNo"/>
        <el-table-column label="记录仪编号" align="center" prop="recorderNo"/>
        <!--<el-table-column label="测风塔层高" align="center" prop="heights"/>-->
<!--        <el-table-column label="数据密码" align="center" prop="password"/>-->
        <el-table-column label="安装时间" align="center" prop="installationTime" width="180">
          <template slot-scope="scope">
            <span>{{ dateFormat(scope.row.installationTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="制造商" align="center" prop="manufacturer"/>
        <el-table-column label="经度" align="center" prop="longitude"/>
        <el-table-column label="纬度" align="center" prop="latitude"/>
        <el-table-column label="状态" align="center" prop="status" :formatter="formatStatus"/>
        <el-table-column label="首页展示层" align="center" prop="displayHeight" :formatter="formatHeight"/>
        <el-table-column label="海拔" align="center" prop="altitude"/>
        <el-table-column label="地形复杂程度" align="center" prop="terrainComplexity"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['dataQuery:windTowerStatusInfo:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['dataQuery:windTowerStatusInfo:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page=page.currentPage
          :page-sizes="[10, 15, 30, 50]"
          :page-size=page.pageSize
          layout="total, sizes, prev, pager, next, jumper"
          :total=page.total>
        </el-pagination>
      </div>

      <!--<pagination-->
      <!--v-show="total>0"-->
      <!--:total="total"-->
      <!--:page.sync="queryParams.pageNum"-->
      <!--:limit.sync="queryParams.pageSize"-->
      <!--@pagination="getList"-->
      <!--/>-->
    </el-card>
    <!-- 添加或修改测风塔信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="equipmentNo">
              <el-input v-model="form.equipmentNo" placeholder="请输入设备编号" :disabled="equipmentNoDisable"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mb8">
<!--          <el-col :span="12">-->
<!--            <el-form-item label="所属项目" prop="projectId">-->
<!--              <el-select v-model="form.projectId" placeholder="请选择所属项目" style="width: 100%" clearable>-->
<!--                <el-option-->
<!--                  v-for="(item,index) in projectInfo"-->
<!--                  :key="index"-->
<!--                  :label="item.projectName"-->
<!--                  :value="item.id">-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col> -->
          <el-col :span="12">
            <el-form-item label="记录仪编号" prop="recorderNo">
              <el-input v-model="form.recorderNo" placeholder="请输入记录仪编号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-form-item label="数据密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="modelNumber">
              <el-input v-model="form.modelNumber" placeholder="请输入型号"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-form-item label="安装时间" prop="installationTime">
              <el-date-picker clearable style="width: 100%"
                              v-model="form.installationTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择安装时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请填写制造商"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-form-item label="海拔" prop="altitude">
              <el-input v-model="form.altitude" placeholder="请输入海拔"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地形复杂程度" prop="terrainComplexity">
              <el-select v-model="form.terrainComplexity" placeholder="请选择" style="width: 100%" clearable>
                <el-option
                  v-for="item in terrain"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mb8">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" style="width: 100%" clearable>
                <el-option
                  v-for="item in statusOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首页展示层高" prop="displayHeight">
              <el-select v-model="form.displayHeight" placeholder="请选择" style="width: 100%" clearable>
                <el-option
                  v-for="(item,index) in heightOption"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWindTowerStatusInfo,
  getWindTowerStatusInfo,
  delWindTowerStatusInfo,
  addWindTowerStatusInfo,
  updateWindTowerStatusInfo,
  listAllInfo,
  FileUpload
} from "@/api/biz/dataQuery/windTowerStatusInfo";
import defaultOption from "@/api/biz/dataQuery/defaultOption";
import {listAll} from "@/api/biz/dataQuery/project";
import {getPointMap} from "@/api/biz/dataQuery/largeScreenPage";
export default {
  name: "WindTowerStatusInfo",
  data() {
    const checkName = (rule, value, callback) => {
      var s6 = this.tableAllData
      if (value == null || value === '') {
        callback(new Error('请填写测风塔名称'))
      }
      for (let i = 0; i < s6.length; i++) {
        if (this.modId == '') {
          // 新增
          if ((value == s6[i].name)) {
            callback(new Error('名称不能重复'))
          }
        } else {
          // 修改
          if (this.modId != s6[i].id) {
            if ((value == s6[i].name)) {
              callback(new Error('名称不能重复'))
            }
          }
        }
      }
      callback()
    }
    const checkEquipmentNo = (rule, value, callback) => {
      var s6 = this.tableAllData
      if (value == null || value === '') {
        callback(new Error('请填写设备编号'))
      }
      for (let i = 0; i < s6.length; i++) {
        if (this.modId == '') {
          // 新增
          if ((value == s6[i].equipmentNo)) {
            callback(new Error('设备编号不能重复'))
          }
        } else {
          // 修改
          if (this.modId != s6[i].id) {
            if ((value == s6[i].equipmentNo)) {
              callback(new Error('设备编号不能重复'))
            }
          }
        }
      }
      callback()
    }
    const checkRecorderNo = (rule, value, callback) => {
      var s6 = this.tableAllData
      if (value == null || value === '') {
        callback(new Error('请填写记录仪编号名称'))
      }
      for (let i = 0; i < s6.length; i++) {
        if (this.modId == '') {
          // 新增
          if ((value == s6[i].recorderNo)) {
            callback(new Error('记录仪编号不能重复'))
          }
        } else {
          // 修改
          if (this.modId != s6[i].id) {
            if ((value == s6[i].recorderNo)) {
              callback(new Error('记录仪编号不能重复'))
            }
          }
        }
      }
      callback()
    }
    const reg = /^[\-\+]?(0?\d{1,2}(\.\d{1,9})*|1[0-7]?\d{1}(\.\d{1,9})*|180(\.0{1,9})*)$/
    const reg1 = /^[\-\+]?([0-8]?\d{1}(\.\d{1,9})*|90(\.0{1,9})*)$/
    const checkLongitude = (rule, value, callback) => {
      if (!value) {
        callback(new Error('不许为空'))
      }
      if (reg.test(value) == false) {
        callback(new Error('请输入正确经度'));
      } else {
        callback()
      }
    }
    const checkLatitude = (rule, value, callback) => {
      if (!value) {
        callback(new Error('不许为空'))
      }
      if (reg1.test(value) == false) {
        callback(new Error('请输入正确纬度'));
      } else {
        callback()
      }
    }
    return {
      //
      dialogVisible: false,
      equipmentNoDisable: false,
      //文件上传
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测风塔信息表格数据
      windTowerStatusInfoList: [],
      tableAllData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        modelNumber: null,
        equipmentNo: null,
        installationTime: null,
        manufacturer: null,
        longitude: null,
        latitude: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{required: true, validator: checkName, trigger: 'blur'}],
        equipmentNo: [{required: true, validator: checkEquipmentNo, trigger: 'blur'}],
        recorderNo: [{required: true, validator: checkRecorderNo, trigger: 'blur'}],
        // modelNumber: [{required: true,  message:'请输入型号', trigger: 'blur'}],
        longitude: [{required: true, validator: checkLongitude, trigger: 'blur'}],
        latitude: [{required: true, validator: checkLatitude, trigger: 'blur'}],
        password: [{required: true, message: '请输入数据密码', trigger: 'blur'}],
      },
      modId: '',
      cftData: [],
      cftId: '',
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      terrain: [{label: "平坦地形", value: "平坦地形"},
        {label: "隆升地形", value: "隆升地形"},
        {label: "低凹地形", value: "低凹地形"}],
      statusOption:[{label: "停机", value: "0"},
        {label: "运行", value: "1"}],
      heightOption:[],
      projectInfo:[]
    };
  },
  created() {
    this.getList();
    this.heightOption=defaultOption.allHeightOptions
  },
  mounted() {
    this.getProjectInfo()
  },
  methods: {
    /*项目信息*/
    getProjectInfo(){
      listAll().then(res=>{
        this.projectInfo = res.rows
        this.getAllWindTowerInfo()
      }).catch(err=>{
        console.log('获取项目信息异常：'+err)
        this.$message.error('获取项目信息异常：'+err)
      })
    },
    /*获取所有的测风塔*/
    getAllWindTowerInfo() {
      listAllInfo().then(res => {
        this.cftId = res.rows[0].equipmentNo
        this.cftData = res.rows
      }).catch(err => {
        this.$message.error('查询测风塔异常：' + err)
        console.log('查询测风塔异常：' + err)
      })
    },
    //文件上传
    dataUpload(item) {
      this.fullscreenLoading = true
      const formData = new FormData()
      formData.append('file', item.file)
      formData.append('eqId', this.cftId)

      FileUpload(formData).then((response) => {
        this.fullscreenLoading = false
        this.$message.success("上传文件成功")
      }).catch((error) => {
        this.$message.error("上传文件失败" + error)
      })
    },
    /** 查询测风塔信息列表 */
    getList() {
      this.loading = true;
      listAllInfo().then(res => {
        console.log(res.rows)
        this.tableAllData = res.rows
        this.page.total = res.rows.length;
        this.loading = false;
      })
      // listWindTowerStatusInfo(this.queryParams).then(response => {
      //   this.tableAllData = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },
    /*条件查询*/
    listWindTowerStatusInfo(){

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        modelNumber: null,
        equipmentNo: null,
        recorderNo: null,
        installationTime: null,
        manufacturer: null,
        longitude: null,
        latitude: null,
        password: null,
        altitude: null,
        terrainComplexity: null,
        projectId: null,
        status:'1',
        displayHeight:""
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.modId = ''
      this.open = true;
      this.equipmentNoDisable = false
      this.title = "添加测风塔信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.equipmentNoDisable = true
      this.reset();
      const id = row.id || this.ids
      this.modId = id
      this.form = {
        id: row.id,
        name: row.name,
        modelNumber: row.modelNumber,
        heights: row.heights,
        password: row.password,
        equipmentNo: row.equipmentNo,
        recorderNo: row.recorderNo,
        installationTime: row.installationTime,
        manufacturer: row.manufacturer,
        longitude: row.longitude,
        latitude: row.latitude,
        altitude: row.altitude,
        terrainComplexity: row.terrainComplexity,
        status:row.status,
        displayHeight:row.displayHeight,
        projectId:row.projectId
      };
      /*动态显示层高*/
      // console.log(row.heights)
      if(row.heights !== null){
        let heights = row.heights.split(',')
        this.heightOption = []
        for(let height of heights){
          this.heightOption.push({value:height,label:height+'m'})
        }
      }else{
        this.heightOption=defaultOption.allHeightOptions
      }
      this.open = true;
      this.title = "修改测风塔信息";
    },
    /** 提交按钮 */
    submitForm() {
      // this.form.heights = this.form.heights.toString()
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWindTowerStatusInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getPoint()
            });
          } else {
            addWindTowerStatusInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getPoint()
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除测风塔信息名称为"' + row.name + '"信息及所有数据？').then(function () {
        return delWindTowerStatusInfo(ids);
      }).then(() => {
        this.getList();
        this.getPoint()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dataQuery/windTowerStatusInfo/export', {
        ...this.queryParams
      }, `windTowerStatusInfo_${new Date().getTime()}.xlsx`)
    },
    /**上传按钮操作*/
    // handleChange(file) {
    //   // console.log(file)
    //   this.uploadFile = file.raw
    //   // console.log(this.uploadFile)
    //   if (this.uploadFile) {
    //     const form = new FormData()
    //     form.append('file', this.uploadFile, this.uploadFile.name)
    //     console.log(form)
    //     FileUpload(form).then(res => {
    //       if (res.code === 200) {
    //         console.log(res)
    //       }
    //     })
    //   }
    // },
    /*pageSize改变*/
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.currentPage = 1
    },
    /*currentPage改变*/
    handleCurrentChange(val) {
      this.page.currentPage = val
    },
    /**
     * 日期格式化
     */
    dateFormat(date) {
      if (date != null) {
        let formatDate = new Date(date)
        let format = 'yyyy-MM-dd';
        let year = formatDate.getFullYear() + "-"
        let startMonth = formatDate.getMonth() + 1
        let month = startMonth < 10 ? '0' + startMonth : startMonth
        let day = formatDate.getDate() < 10 ? '0' + formatDate.getDate() : formatDate.getDate()
        return year + month + "-" + day;
      } else {
        return date
      }

    },
    getPoint(){
      getPointMap().then(res => {
        sessionStorage.setItem("allPointInfo", JSON.stringify({info: this.allPointInfo}))
        this.$store.dispatch('equipmentInfo/allPointInfo', JSON.stringify({info: this.allPointInfo}))
      }).catch(err => {
        console.log('所有点位坐标：' + err)
      })
    },
    formatStatus(row){
      let option = this.statusOption.find(w=>w.value === row.status)
      return option !==undefined?option.label:row.status
    },
    formatHeight(row){
      let option = this.heightOption.find(w=>w.value === row.displayHeight)
      return option !==undefined?option.label:row.displayHeight
    },
    formatProjectId(row){
      let option = this.projectInfo.find(w=>w.id === row.projectId)
      return option !==undefined?option.projectName:row.projectName
    }
  }
};
</script>
<style scoped>
.uploadDiv {
  display: flex;
  justify-content: flex-start;
}

.uploadText {
  font-size: 18px;
  padding: .5%;
}

.upload-demo {
  padding: .5%;
}
</style>
