<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item :label="tLang('device', '设备名称')" prop="name">
        <el-input v-model="queryParams.name" :placeholder="tLang('common', '请输入') + tLang('device', '设备名称')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('device', '设备编码')" prop="code">
        <el-input v-model="queryParams.code" :placeholder="tLang('common', '请输入') + tLang('device', '设备编码')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('device', '车间名称')" prop="workShop">
        <el-input v-model="queryParams.workShop" :placeholder="tLang('common', '请输入') + tLang('device', '车间名称')"
          clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item :label="tLang('device', '产线名称')" prop="lineName">
        <el-input v-model="queryParams.lineName" :placeholder="tLang('common', '请输入') + tLang('device', '产线名称')"
          clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item :label="tLang('device', '供货商名称')" prop="supplier" label-width="100px">
        <el-input v-model="queryParams.supplier" :placeholder="tLang('common', '请输入') + tLang('device', '供货商名称')"
          clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item :label="tLang('device', '生产厂家')" prop="manufacturer">
        <el-input v-model="queryParams.manufacturer" :placeholder="tLang('common', '请输入') + tLang('device', '生产厂家')"
          clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item :label="tLang('device', '品牌')" prop="brand">
        <el-input v-model="queryParams.brand" :placeholder="tLang('common', '请输入') + tLang('device', '品牌')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item :label="针数" prop="needleNum">
        <el-input v-model="queryParams.needleNum" :placeholder="tLang('common','请输入') + 针数" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item :label="tLang('device', '设备型号')" prop="model">
        <el-input v-model="queryParams.model" :placeholder="tLang('common', '请输入') + tLang('device', '设备型号')" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search"  @click="handleQuery">{{ tLang('common', '搜索') }}</el-button>
        <el-button icon="refresh"  @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"  @click="handleAdd" v-hasPermi="['pms:device:add']">
          {{ $t('common.新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="edit"  :disabled="single" @click="handleUpdate"
          v-hasPermi="['pms:device:edit']">{{ $t('common.修改') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete"  :disabled="multiple" @click="handleDelete"
          v-hasPermi="['pms:device:remove']">{{ $t('common.删除') }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="download"  @click="handleExport"
          v-hasPermi="['device:device: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="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" :label="$t('common.序号')" width="60" align="center" />
      <el-table-column :label="tLang('device', '设备名称')" align="center" v-if="columns[0].visible" prop="name" />
      <el-table-column :label="tLang('device', '机架号')" align="center" v-if="columns[1].visible" prop="label" />
      <el-table-column :label="tLang('device', '设备类型')" align="center" v-if="columns[2].visible" prop="type">
        <template #default="{ row }">
          <span>{{ typeOptions.find(item => item.value == row.type)?.label }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tLang('device', '设备型号')" align="center" v-if="columns[3].visible" prop="model" />
      <el-table-column :label="tLang('device', '设备版本')" align="center" v-if="columns[4].visible" prop="version" />
      <el-table-column :label="tLang('device', '保养周期')" align="center" v-if="columns[5].visible" prop="maintenance" />
      <el-table-column :label="tLang('device', '供货商名称')" align="center" v-if="columns[6].visible" prop="supplier" />
      <el-table-column :label="tLang('device', '供货商联络人')" align="center" v-if="columns[7].visible"
        prop="supplierContactPerson" />
      <el-table-column :label="tLang('device', '生产厂家')" align="center" v-if="columns[8].visible" prop="manufacturer" />
      <el-table-column :label="tLang('device', '厂家电话')" align="center" v-if="columns[9].visible"
        prop="contactPhone" />
      <el-table-column :label="tLang('device', '品牌')" align="center" v-if="columns[10].visible" prop="brand" />
      <!-- <el-table-column :label="tLang('device', '设备型号')" align="center" v-if="columns[11].visible" prop="model" /> -->
      <el-table-column :label="tLang('device', '负责人')" align="center" v-if="columns[11].visible" prop="director" />
      <el-table-column :label="tLang('device', '备注')" align="center" v-if="columns[12].visible" prop="remark" />
      <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="Download" @click="handleDownload(scope.row)"
            v-hasPermi="['pms:device:download']"></el-button>
          </el-tooltip> -->
          <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="['pms:device:query']"></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="['pms:device:edit']"></el-button>
          </el-tooltip>
          <!-- <el-tooltip :content="tLang('common', '解绑')" placement="top" v-if="scope.row.sn&&scope.row.sn.length > 0">
            <el-button link type="primary" icon="Failed" @click="handleUnbind(scope.row)"
              v-hasPermi="['pms:device: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="['pms:device: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="deviceinfo" />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { listDevice, getDevice, delDevice, addDevice, updateDevice, listDeviceType,downloadDeviceReport,downloadDeviceReportFile } from "@/api/pms/device.js";
import InfoVue from "./info.vue";
import AddEdit from './add_edit.vue';
const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
// 遮罩层
let loading = ref(true)
// 选中数组
let ids = ref([])
// 非单个禁用
let single = ref(true)
// 非多个禁用
let multiple = ref(true)
// 显示搜索条件
let showSearch = ref(false)
// 总条数
let total = ref(0)
// 设备信息表格数据
let deviceList = ref([])
// 弹出层标题
let title = ref("")
// 是否显示弹出层
let open = ref(false)
let infoDialog = ref(false)
let deviceinfo = ref({})
// 查询参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  code: null,
  label: null,
  type: null,
  workShop: null,
  lineName: null,
  maintenance: null,
  supplier: null,
  supplierContactPerson: null,
  manufacturer: null,
  contactPhone: null,
  brand: null,
  // needleNum: null,
  model: null,
  file: null,
})
// 表单参数
let form = ref({})
const formRef = ref(null)
// 表单校验
let rules = ref({
  code: [
    {
      required: true,
      message: proxy.tLang('common', '请输入') + proxy.tLang('device', '设备编码'),
      trigger: 'blur',
    },
  ],
  name: [
    {
      required: true,
      message: proxy.tLang('common', '请输入') + proxy.tLang('device', '设备名称'),
      trigger: 'blur',
    },
  ],
})
// 列显隐信息
const columns = ref([
  { key: 0, label: proxy.tLang('device', `设备名称`), visible: true },
  { key: 1, label: proxy.tLang('device', `机架号`), visible: true },
  { key: 2, label: proxy.tLang('device', `设备类型`), visible: true },
  { key: 3, label: proxy.tLang('device', `设备型号`), visible: false },
  { key: 4, label: proxy.tLang('device', `设备版本`), visible: true },
  { key: 5, label: proxy.tLang('device', `保养周期`), visible: true },
  { key: 6, label: proxy.tLang('device', `供货商名称`), visible: true },
  { key: 7, label: proxy.tLang('device', `供货商联络人`), visible: true },
  { key: 8, label: proxy.tLang('device', `生产厂家`), visible: true },
  { key: 9, label: proxy.tLang('device', `联系电话`), visible: true },
  { key: 10, label: proxy.tLang('device', `品牌`), visible: true },
  { key: 11, label: proxy.tLang('device', `负责人`), visible: true },
  { key: 12, label: proxy.tLang('device', `备注`), visible: false },
]);
/** 查询设备信息列表 */
function getList() {
  loading.value = true;
  listDevice(queryParams).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
let typeOptions = ref([])
function getListDeviceType() {
  listDeviceType({ pageSize: 100 }).then(res => {
    typeOptions.value = res.rows.map(item => {
      return {
        value: item.code,
        label: item.name
      }
    })
  })
}

//下载 
function handleDownload(row) {
  downloadDeviceReport(row.id).then(res => {
    // downloadDeviceReportFile(row.code).then(result=>{
      
    // })
    // const blob = new Blob([baseUrl + res.msg])
    const url = baseUrl + res.msg
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', `${row.code}`)
    document.body.appendChild(link)
    link.click()
    window.URL.revokeObjectURL(url)
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    code: null,
    label: null,
    workShop: null,
    lineName: null,
    maintenance: null,
    supplier: null,
    supplierContactPerson: null,
    manufacturer: null,
    machineHead: 1,
    contactPhone: null,
    brand: null,
    // needleNum: 1,
    model: null,
    file: null,
    remark: null,
    director: null,
    config: '',
    maintenanceManual: '',
    configList: [],
  };
  //resetForm("form");
}

//** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.name = null
  queryParams.code = null
  queryParams.type = null
  queryParams.workShop = null
  queryParams.lineName = null
  queryParams.maintenance = null
  queryParams.supplier = null
  queryParams.supplierContactPerson = null
  queryParams.manufacturer = null
  queryParams.contactPhone = null
  queryParams.brand = null
  // queryParams.needleNum = null
  queryParams.model = null
  queryParams.file = null

  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/**详情按钮操作 */
function handleInfo(row) {
  deviceinfo.value = JSON.parse(JSON.stringify(row))
  deviceinfo.value.config = JSON.parse(deviceinfo.value.config)
  infoDialog.value = true
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = proxy.tLang('common', '添加') + ' ' + proxy.tLang('device', '设备信息');
}

//解绑平板设备
function handleUnbind(row) {
  proxy.$modal.confirm(proxy.tLang('tip', '是否确定解绑当前设备？') + ` [${row.id}]`).then(function () {
    return updateDevice({id:row.id,sn:''});
  }).then(() => {
    proxy.$modal.msgSuccess(proxy.tLang('common', '解绑成功'));
      getList();
  }).catch(() => { });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getDevice(id).then(response => {
    form.value = response.data;
    form.value.configList = JSON.parse(form.value.config) || []
    form.value.type = parseInt(form.value.type)
    open.value = true;
    title.value = proxy.tLang('common', '修改') + ' ' + proxy.tLang('device', '设备信息');
  });
}
/** 提交按钮 */
function submitForm() {
  form.value.config = JSON.stringify(form.value.configList)
  if (form.value.id != null) {
    updateDevice(form.value).then(response => {
      proxy.$modal.msgSuccess(proxy.tLang('common', '修改成功'));
      open.value = false;
      getList();
    });
  } else {
    addDevice(form.value).then(response => {
      proxy.$modal.msgSuccess(proxy.tLang('common', '新增成功'));
      open.value = false;
      getList();
    });
  }
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal.confirm(proxy.tLang('tip', '确定删除选中记录？') + ` [${id}]`).then(function () {
    return delDevice(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(proxy.tLang('common', '删除成功'));
  }).catch(() => { });
}
/** 导出按钮操作 */
function handleExport() {
  this.download('casm/device/export', {
    ...queryParams
  }, `device_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getListDeviceType()
})
</script>

<style lang="scss" scoped>
.demo-form-inline :deep(.el-input) {
  --el-input-width: 220px;
}

.demo-form-inlinee :deep(.el-select) {
  --el-select-width: 220px;
}

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