<template>
  <div class="app-container">
    <el-form ref="queryForm" size="small" :inline="true">
      <el-form-item label="场站名称">
        <el-input v-model="stationName" maxlength="50"/>
      </el-form-item>
      <el-form-item label="场站类型">
        <el-select v-model="electricFieldType" placeholder="请选择" clearable>
          <el-option
              v-for="item in electricFieldTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="dataQuery">查询
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <div style="padding-top: 10px">
      <vxe-table
          ref="xTable"
          align="center"
          class="mytable-style"
          auto-resize
          border
          resizable
          export-config
          highlight-current-row
          show-overflow
          max-height="700"
          :data="tableData"
          :radio-config="{trigger: 'row'}">
        <vxe-column type="radio" width="60"/>
        <vxe-table-column field="stationCode" title="场站编号"></vxe-table-column>
        <vxe-table-column field="name" title="名称"></vxe-table-column>
        <vxe-table-column field="electricFieldTypeEnum" title="类型" :formatter="electricFieldTypeFormat"></vxe-table-column>
        <vxe-table-column field="capacity" title="装机容量(MW)"></vxe-table-column>
        <vxe-table-column field="longitude" title="经度"></vxe-table-column>
        <vxe-table-column field="latitude" title="纬度"></vxe-table-column>
        <vxe-table-column field="provinceEnum" title="省份" :formatter="provinceEnumFormat"></vxe-table-column>
        <vxe-table-column field="ftpChanelId" title="ftpt通道名称" :formatter="ftpChanelIdFormat"></vxe-table-column>
        <vxe-table-column field="ftpUrl" title="ftp扫描路径"></vxe-table-column>
      </vxe-table>
      <vxe-pager
          background
          :loading="loading"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="total"
          @page-change="handlePageChange"
          :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
      </vxe-pager>
    </div>

    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="850px" height="600px">
      <el-form ref="form" :model="form" :rules="rules" width="830px" label-width="150px">
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="场站编号" prop="stationCode">
              <el-input v-model="form.stationCode" maxlength="32" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站名称" prop="name">
              <el-input style="width: 100%" v-model="form.name" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="类型" prop="electricFieldTypeEnum">
              <el-select v-model="form.electricFieldTypeEnum" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in this.electricFieldTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站装机容量(MW)" prop="capacity">
              <el-input style="width: 100%" v-model="form.capacity" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input  style="width: 100%" v-model="form.longitude" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input style="width: 100%" v-model="form.latitude" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="省份" prop="provinceEnum">
              <el-select v-model="form.provinceEnum" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in this.provinceEnumList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ftp通道名称">
              <el-select v-model="form.ftpChanelId" placeholder="请选择" style="width: 100%" clearable @change="ftpChannelChange">
                <el-option
                  v-for="item in this.ftpChannelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb4">
          <el-col :span="24">
            <el-form-item label="ftp扫描路径">
              <el-input  style="width: 100%" v-model="form.ftpUrl" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="commitChannel">确 定</el-button>
        <el-button @click="cancelChannel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  name: 'inverterinfo',
  data() {
    return {
      ftpChannelList:[],
      provinceEnumList:[],
      form: {
        stationCode: '',
        name: '',
        electricFieldTypeEnum: '',
        capacity: '',
        longitude: '',
        latitude: '',
        provinceEnum: '',
        ftpChanelId: '',
        ftpUrl: '',
      },
      title: "",
      // 是否显示弹出层
      open: false,
      edit: false,
      total: 0,
      sortOrder: 'asc',
      pageSize: 10,
      currentPage: 1,
      stationList: [],
      electricFieldType: undefined,
      stationName: undefined,
      searchForm: {},
      tableData: [],
      loading: false,
      modId: '',//备用id
      electricFieldTypeList: [
        {value: 'E1', label: '光伏电站'},
        {value: 'E2', label: '风力电站'}
      ],
      // 表单校验
      rules: {
        stationCode: [
          {required: true, message: "场站编号不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "场站名称不能为空", trigger: "blur"}
        ],
        electricFieldTypeEnum: [
          {required: true, message: "类型不能为空", trigger: "blur"}
        ],
        capacity: [
          { required: true, message: '请正确填写装机容量' },
          { pattern: /^\d+(\.\d{0,2})?$/, message: '只能输入正数数字或带两位小数的数字' }
        ],
        longitude: [
          {required: true, message: '经度不能为空'},
          {pattern: /^\d+(\.\d{1,6})?$/, message: '只能输入正数数字或带小数点6位以内的数字'},
          {pattern: /^-?((0|1?[0-9]?[0-9]?)(([.][0-9]{1,10})?)|180(([.][0]{1,10})?))$/, message: '请输入正确的经度'},
          {validator: this.validateCoordinatesLongitude, trigger: "blur"}
        ],
        latitude: [
          {required: true, message: '纬度不能为空'},
          {pattern: /^\d+(\.\d{1,6})?$/, message: '只能输入正数数字或带小数点6位以内的数字'},
          {pattern: /^-?((0|[0-5]?[0-9]?)(([.][0-9]{1,10})?)|90(([.][0]{1,10})?))$/, message: '请输入正确的纬度'},
          {validator: this.validateCoordinatesLatitude, trigger: "blur"}
        ],
        provinceEnum: [
          {required: true, message: "省份不能为空", trigger: "blur"}
        ],
      },
    }
  },
  created() {
    // 获取后端省份枚举
    this.$axios.get('/electricfield/getProvinceEnum').then(response => {
      this.provinceEnumList = response.data
    })
    // 获取后端ftp通道
    this.$axios.get('/electricfield/getFtpChannelId').then(response => {
      this.ftpChannelList = response.data
    })
  },
  mounted() {
    this.dataQuery()
  },
  computed: {},
  methods: {
    validateCoordinatesLongitude(rule, value, callback) {
      // 验证经度范围：73.66 到 135.05
      if (this.form.longitude < 73.66 || this.form.longitude > 135.05) {
        callback(new Error("请输入有效的经度"));
      } else {
        callback();
      }
    },
    validateCoordinatesLatitude(rule, value, callback) {
      // 纬度范围：3.86 ~ 53.55
      if (this.form.latitude < 3.86 || this.form.latitude > 53.55) {
        callback(new Error("请输入有效的纬度"));
      } else {
        callback();
      }
    },
    // ftp通道改变
    ftpChannelChange(){
      // 清空扫描路径
      this.form.ftpUrl = ''
    },
    // 表单重置
    reset() {
      this.edit = false;
      this.form = {
        stationCode: '',
        name: '',
        electricFieldTypeEnum: '',
        capacity: '',
        longitude: '',
        latitude: '',
        provinceEnum: '',
        ftpChanelId: '',
        ftpUrl: '',
      },
      this.resetForm("form");
    },
    // 取消按钮
    cancelChannel() {
      this.open = false;
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增场站信息";
      this.edit = false;
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.title = "修改场站信息";
      this.reset();
      const _selectData = this.$refs.xTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.open = true;
      this.edit = true;
      this.form = JSON.parse(JSON.stringify(_selectData))
    },
    // 提交按钮
    commitChannel() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          console.log(this.form.ftpChanelId)
          if (this.form.ftpChanelId!=undefined && this.form.ftpChanelId!=''){
            if (this.form.ftpUrl==undefined || this.form.ftpUrl==''){
              this.$message.warning('请录入ftp扫描路径')
              return
            }
          }
          if (this.form.ftpUrl!=undefined && this.form.ftpUrl!=''){
            if (this.form.ftpChanelId==undefined || this.form.ftpChanelId==''){
              this.$message.warning('请选择ftp通道名称')
              return
            }
          }

          if (this.form.id != undefined) {
            // 更新操作
            this.$axios.post('/electricfield/updateById', this.form).then((res) => {
              this.$message.success('修改成功')
              this.open = false;
              this.dataQuery()
            }).catch((error) => {
            })
          } else {
            // 新增操作
            this.$axios.post('/electricfield/save', this.form).then((res) => {
              if (res == undefined) {
                this.$message.success('新增失败')
              } else {
                this.$message.success('新增成功')
                this.dataQuery()
                this.open = false;
              }
            }).catch((error) => {
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      const _selectData = this.$refs.xTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }

      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(_selectData)
      }).catch(() => {
      });
    },
    /**
     * 删除提交
     */
    doDelete(row) {
      this.$axios.post('/electricfield/remove', row).then((res) => {
        this.$message.success('删除成功！')
        this.dataQuery()
      }).catch((error) => {
      })
      this.loading = false
    },
    stationChange() {
      this.currentPage = 1
      this.pageSize = 10
    },
    stationCodeFormat({cellValue, row, column}) {
      const item = this.stationList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    electricFieldTypeFormat({cellValue, row, column}) {
      if (cellValue == 'E1') {
        return '光伏电站'
      } else if (cellValue == 'E2') {
        return '风力电站'
      } else{
        return ''
      }
    },
    provinceEnumFormat({cellValue, row, column}) {
      const item = this.provinceEnumList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    ftpChanelIdFormat({cellValue, row, column}) {
      if (cellValue != undefined && cellValue != ''){
        const item = this.ftpChannelList.find(item => item.value === cellValue.toString())
        return item ? item.label : ''
      }
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.executeQuery();
    },
    dataQuery() {
      this.currentPage = 1
      this.pageSize = 10
      this.executeQuery()
    },
    executeQuery() {
      this.loading = true
      const param = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        "stationName": this.stationName,
        "electricFieldType": this.electricFieldType,
      }

      this.$axios.get('/electricfield/getList', {params: param}).then(response => {
        this.tableData = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
  }
}
</script>
