<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      :size="productId ? 'small' : 'default'"
      label-position="left"
      label-width="100px"
    >
      <el-form-item label="固件名称" prop="firmwareName">
        <el-input
          v-model="queryParams.firmwareName"
          clearable
          placeholder="请输入固件名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="!productId" label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          :remote-method="getProductOptions"
          clearable
          filterable
          placeholder="请选择产品"
          remote
          remote-show-suffix
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租户" prop="tenantId">
        <el-select
          v-model="queryParams.tenantId"
          :remote-method="getTenantOptions"
          clearable
          filterable
          remote
          remote-show-suffix
        >
          <el-option
            v-for="item in tenantOptions"
            :key="item.tenantId"
            :label="item.tenantName"
            :value="item.tenantId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否最新版本" prop="latestVersionFlag">
        <el-select
          v-model="queryParams.latestVersionFlag"
          clearable
          placeholder="请选择是否最新版本"
        >
          <el-option :value="1" label="是"></el-option>
          <el-option :value="0" label="否"></el-option>
        </el-select>
      </el-form-item>
      <!--                        <el-form-item label="固件版本" prop="version">-->
      <!--                            <el-input-->
      <!--                                    v-model="queryParams.version"-->
      <!--                                    placeholder="请输入固件版本"-->
      <!--                                    clearable-->
      <!--                                    @keyup.enter="handleQuery"-->
      <!--                            />-->
      <!--                        </el-form-item>-->
      <!--                        <el-form-item label="文件路径" prop="downloadUrl">-->
      <!--                            <el-input-->
      <!--                                    v-model="queryParams.downloadUrl"-->
      <!--                                    placeholder="请输入文件路径"-->
      <!--                                    clearable-->
      <!--                                    @keyup.enter="handleQuery"-->
      <!--                            />-->
      <!--                        </el-form-item>-->
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['product:firmware:add']"
          :size="productId ? 'small' : 'default'"
          icon="Plus"
          plain
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['product:firmware:edit']"
          :disabled="single"
          :size="productId ? 'small' : 'default'"
          icon="Edit"
          plain
          type="success"
          @click="handleUpdate"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['product:firmware:remove']"
          :disabled="multiple"
          :size="productId ? 'small' : 'default'"
          icon="Delete"
          plain
          type="danger"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['product:firmware:export']"
          :size="productId ? 'small' : 'default'"
          icon="Download"
          plain
          type="warning"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :border="!!productId"
      :data="firmwareList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="ID" prop="firmwareId">
      </el-table-column>
      <el-table-column align="center" label="固件名称" prop="firmwareName">
      </el-table-column>
      <el-table-column align="center" label="产品" prop="productId">
        <template #default="{ row }">
          {{
            productOptions.find((el) => el.productId === row.productId)
              ?.productName ?? "暂无"
          }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="租户" prop="tenantId">
        <template #default="{ row }">
          {{
            tenantOptions.find((el) => el.tenantId === row.tenantId)
              ?.tenantName ?? "暂无"
          }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="是否最新版本"
        prop="latestVersionFlag"
      >
        <template #default="{ row }">
          <dict-tag
            :options="firmwareLatestTypeOptions"
            :value="[row.latestVersionFlag]"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="固件版本" prop="version" />
      <el-table-column align="center" label="文件路径" prop="downloadUrl" />
      <el-table-column align="center" label="备注" prop="remark" />
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="scope">
          <el-button
            v-hasPermi="['product:firmware:edit']"
            icon="Edit"
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            v-hasPermi="['product:firmware:remove']"
            icon="Delete"
            link
            type="primary"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改产品固件对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form
        ref="firmwareRef"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="固件名称" prop="firmwareName">
          <el-input v-model="form.firmwareName" placeholder="请输入固件名称" />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="form.productId"
            :disabled="!!productId"
            :remote-method="getProductOptions"
            filterable
            placeholder="请选择产品"
            remote
            remote-show-suffix
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <!--          <el-input v-model="form.tenantId" placeholder="请输入租户ID" />-->
          <el-select
            v-model="form.tenantId"
            :remote-method="getTenantOptions"
            filterable
            remote
            remote-show-suffix
          >
            <el-option
              v-for="item in tenantOptions"
              :key="item.tenantId"
              :label="item.tenantName"
              :value="item.tenantId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否最新版本" prop="latestVersionFlag">
          <!--          <el-input v-model="form.latestVersionFlag" placeholder="请输入是否最新版本" />-->
          <el-switch
            v-model="form.latestVersionFlag"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          ></el-switch>
        </el-form-item>
        <el-form-item label="固件版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入固件版本" />
        </el-form-item>
        <el-form-item label="文件路径" prop="downloadUrl">
          <el-input v-model="form.downloadUrl" placeholder="请输入文件路径" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入内容"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Firmware" setup>
import {
  addFirmware,
  delFirmware,
  getFirmware,
  listFirmware,
  updateFirmware,
} from "@/api/product/firmware";
import { listProduct } from "@/api/product/product";
import { listTenant } from "@/api/system/tenant";
import { firmwareLatestTypeOptions } from "@/constant/dict";
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import DictTag from "@/components/DictTag/index.vue";

const props = defineProps(["productId"]);
const { productId } = toRefs(props);
const { proxy } = getCurrentInstance();

const firmwareList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const productOptions = ref([]);
const tenantOptions = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    firmwareName: null,
    productId: null,
    tenantId: null,
    latestVersionFlag: null,
    version: null,
    downloadUrl: null,
  },
  rules: {
    firmwareName: [
      { required: true, message: "固件名称不能为空", trigger: "blur" },
    ],
    productId: [{ required: true, message: "产品ID不能为空", trigger: "blur" }],
    tenantId: [{ required: true, message: "租户ID不能为空", trigger: "blur" }],
    latestVersionFlag: [
      { required: true, message: "是否最新版本不能为空", trigger: "blur" },
    ],
    version: [{ required: true, message: "固件版本不能为空", trigger: "blur" }],
    downloadUrl: [
      { required: true, message: "文件路径不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品固件列表 */
function getList() {
  loading.value = true;
  if (productId.value) {
    queryParams.value.productId = productId.value;
  }
  listFirmware(queryParams.value).then((response) => {
    firmwareList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    firmwareId: null,
    firmwareName: null,
    productId: null,
    tenantId: null,
    latestVersionFlag: null,
    version: null,
    downloadUrl: null,
    createBy: null,
    createTime: null,
    remark: null,
  };
  proxy.resetForm("firmwareRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  if (productId.value) {
    form.value.productId = productId.value;
  }
  open.value = true;
  title.value = "添加产品固件";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _firmwareId = row.firmwareId || ids.value;
  getFirmware(_firmwareId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改产品固件";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["firmwareRef"].validate((valid) => {
    if (valid) {
      if (form.value.firmwareId != null) {
        updateFirmware(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFirmware(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _firmwareIds = row.firmwareId || ids.value;
  proxy.$modal
    .confirm('是否确认删除产品固件编号为"' + _firmwareIds + '"的数据项？')
    .then(function () {
      return delFirmware(_firmwareIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "product/firmware/export",
    {
      ...queryParams.value,
    },
    `firmware_${new Date().getTime()}.xlsx`
  );
}

function getProductOptions(keyword) {
  listProduct({
    productName: keyword,
    pageNum: 1,
    pageSize: 20,
  }).then((resp) => {
    productOptions.value = resp.rows;
  });
}

const getTenantOptions = async (keyword) => {
  const response = await listTenant({
    pageNum: 1,
    pageSize: 20,
    tenantName: keyword,
  });
  tenantOptions.value = response.rows;
};

getList();
getProductOptions();
getTenantOptions();
</script>
