<template>
  <div class="app-container" ref="appPanel">
    <!-- 工具栏 -->
    <div ref="toolPanel">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            plain
            size="mini"
            @click="handleAdd('1楼二楼全盘')"
          >全盘
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            size="mini"
            @click="handleAdd('1楼全盘')"
          >一楼盘点
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            size="mini"
            @click="handleAdd('2楼全盘')"
          >二楼盘点
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
          >刷新
          </el-button>
        </el-col>
        <right-toolbar v-if="rightToolbarShow" :showSearch.sync="showSearch" @queryTable="getList"
                       showColumnsType="transfer" :columns="columns" :businessCode="businessCodeTrk"
                       :tableNo="tableNo"></right-toolbar>
      </el-row>
    </div>

    <!-- 搜索条件 -->
    <div class="search-container" ref="searchPanel">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="盘点时间" prop="checkTime">
          <el-date-picker clearable
                          v-model="queryParams.checkTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择盘点时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务号" prop="taskNumber">
          <el-input
            v-model="queryParams.taskNumber"
            placeholder="请输入任务号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 主表格 -->
    <div class="table-container">
      <div ref="mainTablePanel" :style="{height: mainTableDivHeight}">
        <el-table v-loading="loading" border size="mini" :height="mainTableHeight" :data="checkList"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="主键" align="center" prop="id" v-if="columns[0].visible"/>
          <el-table-column label="盘点时间" align="center" prop="checkTime" width="180" v-if="columns[1].visible">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" prop="checkType" v-if="columns[2].visible"/>
          <el-table-column label="任务号" align="center" prop="taskNumber" v-if="columns[3].visible"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >查看数据
              </el-button>
            </template>
          </el-table-column>
        </el-table>

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

    <!-- 盘点数据对话框 -->
    <el-dialog title="盘点数据" :visible.sync="outerVisible" width="80%" append-to-body @close="handleDialogClose">
      <div v-loading="stockLoading">
        <el-table
          :data="stockList"
          style="width: 100%"
          border
          size="mini">
          <el-table-column
            prop="goodsName"
            label="物料名称"
            min-width="180"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="goodsId"
            label="物料编号"
            min-width="120"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="ctl"
            label="容器号"
            min-width="100"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="locationId"
            label="库位号"
            min-width="100"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="shelvesNum"
            label="数量"
            min-width="80"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="storageShortName"
            label="仓库"
            min-width="100"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="price"
            label="单价"
            min-width="100"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="totalMoney"
            label="总价"
            min-width="100"
            show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <div class="pagePanel">
          <pagination
            v-show="stockTotal>0"
            :total="stockTotal"
            :page.sync="stockQueryParams.pageNum"
            :limit.sync="stockQueryParams.pageSize"
            @pagination="handleStockPagination"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCheck,
  getCheck,
  delCheck,
  addCheck,
  updateCheck,
  disabled,
  enabled,
  changeStatus,
  listCheckStock,
  pushCheck
} from "@/api/system/check";
import { listCOLUMN } from "@/api/system/column";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "Check",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 盘点数据加载状态
      stockLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点主表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "check",
      rightToolbarShow: false,
      tableNo: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        checkTime: null,
        checkType: null,
        taskNumber: null
      },
      // 盘点数据查询参数
      stockQueryParams: {
        pageNum: 1,
        pageSize: 100,
        checkId: null,
      },
      // 盘点数据总条数
      stockTotal: 0,
      // 盘点数据列表
      stockList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        checkTime: [
          { required: true, message: "盘点时间不能为空", trigger: "blur" }
        ],
        checkType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        taskNumber: [
          { required: true, message: "任务号不能为空", trigger: "blur" }
        ]
      },
      // 列显示控制
      columns: [
        { key: 0, label: `主键`, visible: true, columnName: "id" },
        { key: 1, label: `盘点时间`, visible: true, columnName: "check_time" },
        { key: 2, label: `类型`, visible: true, columnName: "check_type" },
        { key: 3, label: `任务号`, visible: true, columnName: "task_number" },
      ],
      // 盘点数据对话框显示控制
      outerVisible: false,
      // 当前查看的任务号
      currentTaskNumber: null
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.computedTableHeight();
    window.addEventListener('resize', this.computedTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.computedTableHeight);
  },
  watch: {
    'showSearch': function() {
      this.computedTableHeight();
    }
  },
  methods: {
    /** 查询用户展示字段定义管理列表 */
    getHideColumn() {
      const queryHideColumnParams = {
        pageNum: 1,
        pageSize: 100,
        businessCode: this.businessCodeTrk,
        tableNo: this.tableNo
      };
      listCOLUMN(queryHideColumnParams).then(response => {
        if (response.rows.length > 0) {
          const row = response.rows[0];
          const columnHide = row.columnHide.split(",");
          if (columnHide.length > 0) {
            for (let item in this.columns) {
              if (columnHide.indexOf(this.columns[item].columnName) > -1) {
                this.columns[item].visible = false;
              }
            }
          }
        }
        this.rightToolbarShow = true;
      });
    },
    computedTableHeight() {
      this.$nextTick(() => {
        const totalHeight = this.$refs.appPanel.clientHeight;
        const toolHeight = this.$refs.toolPanel.clientHeight;
        const searchHeight = this.$refs.searchPanel.clientHeight;
        const tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;

        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = (tablePanelHeight - 25) + "px";
      });
    },
    /** 查询盘点主列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.getHideColumn();
      });
    },
    /** 查询盘点数据列表 */
    getStockList() {
      this.stockLoading = true;
      const params = {
        ...this.stockQueryParams,
        checkId: this.currentTaskNumber
      };

      listCheckStock(params).then(response => {
        this.stockList = response.rows;
        this.stockTotal = response.total;
        this.stockLoading = false;
      }).catch(() => {
        this.stockLoading = false;
      });
    },
    // 处理盘点数据分页变化
    handleStockPagination(val) {
      this.stockQueryParams.pageNum = val.page;
      this.stockQueryParams.pageSize = val.limit;
      this.getStockList();
    },
    // 处理对话框关闭
    handleDialogClose() {
      this.outerVisible = false;
      this.currentTaskNumber = null;
      this.stockQueryParams.pageNum = 1;
      this.stockList = [];
      this.stockTotal = 0;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        checkTime: null,
        checkType: null,
        taskNumber: 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.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      const params = {
        checkType: type,
      };
      pushCheck(params).then(response => {
        this.$modal.msgSuccess("发送成功");
        this.getList();
      }).catch(error => {
        this.$modal.msgError("发送失败：" + error.message);
      });
    },
    /** 查看数据按钮操作 */
    handleUpdate(row) {
      this.outerVisible = true;
      this.currentTaskNumber = row.taskNumber;
      this.stockQueryParams.pageNum = 1;
      this.getStockList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCheck(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCheck(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除盘点主编号为"' + ids + '"的数据项？').then(function() {
        return delCheck(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '"id为"' + row.id + '"数据项？').then(function() {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认启用盘点主编号为"' + ids + '"的数据项？').then(function() {
        return enabled(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启用成功");
      }).catch(() => {});
    },
    /** 禁用按钮操作 */
    handleDisabled(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认禁用盘点主编号为"' + ids + '"的数据项？').then(function() {
        return disabled(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("禁用成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/check/export', {
        ...this.queryParams
      }, `check_${new Date().getTime()}.xlsx`);
    },
    // 时间格式化
    parseTime
  }
};
</script>

<style scoped>
.app-container {
  height: calc(100vh - 84px);
}

.mb8 {
  margin-bottom: 8px;
}

.table-container {
  margin-top: 8px;
}

.pagePanel {
  margin-top: 8px;
  text-align: right;
}

.edit-container {
  padding: 10px 20px;
}

.dialog-footer {
  text-align: center;
}

.small-padding {
  padding-left: 5px;
  padding-right: 5px;
}

.fixed-width {
  min-width: 100px;
}
</style>
