<template>
  <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(['stock: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="goods_vo.name" label="商品名称" />
        <el-table-column prop="goods_vo.category_name" label="商品类别" />
        <el-table-column prop="goods_vo.brand_name" label="品牌" />
        <el-table-column prop="goods_vo.goods_style" label="规格型号" />
        <el-table-column prop="sn_code" label="序列号" />
        <el-table-column label="操作" width="260">
          <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" @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="stockForm.id ? '编辑序列号' : '新增序列号'"
      :visible.sync="dialogVisible"
      width="600px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="header">
        <span>商品编号/条码</span>
        <el-input v-model="stockForm.sn"></el-input>
        <el-button>搜索</el-button>
      </div>
      <div class="center">
        <el-table :data="snTableData" border style="width: 100%" @selection-change="snHandleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="goods_vo.sn" label="商品编号" width="180">
          </el-table-column>
          <el-table-column prop="goods_vo.bar_code" label="商品条码" width="180">
          </el-table-column>
          <el-table-column prop="qty" label="序列号数量"> </el-table-column>

        </el-table>
      </div>
      <!-- <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 v-model="stockForm.qty" placeholder="请输入要生成序列号的数量"></el-input>
        <el-button @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 style="margin-top: 10px;  font-size: 20px; text-align: center;">{{ item }}</div>
          </div>
        </div>
      </div>
    </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:[]
    };
  },
  mounted() {
    this.GET_WarehouseList();
    this.GET_DeptList();
    // this.GET_StationAllList()
    this.GET_AdministratorList();
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    snHandleSelectionChange(val){
      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.dialogVisible = false
      this.codeList=[]
    },
    // 打印
    PrintIng(row){
      this.PrintVisible=true
      this.codeList.push(row.sn_code)
    },
    // 删除
    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.addSave({goods_id:this.snMultipleSelection[0].goods_id,
          qty: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.snTableData=this.tableData.data
      this.dialogVisible = true;
    },

    /** 编辑仓库 */
    handleEditWarehouse(index, row) {
      this.snTableData[0]=row
      console.log( this.snTableData);
      this.stockForm = this.MixinClone(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,
        keyword: data,
      };
      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;
        });
    },
  },
};
</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;
}
</style>
