<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="批次号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批次号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="区别编码" prop="differentCode">
        <el-select
          v-model="queryParams.differentCode"
          style="width: 100%"
          placeholder="请选择区别编码"
        >
          <el-option
            v-for="dict in differentCodeDicts"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="厂商" prop="vendorId">
        <el-select
          v-model="queryParams.vendorId"
          style="width: 100%"
          placeholder="请选择区别编码"
        >
          <el-option
            v-for="dict in queryVendorList"
            :key="dict.vendorId"
            :label="dict.vendorName"
            :value="dict.vendorId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="批次编码" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:batch:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:batch:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:batch:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="batchList"
      @selection-change="handleSelectionChange"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <!-- <el-table-column label="序号" align="center" prop="index" width="50" /> -->
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <!-- <el-table-column
        label="区别编码"
        align="left"
        prop="differentCode"
        :formatter="statusFormat"
      /> -->
      <el-table-column label="厂商" align="left" prop="vendorName" />
      <el-table-column label="批次编码" align="left" prop="batchCode" />
      <el-table-column
        label=" 创建时间"
        align="center"
        prop="createTime"
        sortable="custom"
        width="150px"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:batch:edit']"
            >修改</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:batch:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改硬件数据库对话框 -->
    <div>
      <dialog-template :title="title" :visible="open" @close="open = false" >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          slot="dialog-center"
          label-width="80px"
        >
          <el-form-item label="批次号" prop="batchNumber">
            <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
          </el-form-item>
          <!-- <el-form-item label="区别编码" prop="differentCode">
            <el-select
              v-model="form.differentCode"
              style="width: 100%"
              placeholder="请选择区别编码"
            >
              <el-option
                v-for="dict in differentCodeDicts"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="厂商" prop="vendorId">
            <el-input
              v-model="form.vendorName"
              placeholder="点击选择厂商"
              @focus="openTableSelectDialog()"
            />
          </el-form-item>
        </el-form>
        <div slot="dialog-footer">
          <el-button type="primary" size="mini" @click="submitForm"
            >确 定</el-button
          >
          <el-button size="mini" @click="cancel">取 消</el-button>
        </div>
      </dialog-template>

      <el-dialog
        title="选择"
        :visible.sync="selectTableShow"
        width="75%"
        top="10vh"
        class="select-table-dialog"
        :close-on-click-modal="false"
      >
        <select-table-wrap
          v-if="selectTableShow"
          :tableOption="tableSelectOption.tableOpt"
          :queryOption="tableSelectOption.queryOpt"
          :tableList="tableSelectOption.tableList"
          @parentGetList="childGetList($event)"
          :otherOption="tableSelectOption.otherOption"
          @returnEvent="returnEvent($event)"
        />

        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="resuleClick"
            >确 定</el-button
          >
          <el-button
            size="mini"
            @click="
              () => {
                selectTableShow = false;
              }
            "
            >取 消</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listBatch,
  getBatch,
  delBatch,
  addBatch,
  updateBatch,
  exportBatch,
} from "@/api/iot/batch";
import { listVendor } from "@/api/iot/vendor";
import DialogTemplate from "@/components/DialogTemplate";
import SelectTableWrap from "@/components/SelectTable/index";

export default {
  name: "Batch",
  components: {
    DialogTemplate,
    SelectTableWrap,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备批次号表格数据
      batchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchNumber: null,
        differentCode: null,
        vendorId: null,
        batchCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        batchNumber: [
          { required: true, message: "批次号不能为空", trigger: "blur" },
        ],
        differentCode: [
          { required: true, message: "区别编码不能为空", trigger: "blur" },
        ],
        vendorId: [
          { required: true, message: "厂商主键ID不能为空", trigger: "blur" },
        ],
      },
      selectResult: {},
      tableSelectOption: {},
      selectTableShow: false,
      differentCodeDicts: null,
      queryVendorList: [],
    };
  },
  created() {
    this.getDicts("different_code").then((response) => {
      this.differentCodeDicts = response.data;
    });
    this.getVendor();
    this.getList();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    indexFormatter(val) {
      return val + 1 + ((this.queryParams.pageNum - 1) * this.queryParams.pageSize);
    },
    getVendor() {
      listVendor(
        Object.assign({ selected: 1, pageSize: 99999, pageNum: 1 })
      ).then((response) => {
        this.queryVendorList = response.rows;
      });
    },
    // 菜单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.differentCodeDicts, row.differentCode);
    },
    // 打开厂商选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "vendor",
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            vendorName: "",
            vendorAddress: "",
            vendorContact: "",
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0,
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "厂商名称",
              clearable: true,
              label: "厂商名称",
              type: "input",
              key: "vendorName",
              size: "small",
              value: "",
            },
            {
              style: "",
              placeholder: "厂商地址",
              clearable: true,
              label: "厂商地址",
              type: "input",
              key: "vendorAddress",
              size: "small",
              value: "",
            },
            {
              style: "",
              placeholder: "联系方式",
              clearable: true,
              label: "联系方式",
              type: "input",
              key: "vendorContact",
              size: "small",
              value: "",
            },
          ],
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "厂商名称",
              type: "",
              prop: "vendorName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: " 联系方式",
              type: "",
              prop: "vendorContact",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "厂商地址",
              type: "",
              prop: "vendorAddress",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
          ],
          tableList: {
            type: Array,
          },
        },
        tableList: [],
      };
      this.selectTableShow = true;
    },
    // 查询回调
    childGetList(data) {
      if (data.otherOption.tableType === "vendor") {
        this.vendorChildList(data);
      } else if (data.otherOption.tableType === "product") {
        this.productChildList(data);
      }
    },
    productChildList(data) {
      listProductList(
        Object.assign(data.page, data.param, { selected: 1 })
      ).then((response) => {
        this.tableSelectOption.tableList = response.data;
        // this.tableSelectOption.queryOpt.page.total = Number(response.total);
      });
    },
    vendorChildList(data) {
      listVendor(Object.assign(data.page, data.param, { selected: 1 })).then(
        (response) => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      this.selectResult = {};
      if (data.type === "dblclick") {
        if (data.otherOption.tableType === "vendor") {
          this.form.vendorId = data.value.vendorId;
          this.form.vendorName = data.value.vendorName;
        } else if (data.otherOption.tableType === "product") {
          this.form.prodKey = data.value.prodId;
          this.form.prodSecret = data.value.prodSecret;
        }
        this.$refs.form.validateField('vendorId');
        this.selectTableShow = false;
      } else if (data.type === "click") {
        if (data.otherOption.tableType === "vendor") {
          this.selectResult.vendorId = data.value.vendorId;
          this.selectResult.vendorName = data.value.vendorName;
        } else if (data.otherOption.tableType === "product") {
          this.selectResult.prodKey = data.value.prodId;
          this.selectResult.prodSecret = data.value.prodSecret;
        }
        this.selectResult.tableType = data.otherOption.tableType;
      }
    },
    // 点击确定按钮
    resuleClick() {
      if (this.selectResult.tableType === "vendor") {
        this.form.vendorId = this.selectResult.vendorId;
        this.form.vendorName = this.selectResult.vendorName;
      } else if (this.selectResult.tableType === "product") {
        this.form.prodKey = this.selectResult.prodKey;
        this.form.prodSecret = this.selectResult.prodSecret;
      }
      this.$refs.form.validateField('vendorId');
      this.selectTableShow = false;
    },
    /** 查询设备批次号列表 */
    getList() {
      this.loading = true;
      listBatch(this.queryParams).then((response) => {
        this.batchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        batchId: null,
        batchNumber: null,
        createId: null,
        differentCode: '1',
        createTime: null,
        vendorId: null,
        updateId: null,
        batchCode: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.batchId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备批次号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const batchId = row.batchId || this.ids;
      getBatch(batchId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备批次号";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.batchId != null) {
            updateBatch(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBatch(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const batchIds = row.batchId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delBatch(batchIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有设备批次号数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportBatch(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
