<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="tLang('product', '产品名称')" prop="name">
        <el-input v-model="queryParams.name" :placeholder="tLang('common', '请输入') + tLang('product', '产品名称')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('product', '产品编码')" prop="code">
        <el-input v-model="queryParams.code" :placeholder="tLang('common', '请输入') + tLang('product', '产品编码')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('product', '产品类型')" prop="type">
        <el-input v-model="queryParams.type" :placeholder="tLang('common', '请输入') + tLang('product', '产品类型')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" size="mini" @click="handleQuery">{{ tLang('common', '搜索') }}</el-button>
        <el-button icon="refresh" size="mini" @click="resetQuery">{{ tLang('common', '重置') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:product:add']">{{ tLang('common', '新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:product:edit']">{{ tLang('common', '修改') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:product:remove']">{{ tLang('common', '删除') }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="download" size="mini" @click="handleExport"
          v-hasPermi="['product:product:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="productionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" :label="tLang('common', '序号')" width="60" align="center" />
      <el-table-column :label="tLang('product', '产品名称')" align="center" v-if="columns[0].visible" prop="name" />
      <el-table-column :label="tLang('product', '产品类型')" align="center" v-if="columns[1].visible" prop="type" />
      <el-table-column :label="tLang('product', '产品编码')" align="center" v-if="columns[2].visible" prop="code" />
      <el-table-column :label="tLang('product', '二维码')" align="center" v-if="columns[2].visible" prop="code">
        <template #default="scope">
          <el-button type="primary" @click="getProductQRCode(scope.row.code)">{{ tLang('product', '下载')
            }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('common', '操作')" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip :content="tLang('common', '详情')" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Tickets" @click="handleInfo(scope.row)"
              v-hasPermi="['product:product:info']"></el-button>
          </el-tooltip>
          <el-tooltip :content="tLang('common', '修改')" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['product:product:edit']"></el-button>
          </el-tooltip>
          <el-tooltip :content="tLang('common', '删除')" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['product:product:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination :hide-on-single-page="true" v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize" :page-sizes="[25, 50, 100, 150]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList"
        @current-change="getList" />
    </div>
    <AddEdit :title="title" v-model="open" :form="form" @submitForm="submitForm"></AddEdit>
    <InfoVue v-model="infoDialog" :info="productinfo" />

    <el-image-viewer v-if="showImagePreview" :url-list="showsrcListref" hide-on-click-modal teleported
      @close="closePreview" style="z-index: 3000" />
  </div>
  <canvas ref="myCanvas" width="250" height="350" style="display: none;background-color: #fff;"></canvas>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { listProduction, getProduction, delProduction, addProduction, updateProduction, selectProduction, getQRCode } from "@/api/casm/product";
import AddEdit from './add_edit.vue';
import InfoVue from "./info.vue";
const { proxy } = getCurrentInstance();


let showsrcListref = ref([])
// 遮罩层
let loading = ref(true)
// 选中数组
let ids = ref([])
// 非单个禁用
let single = ref(true)
// 非多个禁用
let multiple = ref(true)
// 显示搜索条件
let showSearch = ref(false)
// 表单参数
let form = ref({})
// 是否显示弹出层
let open = ref(false)
// 弹出层标题
let title = ref("")
// 查询参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  code: null,
  type: null
})

let total = ref(0)
// 设备信息表格数据
let productionList = ref([
  { name: '设备1', code: 'code1', id: 1 },
])
//二维码预览
let showImagePreview = ref(false)
function closePreview() {
  showImagePreview.value = false
}
let myCanvas = ref(null)
let ctx = null
function getProductQRCode(code) {
  getQRCode({ code }).then(response => {
    if (response.code == 200) {
      const qrCodeURL = response.data.base64
      let list = JSON.parse(response.data.content)
      console.log(list);
      ctx = myCanvas.value.getContext('2d');

      // 设置背景颜色
      ctx.fillStyle = '#ffffff';
      // 填充整个画布
      ctx.fillRect(0, 0, myCanvas.value.width, myCanvas.value.height);
      // 绘制二维码
      const qrImage = new Image();
      qrImage.onload = function () {
        ctx.drawImage(qrImage, 20, 60, 220, 220); // 根据需要调整二维码的位置
        addListInfo(list);
      };
      qrImage.src = qrCodeURL;
    }
  });


  // 添加列表信息
  function addListInfo(list) {
    ctx.font = "bold 20px Arial";
    ctx.fillStyle = "black";
    ctx.textAlign="center";
    ctx.fillText("产品编码" + ':' + code, 125, 310); // 调整文本的位置和行间距
    // Object.keys(list).forEach((key,index) => {
    //   ctx.fillText(key +':'+ list[key], 240, 30 + index * 20); // 调整文本的位置和行间距
    // });
    downloadImage();
  }

  // 下载图片
  function downloadImage() {
    const image = myCanvas.value.toDataURL("image/png").replace("image/png", "image/octet-stream");
    const link = document.createElement('a');
    link.download = code + '.png';
    link.href = image;
    link.click();
  }
}





// 列显隐信息
const columns = ref([
  { key: 0, label: proxy.tLang('product', '产品名称'), visible: true },
  { key: 1, label: proxy.tLang('product', '产品类型'), visible: true },
  { key: 2, label: proxy.tLang('product', '产品编码'), visible: true },
]);

let infoDialog = ref(false)
let productinfo = ref({})
/** 查询设备信息列表 */
function getList() {
  loading.value = true;
  listProduction(queryParams).then(response => {
    productionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.code)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

//** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.name = null
  queryParams.code = null

  handleQuery();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = proxy.tLang('common', '添加') + proxy.tLang('product', '产品信息');
}

/**详情按钮操作 */
function handleInfo(row) {
  selectProduction(row.code).then(response => {
    productinfo.value = response.data
    infoDialog.value = true
  });
}

/** 提交按钮 */

/** 提交按钮 */
function submitForm(propform) {
  if (propform.code != null) {
    updateProduction(propform).then(response => {
      proxy.$modal.msgSuccess(proxy.tLang('common', '修改成功'));
      open.value = false;
      getList();
    });
  } else {
    addProduction(propform).then(response => {
      proxy.$modal.msgSuccess(proxy.tLang('common', '添加成功'));
      open.value = false;
      getList();
    });
  }
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    name: '',
    type: '',
    code: '',
    remark: "",
    file: "",    
    disabled: false
  };
  //resetForm("form");
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.code || ids.value
  getProduction(id).then(response => {
    form.value = response.data;
    form.value.disabled = true;
    open.value = true;
    title.value = proxy.tLang('common', '修改') + proxy.tLang('product', '产品信息');
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.code || ids.value;
  proxy.$modal.confirm(proxy.tLang('tip', '确定删除选中记录？') + ` [${id}]`).then(function () {
    return delProduction(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(proxy.tLang('common', '删除成功'));
  }).catch(() => { });
}
onMounted(() => {
  getList();
})
</script>

<style lang="scss" scoped>
.pagination {
  width: 100%;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
