<template>
  <div class="device">
    <searchBox :btn-option-list="btnOptionList" @operateForm="operateForm"></searchBox>

    <div style="display: flex; height: calc(100% - 40px); ">
     <div style="display: block; min-width:200px; width: 200px; height: 100%; overflow-y: auto; background-color: #08365c; border-radius: 5px; padding-top: 10px;">
        <a-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys" :tree-data="stationTreeData" @select="onSelectStation">
        </a-tree>
      </div>

      <div class="content-table">
        <ComTable
          :columns="columns"
          :table-data="tableData"
          @handlePagesizeChange="handlePagesizeChange"
          ref="comTable"
          :table-option="tableOption"
          :page-option="pageOption"
        >
          <template #type="record">
            <span>{{ getType(record.type) }}</span>
          </template>
          <template #isEnable="record">
            <span
              ><a-tag :color="record.is_open == 1 ? 'green' : 'red'">{{
                record.is_open == 1 ? '启用' : '禁用'
              }}</a-tag></span
            >
          </template>

          <template #action="record">
            <OperateCom :record="record" :operate-list="operateList" @operateForm="operateForm" />
          </template>
        </ComTable>
      </div>
    </div>
    <a-modal v-model:open="formModal" width="750px" style="top: 80px" :footer="null">
      <!-- action:edit add -->
      <EditCom
        v-if="formModal"
        :record="formState"
        @operateForm="operateForm"
        type="device"
        :action="formStatus"
        ref="editComRef"
      ></EditCom>
    </a-modal>
  </div>
</template>

<script>
import { columnList, deviceOptions } from '../../../public/config/columnList'
import { getReq, postReq } from '@/request/api.js'
import ComTable from '@/components/ComTable'
import OperateCom from '@/components/OperateCom'
import EditCom from '@/components/EditCom.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'

import searchBox from '@/components/SearchBox.vue'
import { deviceTypeList } from '@/utils/config.js'
export default {
  name: '',
  components: {
    searchBox,
    EditCom,
    ComTable,
    OperateCom
  },
  props: {},
  data() {
    return {
      deviceTypeList,
      formModal: false,
      formState: {},
      formStatus: 'add', //表单状态辑状态 add:新增 edit:编辑
      pageOption: {
        pageSize: 10,
        page: 1
      },
      btnOptionList: [],
      paramsDate: {},
      tableData: [],
      tableOption: {},
      stations: [], //场站列表
      stationTreeData: [],
      selectedStationId: undefined
    }
  },
  computed: {},
  created() {
    let info = []
    let col = columnList.find((i) => i.page == 'device').columns
    if (col.length) {
      col.forEach((item) => {
        info.push(this.$setWidth(item))
      })
    }
    this.columns = info
  },

  mounted() {
    this.operateList = this.$getBtns(['查看', '修改', '删除'])
    this.btnOptionList = this.$getBtns(['新增'])
    this.getStations()
    //this.getList()
  },

  methods: {
    //查询场站列表
    async getStations() {
      this.stations = []
      try {
        const res = await getReq('/queryStationList', { page: 0, page_size: 10000 })
        this.stations = res.data
        this.stationTreeData = []
        res.data.forEach((item)=>{
          this.stationTreeData.push( { title: item.name, key: item.station_id})
        })
      } catch (error) {
        this.stations = []
      }
      return
    },
    //获取设备类型
    getType(type) {
      const device = this.deviceTypeList.find((item) => item.value == type) || null
      if (device) return device.label
      return type
    },
    async getList() {
      this.$refs.comTable.loading = true

      const { page, pageSize } = this.pageOption

      const params = {
        station_id: this.selectedStationId,
        ...this.paramsDate,
        page_size: pageSize,
        page
      }

      try {
        const res = await getReq('/queryDeviceList', params)
        if (res.errcode === 0) {
          this.$refs.comTable.loading = false

          this.tableData = res.data

          this.pageOption = {
            page: res.page,
            pageSize: res.page_size,
            count: res.count
          }
        } else {
          const err = { tip: res.errmsg }
          throw err
        }
      } catch (error) {
        //统一处理报错提示
      }
    },
    async operateForm(type, record = {}) {
      this.formStatus = type
      if (type == 'add') {
        this.formModal = true
        this.formState = {}
        this.getRuleFormInfo()
      } else if (type == 'edit' || type == 'read') {
        await this.getRuleFormInfo(record)
        this.formModal = true
        this.formState = record
      } else if (type == 'del') {
        this.handleDelete([record.device_id], this.getList)
      } else if (type == 'back') {
        this.formModal = false
        this.getList()
      }
    },
    //  删除操作
    async handleDelete(id, callback) {
      const that = this
      this.$Modal.confirm({
        title: '你确认删除数据吗?',
        icon: createVNode(ExclamationCircleOutlined),

        async onOk() {
          try {
            const res = await getReq('/deleteDevice', { device_id: id })
            if (res.errcode === 0) {
              this.$message.success(res.errmsg)
              this.pageOption.page = 1
              callback()
            } else {
              throw res
            }
          } catch (error) {
            callback()
          }
        },
        onCancel() {},
        class: 'test'
      })
    },
    async getRuleFormInfo(record) {
      const row = record || {}

      for (let e of deviceOptions) {
        for (let i of e.list) {
          if (i.key === 'id') {
            e.ruleForm.id = row.id
          } else if (i.key === 'is_open') {
            e.ruleForm.is_open = Boolean(Number(row.is_open))
          } else {
            e.ruleForm[i.key] = row[i.key] || ''
          }

          if (i.key === 'station_id') {
            i.list = this.stations
          }
          if (['rated_capacity', 'rated_current', 'rated_voltage', 'reted_power'].includes(i.key)) {
            const attrs = JSON.parse(row.attrs || '{}')
            e.ruleForm[i.key] = attrs[i.key]
          }
        }
      }
    },
    handlePagesizeChange(pageOption) {
      this.pageOption.pageSize = pageOption.pageSize
      this.pageOption.page = pageOption.page
      this.getList()
    },
    onSelectStation(selectedKey, ) {
      this.selectedStationId = selectedKey
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.device {
  height: 100%;
  padding:  20px;

  .content-table {
    width: 100%;
    height: calc(100% - 52px);
    margin-left: 20px;
  }
}


:deep(.ant-tree-list) {
  background-color: #08365c;
  font-size: 16px;
  color: white;
}
:deep(.ant-tree-treenode ) {
  width: 100%;
  height: 30px;
}
:deep(.ant-tree-node-content-wrapper) {
  width: calc(100% - 34px);
  height: 30px;
}
:deep(.ant-tree-node-selected) {
  background-color: #27a188 !important;
  border-radius: 5px !important;
}
</style>
