<template>
  <div>
    <div class="search">
      <el-form ref="advancedForm" :model="advancedForm" label-width="160px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="sku">
              <el-input v-model="advancedForm.sku" placeholder="请输入内容" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="advancedForm.status" clearable>
                <el-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- <el-form-item label="出入库">
              <el-select v-model="advancedForm.status">
                <el-option key="WAIT" label="出库" value="WAIT" />
                <el-option key="NEW" label="入库" value="NEW" />
              </el-select>
            </el-form-item> -->
          </el-col>
        </el-row>
      </el-form>
      <el-button @click="searchEvent"> 搜索 </el-button>
    </div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['createSnCode:add'])" type="primary"
            @click="handleAddWarehouse">新增</el-button>
          <!--  <el-button
            size="mini"
            type="delect"
            :disabled="multipleSelection.length === 0"
            @click="handleDelectWarehous"
            >删除</el-button
          > -->
          <el-button size="mini" type="primary" :disabled="multipleSelection.length === 0"
            @click="batchPrint">批量打印</el-button>
        </div>
        <!--
        <div class="toolbar-search" style="display: flex; align-items: center">

          <span>商品编号/条码：</span>
          <en-table-search
            @search="searchEvent"
            placeholder="请输入关键字搜索"
          />
        </div> -->
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="goods_vo.sn" label="商品编号" />
        <!-- <el-table-column prop="inventory_id" label="盘点单ID">
        </el-table-column> -->
        <el-table-column prop="inventory_id" label="所在仓库">
          <template slot-scope="scope">
            {{ warehouseName(scope.row.warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="goods_vo.name" label="商品名称" />
        <el-table-column prop="product_vo.spec_name" label="规格型号" />
        <el-table-column prop="sku" label="sku" />
        <el-table-column prop="sn_code" label="序列号" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ typeName(scope.row.status) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="out_house_id" label="出库单编号" />
        <el-table-column prop="entry_house_id" label="入库单编号" /> -->
        <el-table-column label="操作" width="310">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['stock:edit'])"
              @click="handleEditWarehouse(scope.$index, scope.row)">查看</el-button>
            <!-- <el-button
              size="mini"
              v-if="checkPermission(['stock:del'])"
              type="danger"
              @click="handleDeleteWarehouse(scope.$index, scope.row)"
              >删除</el-button
            > -->
            <el-button size="mini" v-if="checkPermission(['updateSnCode:update'])"
              @click="editPrintIng(scope.row)">编辑序列号</el-button>
            <el-button size="mini" @click="PrintIng(scope.row)">打印序列号</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" @open="handleDialogOpen"
      :modal-append-to-body="false" :close-on-click-modal="false" :close-on-press-escape="false" @close="close">
      <div class="header">
        <span>商品编号/sku</span>
        <el-input v-model="stockForm.sn"></el-input>
        <el-button>搜索</el-button>
      </div>
      <div class="center">
        <el-table :data="snTableData.records" border ref="table" style="width: 100%"
          @selection-change="snHandleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="goods_vo.sn" label="商品编号">
          </el-table-column>
          <el-table-column prop="goods_vo.name" label="商品名称" />
          <el-table-column prop="sku" label="sku" v-if="title !== '查看序列号'">
          </el-table-column>
          <el-table-column prop="product_vo.sku" label="sku" v-else>
          </el-table-column>
          <el-table-column prop="spec_name" label="规格型号" v-if="title !== '查看序列号'">
          </el-table-column>
          <el-table-column prop="product_vo.spec_name" label="规格型号" v-else>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination @size-change="goodsPageSizeChange" @current-change="goodsPageCurrentChange"
        :current-page="snTableData.current" :page-sizes="[10, 20, 50, 100]" :page-size="snTableData.size"
        layout="total, sizes, prev, pager, next, jumper" :total="snTableData.total"></el-pagination>
      <!-- <el-form :model="stockForm" :rules="stockRules" ref="stockForm" label-width="120px">
        <el-form-item label="商品编码/条码">
          <span>
            <el-input v-model="stockForm.sn"></el-input><el-button>搜索</el-button>
          </span>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="stockForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入仓库名称"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="stockForm.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
            placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form> -->
      <div class="dialog-footer">
        <el-input :disabled="title == '查看序列号'" v-model="stockForm.qty" placeholder="请输入要生成序列号的数量"></el-input>
        <el-button :disabled="title == '查看序列号'" @click="saveQ">生成</el-button>
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitWarehouseForm">确 定</el-button> -->
      </div>
      <div class="info">
        <p>生成规则：序号号=商品编号+4位规格编码+当前生成时间+4位自然序号</p>
        <p>
          注意：如果没有规格的商品默认规格编码就是0000,单次生成数量不得超过9999
        </p>
      </div>
    </el-dialog>
    <el-dialog title="打印预览" :visible.sync="PrintVisible" width="940px" center @close="handleCancle">
      <el-button size="mini" type="primary" @click="handlePrintGoodsLend" class="print">打印</el-button>
      <div id="deliverySheet" style="width: 900px">
        <div class="tips-t" v-for="(item, index) in codeList" :key="index">
          <div>
            <!-- <div class="qrcode-pic" ref="codeItem" ></div> -->
            <div class="numOrder">

            </div>
            <div  style="margin-top: 10px; font-size: 20px; text-align: center">
              <barcode :value="item" format="CODE128" height="65" width="1"></barcode>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="修改序列号" :visible.sync="SKUVisible" width="30%" center @close="snCodeCancle">
      <el-form ref="SKUForm" :model="SKUForm" :rules="SKUFormRule" label-width="160px" inline class="change-form">
        <el-form-item label="序列号" prop="snCode" class="change-form-item">
          <el-input v-model="SKUForm.snCode" placeholder="请输入" style="width: 300px;"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="snCodeCancle">取消</el-button>
        <el-button @click="snCodeEdit">修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_Setting from "@/api/setting";
import * as API_Auth from "@/api/auth";
import { Foundation } from "~/ui-utils";
import { mapGetters } from "vuex";
import Print from "print-js";
export default {
  name: "warehouse",
  data() {
    return {
      deptList: [],
      adminList: [],
      // postList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
      },
      // 列表数据
      tableData: "",
      // 仓库表单
      stockForm: {
        qty: 0,
      },
      // 仓库表单 规则
      stockRules: {
        sn: [{ required: true, message: "请输入仓库编号", trigger: "blur" }],
        name: [
          { required: true, message: "请选择输入仓库名称", trigger: "blur" },
        ],
      },
      // 仓库表单 dialog
      dialogVisible: false,
      snTableData: [],
      // 当前已选择的行
      multipleSelection: [],
      PrintVisible: false,
      codeList: [],
      // 新增窗口选中的值
      snMultipleSelection: [],
      title: "",
      statusList: [],
      // 高级搜索数据
      advancedForm: {},
      barcodeValue: "",
      SKUForm: {
        snCode: '',
        id: ''
      },
      SKUFormRule: {
        snCode: [{
          required: true,
          message: '请输入序列号',
          trigger: 'blur'
        }
        ],
      },
      SKUVisible: false,
      warehouseList: '',
    };
  },
  mounted() {
    this.GET_WarehouseList();
    this.GET_DeptList();
    // this.GET_StationAllList()
    this.GET_AdministratorList();
  },
  watch: {

  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    warehouseName(val) {
      let name = ''
      this.warehouseList.map((el) => {
        if (el.id == val) {
          return name = el.name
        }
      });
      return name
    },
    snCodeCancle() {
      this.SKUForm.id = ""
      this.SKUForm.snCode = ""
      this.SKUVisible = false
    },
    snCodeEdit() {
      API_Setting.updateSnCode(this.SKUForm.id, this.SKUForm.snCode).then(res => {
        this.$message.success('修改成功!')
        this.SKUForm.id = ""
        this.SKUForm.snCode = ""
        this.SKUVisible = false
        this.GET_WarehouseList();
      })
    },
    editPrintIng(row) {
      this.SKUForm.id = row.id
      this.SKUForm.snCode = row.sn_code
      this.SKUVisible = true
    },
    /* 分页 */
    goodsPageSizeChange(size) {
      this.params.page_size = size;
      API_Setting.getSnProduct(this.params).then((res) => {
        this.snTableData = res; //this.tableData.data
      });
    },
    goodsPageCurrentChange(page) {
      this.params.page_no = page;
      API_Setting.getSnProduct(this.params).then((res) => {
        this.snTableData = res; //this.tableData.data

      });

    },
    typeName(val) {
      let name = "";
      this.statusList.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    close() {
      this.dialogVisible = false;
      this.snTableData = [];
    },
    snHandleSelectionChange(val) {
      if (val.length > 1) {
        // 如果当前选中数量超过1，移除先前选中的，保留最后选中的
        const lastSelected = val[val.length - 1];
        this.$refs.table.clearSelection(); // 清除所有选中
        this.$refs.table.toggleRowSelection(lastSelected, true); // 重新选中最后一个
      }
      this.snMultipleSelection = val; // 更新当前选中的行
    },
    // 批量打印
    batchPrint() {
      const ids = this.multipleSelection.map((item) => item.sn_code);
      this.codeList = ids;
      this.PrintVisible = true;
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      Print({
        printable: "deliverySheet",
        type: "html",
        targetStyles: ["*"],
        ignoreElements: ["no-logs", "goods-image", "no-btn"],
      });
    },
    handleCancle() {
      this.PrintVisible = false;
      this.codeList = [];
    },
    // 打印
    PrintIng(row) {
      this.barcodeValue = row.sn_code;
      this.$nextTick(() => {
        this.codeList.push(row.sn_code);
        this.PrintVisible = true;
      });
    },
    // 删除
    handleDelectWarehous() {
      /*  if (!this.multipleSelection || !this.multipleSelection.length)
        return this.$message.error("请先选择！");
      this.$confirm("确定要删除这些吗？", "提示", { type: "warning" })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          API_Setting.deleteSn(ids).then(() => {
            this.$message.success("删除成功！");
            this.GET_WarehouseList();
          });
        })
        .catch(() => {}); */
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 生成序列号
    saveQ() {
      // if (!this.snMultipleSelection || !this.snMultipleSelection.length)
      API_Setting.addCreateSnCode({
        product_id: this.snMultipleSelection[0].id,
        num: Number(this.stockForm.qty),
      }).then((res) => {
        this.dialogVisible = false;
        this.snTableData = [];
        this.GET_WarehouseList();
      });
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0,
      }).then((response) => {
        this.adminList = response.data;
      });
    },
    // /** 获取岗位 */
    // GET_StationAllList() {
    //   API_Setting.getStationAllList().then(response => {
    //     this.postList = response
    //   })
    // },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
      });
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_WarehouseList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_WarehouseList();
    },

    /** 添加仓库 */
    handleAddWarehouse() {
      /* this.stockForm = {
        dept_id: 0,
        admin_id: this.user.uid,
      }; */
      this.title = "新增序列号";
      API_Setting.getSnProduct(this.params).then((res) => {
        this.snTableData = res; //this.tableData.data
        this.dialogVisible = true;
      });
    },

    /** 编辑仓库 */
    handleEditWarehouse(index, row) {
      this.title = "查看序列号";
      this.snTableData.push(row);
      this.dialogVisible = true;
    },

    /** 删除 */
    handleDeleteWarehouse(index, row) {
      /*  this.$confirm("确定要删除这个仓库吗？", "提示", { type: "warning" })
        .then(() => {
          API_Setting.deleteSn(row.id).then(() => {
            this.$message.success("删除成功！");
            this.GET_WarehouseList();
          });
        })
        .catch(() => {}); */
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => {
        this.$refs["stockForm"].clearValidate();
      });
    },

    /** 提交仓库表单 */
    submitWarehouseForm() {
      this.$refs["stockForm"].validate((valid) => {
        if (valid) {
          const { id } = this.stockForm;
          const params = this.MixinClone(this.stockForm);
          if (!params.real_name) delete params.real_name;
          params.role_id === "超级仓库" ? (params.role_id = 0) : null;
          delete params.admin_name;
          if (id) {
            API_BasicSetting.editWarehouse(id, params).then((response) => {
              this.dialogVisible = false;
              this.$message.success("修改成功！");
              this.GET_WarehouseList();
            });
          } else {
            API_BasicSetting.addWarehouse(params).then(() => {
              this.dialogVisible = false;
              this.$message.success("添加成功！");
              this.GET_WarehouseList();
            });
          }
        } else {
          this.$message.error("表单填写有误，请核对！");
          return false;
        }
      });
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        ...this.advancedForm,
      };
      this.params.page_no = 1;
      this.GET_WarehouseList();
    },

    /** 获取序列号列表 */
    GET_WarehouseList() {
      this.loading = true;
      API_Setting.getDictSn(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
      API_Setting.getPage({ dictType: "sn_code_status" }).then((res) => {
        this.statusList = res.data;
      });
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.header {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-input {
    width: 200px;
    margin: 15px;
  }
}

.dialog-footer {
  margin-top: 30px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;

  .el-input {
    width: 200px;
    margin-right: 15px;
  }
}

.info {
  text-align: center;
  color: #aaaaaa;
}

.search {
  display: flex;
  align-items: center;
  background: #fff;
  overflow: hidden;
  padding: 30px 10px 10px 10px;

  /deep/ .el-form-item {
    .el-form-item__content {
      .el-input {
        width: 200px;
      }
    }
  }

  .el-button {
    margin-top: -19px;
    margin-left: 20px;
  }
}

.numOrder {
  display: flex;
  justify-content: center;
}
</style>
