<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="6" :lg="12" :md="12" :sm="24" :xs="24">
            <a-form-item label="部件类型">
              <a-select v-model:value="queryform.componentType" placeholder="请选择部件类型" allow-clear>
                <a-select-option value="车辆">车辆</a-select-option>
                <a-select-option value="电池">电池</a-select-option>
                <a-select-option value="头盔">头盔</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="12" :md="12" :sm="24" :xs="24">
            <a-form-item label="供应商">
              <a-input v-model:value.trim="queryform.supplier" placeholder="请输入供应商" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :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="handleAdd">
          <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 === 'action'">
            <SettingOutlined style="margin-right: 5px" />{{ column.title }}
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            {{ record.state == '1' ? '已生成二维码' : record.state == '-1' ? '已删除' : '' }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space  v-if="record.state != '1' && record.state != '-1'">
              <a @click="handleEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm
                @confirm="handleDel(record)"
                ok-text="是"
                cancel-text="否"
                placement="topRight"
                title="确定要删除吗？"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a @click="handleCreateQR(record)">生成二维码</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="open" :title="openTitle" @ok="handleOk" width="800px" :maskClosable="false">
      <a-form ref="formRef" :model="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 :xs="24">
            <a-form-item label="部件类型" required name="componentType" :rules="[{ required: true, message: '请选择部件类型' }]">
              <a-select v-model:value="form.componentType" placeholder="请选择部件类型" allow-clear>
                <a-select-option value="车辆">车辆</a-select-option>
                <a-select-option value="电池">电池</a-select-option>
                <a-select-option value="头盔">头盔</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24">
            <a-form-item label="供应商" required name="supplier" :rules="[{ required: true, message: '请输入供应商' }]">
              <a-input v-model:value="form.supplier" placeholder="请输入供应商" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24">
            <a-form-item label="数量" required name="quantity" :rules="[{ required: true, message: '请输入数量' }]">
              <a-input v-model:value="form.quantity" placeholder="请输入数量" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24">
            <a-form-item label="备注">
              <a-textarea v-model:value="form.remark" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } 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 {
  SettingOutlined
} from '@ant-design/icons-vue'

const formRef = ref()
const open = ref(false);
const openTitle = ref('下单');

// 表格行数据
const dataSource = ref([])
const data = ref([])
// 查询相关
const queryform = ref({
  owningRegion: '',
  componentType: '',
  supplier: '',
  pageParam: {
    pageNum: config.pageParam.pageNum,
    pageSize: config.pageParam.pageSize
  }
})

// 表单相关
const form = ref({
  componentId: null,
  owningRegion: '',
  componentType: '',
  supplier: '',
  quantity: 0,
  remark: '',
  state: '',
  createdUser: ''
})

//对于每页数据的管理
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([
  {
    title: '序号',
    key: 'index',
    width: 70,
    align: 'center',
    dataIndex: 'index'
  },
  {
    key: 'componentType',
    title: '部件类型',
    dataIndex: 'componentType',
    align: 'center'
  },
  {
    key: 'supplier',
    title: '供应商',
    align: 'center',
    dataIndex: 'supplier'
  },
  {
    key: 'quantity',
    title: '数量',
    align: 'center',
    dataIndex: 'quantity'
  },
  {
    key: 'state',
    title: '状态',
    align: 'center',
    dataIndex: 'state'
  },
  {
    title: '操作',
    key: 'action',
    width: 320,
    align: 'center'
  }
])

//获取用户列表数据并格式化字段
onMounted(async () => {
  getData();
})

const getData = async () => {
  const res = await callOperate("/ebikeComponentProduction/list", queryform.value);
  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 handleAdd = () => {
  const userinfo = getCache('ebike-userinfo');
  form.value = {
    componentId: null,
    owningRegion: '',
    componentType: '',
    supplier: '',
    quantity: 0,
    remark: '',
    state: '0',
    createdUser: userinfo.username
  }
  open.value = true
  openTitle.value = '下单'
}

const handleEdit = (record) => {
  if(record.componentId == null) {
    message.error('请选择要修改的数据')
    return
  }
  callOperate("/ebikeComponentProduction/getInfo", { id: record.componentId }, 'get').then(res => {
    if (res.code != 200) {
      message.error(res.message)
      return
    }
    form.value = {
      componentId: res.data.componentId,
      owningRegion: res.data.owningRegion,
      componentType: res.data.componentType,
      supplier: res.data.supplier,
      quantity: res.data.quantity,
      remark: res.data.remark,
      state: res.data.state,
      createdUser: res.data.createdUser
    }
    open.value = true
    openTitle.value = '修改'
  });
}

const handleOk = () => {
  formRef.value.validate()
  .then(() => {
    if (form.value.componentId == null) {
      callOperate("/ebikeComponentProduction/save", form.value).then(res => {
        if (res.code != 200) {
          message.error(res.message)
          return
        }
        open.value = false
        getData()
      });
    }
    else
    {
      callOperate("/ebikeComponentProduction/update", form.value).then(res => {
        if (res.code != 200) {
          message.error(res.message)
          return
        }
        open.value = false
        getData()
      });
    }
  })  
  .catch(error => {
    console.log('error', error);
  });
}

//删除
const handleDel = async (record) => {
  const sform = {
    componentId: record.componentId,
    state: '-1'
  }
  const res = await callOperate("/ebikeComponentProduction/update", sform);
  if (res.code!= 200) {
    message.error(res.message)
    return
  }
  getData()
}

//生成二维码
const handleCreateQR = async (record) => {
  if(record.componentId == "") {
    message.error('请选择要生成二维码的数据')
    return
  }
  if(record.state == '1') {
    message.error('该数据已生成二维码')
    return
  }
  if(record.quantity == null || record.quantity == 0 || record.quantity == '' || record.quantity % 1 != 0) {
    message.error('数量不正确')
    return
  }
  if(record.componentType == '车辆') {
    const bqrform = {
      componentProId : record.componentId,
      bikeCodes : []
    }; 
    for(let i = 0; i < record.quantity; i++) {
      const sn = i.toString().padStart(2, '0');
      bqrform.bikeCodes.push(generateDistributedId(sn));
    }
    const res = await callOperate("/ebikeBikeQrcode/batchSave", bqrform);
    if (res.code!= 200) {
      message.error(res.message)
      return
    }
  }
  else if(record.componentType == '电池') {
    const bqrform = {
      componentProId : record.componentId,
      batteryCodes : []
    }; 
    for(let i = 0; i < record.quantity; i++) {
      const sn = i.toString().padStart(2, '0');
      bqrform.batteryCodes.push("B" + generateDistributedId(sn));
    }
    const res = await callOperate("/ebikeBatteryQrcode/batchSave", bqrform);
    if (res.code!= 200) {
      message.error(res.message)
      return
    }
  }
  else if(record.componentType == '头盔') {
    const hqrform = {
      componentProId : record.componentId,
      helmetCodes : []
    }; 
    for(let i = 0; i < record.quantity; i++) {
      const sn = i.toString().padStart(2, '0');
      hqrform.helmetCodes.push("H" + generateDistributedId(sn));
    }
    const res = await callOperate("/ebikeHelmetQrcode/batchSave", hqrform);
    if (res.code!= 200) {
      message.error(res.message)
      return
    }
  }
  else {
    message.error('请选择正确的部件类型')
    return
  }
  const sform = {
    componentId: record.componentId,
    state: '1'
  }
  const res = await callOperate("/ebikeComponentProduction/update", sform);
  if (res.code!= 200) {
    message.error(res.message)
    return
  }
  getData()
}

const generateDistributedId = (sn) => {
  const timestamp = Date.now().toString().slice(-8);
  const random = Math.floor(Math.random() * 100).toString().padStart(2, '0');
  return parseInt(timestamp + sn + random).toString();
}
</script>
