<template>
    <div>
      <a-card :bordered="false">
        <a-form
          :label-col="{ xl: 7, lg: 5, md: 7, sm: 4 }"
          :wrapper-col="{ xl: 17, lg: 19, md: 17, sm: 20 }"
        >
          <a-row :gutter="8">
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <a-form-item label="电池编号">
                <a-input v-model:value.trim="queryform.batteryCode" placeholder="请输入电池编号" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <a-form-item label="绑定状态">
                <a-select v-model:value="queryform.state" placeholder="请选择绑定状态" allow-clear>
                  <a-select-option value="未绑定">未绑定</a-select-option>
                  <a-select-option value="已绑定)">已绑定)</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <a-form-item label="绑定人">
                <a-input v-model:value.trim="queryform.operator" placeholder="请输入绑定人" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <a-form-item label="绑定时间">
                <a-range-picker v-model:value="queryform.boundTime" :placeholder="['绑定时间起','绑定时间止']" />
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
              <a-form-item class="ele-text-right" :wrapper-col="{ span: 24 }">
                <a-space>
                  <a-button type="primary" style="background-color: #5cc750" @click="search"
                    >查询</a-button
                  >
                  <!-- <a-button>重置</a-button> -->
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <!-- 数据操作 -->
        <a-space style="margin-bottom: 10px">
          <a-button style="background-color: #5cc750" type="primary" class="ele-btn-icon" @click="handleBatchBind">
            <template #icon>
              <plus-outlined />
            </template>
            <span>绑定</span>
          </a-button>
        </a-space>
        <!-- 表格 -->
        <a-table
          :pagination="pagination"
          @change="handleTableChange"
          bordered
          :columns="columns"
          :dataSource="dataSource"
        >
          <template #headerCell="{ column }">
            <template v-if="column.key === 'checkbox'">
              <a-checkbox :checked="selectAll" @change="handleAllSelect" />
            </template>
            <template v-if="column.key === 'action'">
              <SettingOutlined style="margin-right: 5px" />{{ column.title }}
            </template>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'checkbox'">
              <a-checkbox :checked="selectkeys.includes(record.batteryCode)" @change="handleSelect(record)" />
            </template>
            <template v-if="column.key === 'state'">
                {{ record.state == '1' ? '已绑定' : '' }}
            </template>
            <template v-if="column.key === 'qrCode'">
                <a-qrcode :data-row-key="record.batteryCode"  :value="record.batteryCode" error-level="H" />
            </template>
            <template v-if="column.key === 'action'">
              <a-space  v-if="record.state != '1'">
                <a @click="handleBind(record)">绑定</a>
              </a-space>
              <a-divider type="vertical" />
              <a-space>
                <a @click="handleDown(record)">下载</a>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, reactive, nextTick } from 'vue'
  import { callOperate } from '@/apis/call.js'
  import { message } from 'ant-design-vue'
  import config from '@/utils/config.js'
  import { getCache } from '@/utils/authority'
  import { dataFormat } from '@/utils/tools'
  import {
    SettingOutlined
  } from '@ant-design/icons-vue'
  
  // 表格行数据
  const dataSource = ref([])
  const data = ref([])
  const selectkeys = ref([])
  const selectAll = ref(false)
  // 查询相关
  const queryform = ref({
    batteryCode: '',
    state: '',
    operator: '',
    boundTime: [
        '',
        ''
    ],
    startBoundTime: '',
    endBoundTime: '',
    pageParam: {
      pageNum: config.pageParam.pageNum,
      pageSize: config.pageParam.pageSize
    }
  })
  
  //对于每页数据的管理
  let pagination = reactive({
    total: dataSource.value.length,
    current: queryform.value.pageParam.pageNum,
    pageSize: queryform.value.pageParam.pageSize,
    showSizeChanger: true,
    pageSizeOptions: config.pageParam.pageSizeOptions,
    showQuickJumper: true
  })
  
  // 表格列配置
  const columns = ref([
    {
      key: 'checkbox',
      width: 48,
      align: 'center'
    },
    {
      title: '序号',
      key: 'index',
      width: 70,
      align: 'center',
      dataIndex: 'index'
    },
    {
      key: 'batteryCode',
      title: '电池编号',
      dataIndex: 'batteryCode',
      align: 'center'
    },
    {
      key: 'state',
      title: '状态',
      dataIndex: 'state',
      align: 'center'
    },
    {
      key: 'operator',
      title: '绑定人',
      dataIndex: 'operator',
      align: 'center'
    },
    {
      key: 'boundTime',
      title: '绑定时间',
      dataIndex: 'boundTime',
      align: 'center'
    },
    {
      key: 'qrCode',
      title: '二维码',
      width: 100,
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: 320,
      align: 'center'
    }
  ])
  
  //获取用户列表数据并格式化字段
  onMounted(async () => {
    getData();
  })
  
  const getData = async () => {
    let queryparams = queryform.value;
    if (queryparams.boundTime && queryparams.boundTime[0] != '') {
      queryparams.startBoundTime = dataFormat(queryparams.boundTime[0], 'yyyy-MM-dd HH:mm:ss');  
    }
    if (queryparams.boundTime && queryparams.boundTime[1]!= '') {
      queryparams.endBoundTime = dataFormat(queryparams.boundTime[1], 'yyyy-MM-dd HH:mm:ss'); 
    }
    delete queryparams.boundTime;
    const res = await callOperate("/ebikeBatteryQrcode/list", queryparams);
    if (res.code != 200) {
      message.error(res.message)
      dataSource.value = []
      data.value = []
      pagination.total = 0
      return
    }
    data.value = res.data.records
    data.value = data.value.map((item, index) => {
      index++
      return { ...item, index }
    })
    dataSource.value = data.value
    pagination.total = res.data.totalRow
  }
  
  
  // 对每页数据显示的交互
  let handleTableChange = (pagina) => {
    pagination.current = pagina.current
    pagination.pageSize = pagina.pageSize
    queryform.value.pageParam.pageNum = pagina.current
    queryform.value.pageParam.pageSize = pagina.pageSize
    getData()
  }
  
  const search = () => {
    getData()
  }
  
  const handleBatchBind = () => {
    if(selectkeys.value.length == 0) {
      message.error('请选择要绑定的数据')
      return
    }
    const params = [];
    for (let i = 0; i < dataSource.value.length; i++) {
      const item = dataSource.value[i];
      if (selectkeys.value.includes(item.batteryCode)) {
        if (item.state == '1') {
          message.error('电池编号为' + item.batteryCode + '已绑定')
          return
        }
        if (item.componentProId == null) {
          message.error('电池编号为' + item.batteryCode + '未选择绑定的数据')
          return
        }
        const userinfo = getCache('ebike-userinfo');
        params.push({
          batteryCodeId: item.batteryCodeId,
          operator: userinfo.username,
          boundTime: dataFormat(new Date(),'yyyy-MM-dd HH:mm:ss'),
          state: '1'
        })
      }
    }
    if(params.length > 0){
      callOperate('/ebikeBatteryQrcode/batchUpdate', params).then(res => {
        if (res.code === 200) {
          message.success('绑定成功')
          getData()
        } else {
          message.error(res.message) 
        } 
      })
    }
  }
  
  const handleBind = (record) => {
    if(record.state == '1') {
      message.error('该电池已绑定')
      return
    }
    if(record.componentProId == null) {
      message.error('请选择要绑定的数据')
      return
    }
    const userinfo = getCache('ebike-userinfo');
    const params = {
      batteryCodeId: record.batteryCodeId,
      operator: userinfo.username,
      boundTime: dataFormat(new Date(),'yyyy-MM-dd HH:mm:ss'),
      state: '1'
    }
    callOperate('/ebikeBatteryQrcode/update', params).then(res => {
      if (res.code === 200) {
        message.success('绑定成功')
        getData()
      } else {
        message.error(res.message)
      } 
    })
  }

  const handleDown = async (record) => {
    await nextTick();
    const rowElement =  document.querySelector(`[data-row-key="${record.batteryCode}"]`);
    var canvas = rowElement.querySelector('Canvas')
    if (canvas) {
        const url = canvas.toDataURL();
        const a = document.createElement('a');
        a.download = `${record.batteryCode}.png`;
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    } else {
        console.error('Row element not found');
    }
  }

  const handleSelect = (record) => {
    if (selectkeys.value.includes(record.batteryCode)) {
      selectkeys.value = selectkeys.value.filter((item) => item !== record.batteryCode)
    } else {
      selectkeys.value.push(record.batteryCode)
    }
    if (selectkeys.value.length === dataSource.value.length) {
      selectAll.value = true
    } else {
      selectAll.value = false 
    }
  }

  const handleAllSelect = () => {
    if (!selectAll.value) {
      selectAll.value = true
      selectkeys.value = dataSource.value.map((item) => item.batteryCode) 
    }   else {
      selectAll.value = false
      selectkeys.value = []
    }
  }
  </script>
  