<template>
  <div class="equipment-container">
    <div class="search-container">
      <div class="search-ctn">
        <div>
          <div class="label">设备类型：</div>
          <div class="input-rule">
            <t-select v-model="queryCondition.equipmentType" style="width: 200px" clearable placeholder="请选择...">
              <t-option v-for="(item,index) in typeList" :value="item.resourceToolType" :key="index+'type'">{{ item.name }}</t-option>
            </t-select>
          </div>
        </div>
        <div>
          <div class="label">设备名称：</div>
          <div class="input-rule">
            <t-input v-model="queryCondition.equipmentName" style="width: 200px" placeholder="请输入..." clearable></t-input>
          </div>
        </div>
        <div>
          <div class="label">设备编号：</div>
          <div class="input-rule">
            <t-input v-model="queryCondition.equipmentNumber" style="width: 200px" placeholder="请输入..." clearable></t-input>
          </div>
        </div>
        <div class="btns">
          <t-button color="success" icon="search-outline" @click="onSearch">查询</t-button>
          <t-button color="secondary" icon="loading" class="reset-btn" @click="onReset">重置</t-button>
          <t-button color="secondary" icon="upload-outline" @click="toExport">导出至Excel</t-button>
          <t-button color="secondary" icon="delete-outline" @click="batchDelete">删除</t-button>
        </div>
      </div>
      <div class="search-ctn" style="justify-content: flex-end;">
        <div class="btns">
          <t-button color="success" icon="plus-outline" @click="addEquipment">新增</t-button>
          <t-button color="success" icon="upload-outline" @click="onReset">导入</t-button>
          <t-button color="success" icon="download-outline" @click="onReset">下载模板</t-button>
        </div>
      </div>
    </div>
    <div>
      <t-table :data="table.data" :loading="tableLoading" @selection-change="handleSelectionChange">
        <t-table-column type="selection" width="70"></t-table-column>
        <t-table-column prop="resourceToolName" label="设备名称"></t-table-column>
        <t-table-column prop="resourceToolCode" label="设备编号"></t-table-column>
        <t-table-column :formatter="type_formatter" prop="resourceToolType" label="设备类型">
        </t-table-column>
        <t-table-column prop="radius" label="半径"></t-table-column>
        <t-table-column prop="longitude" label="经度"></t-table-column>
        <t-table-column prop="latitude" label="纬度"></t-table-column>
        <t-table-column
          fixed="right"
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <a href="javascript:void(0)" size="sm" @click="handleClick(scope.row)">编辑</a>
            <span class="mod-line">|</span>
            <a href="javascript:void(0)" size="sm" @click="remove(scope.row)">删除</a>
          </template>
        </t-table-column>
      </t-table>
      <t-pager :total="table.pager.total" :current.sync="table.pager.currentPage"
               :page-size.sync="table.pager.size"
               :sizer-range="[10,20,50]"
               class="px-24 pt-16 float-right"
               show-elevator show-sizer
               @on-size-change="onSizeChange"
               @on-change="onPagerChange">
      </t-pager>
    </div>
    <t-modal :visibled.sync="modal" :mask-closable="false" title="新增设备" >
      <t-form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" label-position="left">
        <t-form-item label="设备类型" prop="type">
          <t-select v-model="formValidate.type" placeholder="请选择设备类型" clearable>
            <t-option v-for="(item,index) in typeList" :value="item.resourceToolType" :key="index+'type'">{{ item.name }}</t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="设备名称" prop="name">
          <t-input v-model="formValidate.name" placeholder="请输入设备名称"></t-input>
        </t-form-item>
        <t-form-item label="设备编号" prop="number">
          <t-input v-model="formValidate.number" placeholder="请输入字母、数字、中划线、下划线、#"></t-input>
        </t-form-item>
        <t-form-item label="半径" prop="radius">
          <t-input v-model="formValidate.radius" placeholder="请输入设备名称"></t-input>
        </t-form-item>
        <div v-if="formValidate.type!=='001'">
          <t-form-item label="经度" prop="lng">
            <t-format-input v-model="formValidate.lng" :numeral-decimal-scale="8" numeral placeholder="请输入数字"></t-format-input>
          </t-form-item>
        </div>
        <div v-if="formValidate.type!=='001'">
          <t-form-item label="纬度" prop="lat">
            <t-format-input v-model="formValidate.lat" :numeral-decimal-scale="8" numeral placeholder="请输入数字"></t-format-input>
          </t-form-item>
        </div>
      </t-form>
      <div slot="footer">
        <t-button @click="cancel">取消</t-button>
        <t-button class="submit-button" @click="submit">保存</t-button>
      </div>
    </t-modal>
    <t-modal :visibled.sync="updateModal" :mask-closable="false" title="编辑设备" >
      <t-form ref="updateRow" :model="updateRow" :rules="ruleUpdateValidate" :label-width="80" label-position="left">
        <t-form-item label="设备类型" prop="resourceToolType">
          {{ updateRow.name }}
        </t-form-item>
        <t-form-item label="设备编号" prop="resourceToolCode">
          {{ updateRow.resourceToolCode }}
        </t-form-item>
        <t-form-item label="设备名称" prop="resourceToolName">
          <t-input v-model="updateRow.resourceToolName" placeholder="请输入设备名称"></t-input>
        </t-form-item>
        <t-form-item label="半径" prop="radius">
          <t-input v-model="updateRow.radius" numeral placeholder="请输入设备半径"></t-input>
        </t-form-item>
        <div v-if="updateRow.resourceToolType!=='001'">
          <t-form-item label="经度" prop="longitude">
            <t-format-input v-model="updateRow.longitude" :numeral-decimal-scale="8" numeral placeholder="请输入数字"></t-format-input>
          </t-form-item>
        </div>
        <div v-if="updateRow.resourceToolType!=='001'">
          <t-form-item label="纬度" prop="latitude">
            <t-format-input v-model="updateRow.latitude" :numeral-decimal-scale="8" numeral placeholder="请输入数字"></t-format-input>
          </t-form-item>
        </div>
      </t-form>
      <div slot="footer">
        <t-button @click="cancel">取消</t-button>
        <t-button class="submit-button" @click="updateSubmit">保存</t-button>
      </div>
    </t-modal>
    <t-loading v-model="fullLoading" fullscreen tip="加载中...."></t-loading>
  </div>
</template>
<script>
import './equipment-management.scss'
import services from '../../conf/services'
export default {
  data() {
    return {
      typeList: [],
      table: {
        data: [
        ],
        pager: {
          currentPage: 1,
          size: 10,
          total: 0
        }
      },
      selection: [],
      tableLoading: true,
      fullLoading: false,
      queryCondition: {
        equipmentType: null,
        equipmentName: '',
        equipmentNumber: ''
      },
      modal: false,
      updateModal: false,
      updateRow: {
        resourceToolType: '',
        resourceToolName: '',
        radius: null,
        resourceToolCode: '',
        longitude: '',
        latitude: ''
      },
      formValidate: {
        type: '',
        name: '',
        radius: null,
        number: '',
        lng: '',
        lat: ''
      },
      ruleValidate: {
        type: [{
          required: true,
          message: '设备类型不能为空',
          trigger: 'change'
        }],
        name: [
          {
            required: true,
            message: '设备名称不能为空',
            trigger: 'blur'
          },
          {
            message: '设备名称重复',
            trigger: 'blur',
            t: this,
            validator: async function(rule, value, callback) {
              // TODO 判断编号重复
              var flag = await rule.t.checkReptition({
                resourceToolName: value
              })
              console.log(flag)
              if (flag) {
                console.log('编号重复')
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ],
        number: [
          {
            required: true,
            message: '编号不能为空',
            trigger: 'blur'
          },
          {
            message: '请输入字母、数字、中划线、下划线、#',
            trigger: 'blur',
            t: this,
            validator: async function(rule, value, callback) {
              if (!/^[a-zA-Z0-9-_#]+$/.test(value)) {
                callback(rule.message)
              } else {
                // TODO 判断编号重复
                var y = await rule.t.checkReptition({
                  resourceToolCode: value
                })
                console.log(y)
                if (y) {
                  rule.message = '编号重复'
                  callback(rule.message)
                } else {
                  return true
                }
              }
            }
          }
        ],
        radius: [
          {
            message: '请输入数字',
            trigger: 'blur',
            validator: function(rule, value, callback) {
              if (isNaN(value)) {
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ],
        lng: [
          {
            required: true,
            message: '经度不能为空',
            trigger: 'blur'
          },
          {
            message: '请输入数字',
            trigger: 'blur',
            validator: function(rule, value, callback) {
              if (isNaN(value)) {
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ],
        lat: [
          {
            required: true,
            message: '纬度不能为空',
            trigger: 'blur'
          },
          {
            message: '请输入数字',
            trigger: 'blur',
            validator: function(rule, value, callback) {
              if (isNaN(value)) {
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ]
      },
      ruleUpdateValidate: {
        resourceToolName: [
          {
            required: true,
            message: '设备名称不能为空',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              console.log(value)
              if (value) {
                callback()
              } else {
                callback(rule.message)
              }
            }
          },
          {
            message: '设备名称重复',
            trigger: 'blur',
            t: this,
            validator: async function(rule, value, callback) {
              console.log(value)
              // TODO 判断编号重复
              var flag = await rule.t.checkReptition({
                resourceToolName: value
              })
              console.log(flag)
              if (flag) {
                console.log('编号重复')
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ],
        radius: [
          {
            message: '请输入数字',
            trigger: 'blur',
            validator: function(rule, value, callback) {
              if (isNaN(value)) {
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ],
        longitude: [
          {
            required: true,
            message: '经度不能为空',
            trigger: 'blur'
          },
          {
            message: '请输入数字',
            trigger: 'blur',
            validator: function(rule, value, callback) {
              if (isNaN(value)) {
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ],
        latitude: [
          {
            required: true,
            message: '纬度不能为空',
            trigger: 'blur'
          },
          {
            message: '请输入数字',
            trigger: 'blur',
            validator: function(rule, value, callback) {
              if (isNaN(value)) {
                callback(rule.message)
              } else {
                return true
              }
            }
          }
        ]
      }
    }
  },
  mounted() {
    this.getType().then(() => {
      this.getList()
    })
  },
  methods: {
    async getType() {
      this.fullLoading = true
      await this.$test.post(services.equipment.EQUIPMENT_TYPE, {}
      ).then(res => {
        // 请求成功处理...
        this.fullLoading = false
        this.typeList = res.data
      }).catch(res => {
        // 请求失败处理...
        this.fullLoading = false
      })
    },
    getList() {
      this.tableLoading = true
      this.$test.post(services.equipment.GET_EQUIPMENT, {
        pageNumber: this.table.pager.currentPage,
        pageSize: this.table.pager.size,
        data: {
          resourceToolType: this.queryCondition.equipmentType,
          resourceToolNameAsLike: this.queryCondition.equipmentName,
          resourceToolCode: this.queryCondition.equipmentNumber
        }
      }
      ).then(res => {
        // 请求成功处理...
        console.log(res)
        this.tableLoading = false
        this.table.data = res.data.data
        this.table.pager.total = res.data.total
      }).catch(res => {
        // 请求失败处理...
        this.tableLoading = false
      })
    },
    type_formatter(row, column) {
      var arr = this.typeList.filter((item) => {
        return item.resourceToolType === row.resourceToolType
      })
      if (arr[0]) {
        return arr[0].name
      }
    },
    onReset() {
      this.queryCondition = {
        equipmentType: null,
        equipmentName: '',
        equipmentNumber: ''
      }
      this.onSearch()
    },
    onSearch() {
      this.table = {
        data: [
        ],
        pager: {
          currentPage: 1,
          size: 10,
          total: 0
        }
      }
      this.getList()
    },
    toExport() {

    },
    checkReptition(data) {
      return new Promise((resolve) => {
        this.fullLoading = true
        this.$test.post(services.equipment.GET_EQUIPMENT, {
          pageNumber: 1,
          pageSize: 10,
          data: data
        }
        ).then(res => {
        // 请求成功处理...
          this.fullLoading = false
          console.log(res)
          if (res.data.totalPage > 0 && res.data.data[0].resourceToolId === this.updateRow.resourceToolId) {
            resolve(false)
          } else {
            resolve(res.data.totalPage > 0)
          }
        }).catch(res => {
        // 请求失败处理...
          this.fullLoading = false
          resolve(false)
        })
      })
    },
    onPagerChange(page) {
      this.table.pager.currentPage = page
      this.getList()
    },
    onSizeChange(number) {
      this.table.pager.size = number
      this.getList()
    },
    cancel() {
      this.modal = false
      this.updateModal = false
      this.formValidate = {
        type: '',
        name: '',
        radius: null,
        number: '',
        lng: '',
        lat: ''
      }
    },
    submit() {
      this.$refs.formValidate.validate(valid => {
        console.log(valid)
        if (valid) {
          this.fullLoading = true
          this.$test.post(services.equipment.CREATE_EQUIPMENT, {data: {
            latitude: this.formValidate.lat ? this.formValidate.lat : null,
            longitude: this.formValidate.lng ? this.formValidate.lng : null,
            radius: this.formValidate.radius ? this.formValidate.radius : null,
            resourceToolCode: this.formValidate.number,
            resourceToolName: this.formValidate.name,
            resourceToolType: this.formValidate.type
          }}
          ).then(res => {
            // 请求成功处理...
            this.fullLoading = false
            this.$Message.success('提交成功!')
            this.getList()
            this.modal = false
            this.formValidate = {
              type: '',
              name: '',
              radius: null,
              number: '',
              lng: '',
              lat: ''
            }
          }).catch(res => {
            // 请求失败处理...
            this.fullLoading = false
          })
        } else {
          this.$Message.danger('表单验证失败!')
        }
      })
    },
    updateSubmit() {
      this.$refs.updateRow.validate(valid => {
        console.log(valid)
        if (valid) {
          this.fullLoading = true
          console.log(this.updateRow)
          this.$test.post(services.equipment.UPDATE_EQUIPMENT, {
            data: this.updateRow
          }
          ).then(res => {
            // 请求成功处理...
            this.fullLoading = false
            this.$Message.success('提交成功!')
            this.getList()
            this.updateModal = false
          }).catch(res => {
            // 请求失败处理...
            this.fullLoading = false
          })
        } else {
          this.$Message.danger('表单验证失败!')
        }
      })
    },
    addEquipment() {
      this.modal = true
    },
    handleClick(row) {
      this.updateModal = true
      console.log(row)
      var name
      this.typeList.forEach(element => {
        if (element.resourceToolType === row.resourceToolType) {
          name = element.name
        }
      })
      row.name = name
      this.updateRow = row
    },
    remove(row) {
      this.delete([row.resourceToolId])
    },
    delete(arr) {
      this.$Confirm.confirm({
        title: '请确认',
        content: '删除后不可恢复,确认删除吗?',
        ok: () => {
          this.fullLoading = true
          this.$test.post(services.equipment.DEL_EQUIPMENT, {
            data: arr
          }
          ).then(res => {
            // 请求成功处理...
            this.fullLoading = false
            this.$Message.success('操作成功')
            this.table.pager.currentPage = 1
            this.getList()
          }).catch(res => {
            // 请求失败处理...
            this.fullLoading = false
          })
        }
      })
    },
    handleSelectionChange(val) {
      var arr = []
      val.forEach(element => {
        arr.push(element.resourceToolId)
      })
      this.selection = arr
    },
    batchDelete() {
      console.log(this.selection)
      this.delete(this.selection)
    }
    // longLatFormatter(row, column, cellValue, index) {
    //   if (cjsj.FACILITY_TYPE === '001') {
    //     return '--'
    //   }
    //   return cellValue
    // },
  }
}
</script>
