<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(['goodsLend:add'])" type="primary"
            @click="handleAddGoodsLend">新增</el-button>
          <!-- <el-button size="mini" v-if="checkPermission(['goodsLend:del'])" @click="handleDeleteGoodsLend()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button> -->
          <el-button type="success" size="mini" v-if="checkPermission(['goodsLend:confirm'])"
            @click="handleConfirmGoodsLend" :disabled="multipleSelection.length === 0">打印</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入借出单编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="仓库">
                  <el-cascader v-model="advancedForm.dept_id" :options="warehouseList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true,
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status" clearable>
                    <el-option key="NEW" label="新创建" value="NEW" />
                    <el-option key="CONFIRMED" label="已确认" value="CONFIRMED" />
                    <el-option key="RETURNED" label="已归还" value="RETURNED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.goodsLend_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="true" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{
                      disabledDate(time) {
                        return (
                          time.getTime() - 1 >=
                          new Date(
                            new Date().getFullYear(),
                            new Date().getMonth(),
                            new Date().getDate()
                          ).getTime() +
                          86400000 -
                          1
                        );
                      },
                      shortcuts: MixinPickerShortcuts,
                    }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouse.sn" label="仓库编号">
          <!-- <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['goodsLend'])"
              style="color: #409eff;"
              :to="{ name: 'goodsLendDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template> -->
        </el-table-column>
        <el-table-column prop="warehouse.name" label="仓库名称">
          <!-- <template slot-scope="scope">{{ scope.row.lend_time | unixToDate }}</template> -->
        </el-table-column>
        <el-table-column prop="code" label="库位号" />
        <el-table-column prop="type" label="库位区域">
          <template slot-scope="scope">{{
            statusFilter(scope.row.type)
            }}</template>
        </el-table-column>
        <el-table-column prop="bind_num" label="已绑定SKU数" />
        <!-- <el-table-column prop="intro" label="库位说明" />
       <el-table-column prop="lend_person" label="借出人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column> -->
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['inventoryItem'])"
              @click="introGoodsLend(scope.row)">查看</el-button>
            <el-button size="mini" v-if="checkPermission(['bindAreaStock:update'])"
              @click="AddGoodsLend(scope.row)">绑定商品</el-button>
            <el-button size="mini" v-if="checkPermission(['goodsLend:edit'])"
              @click="handleEditGoodsLend(scope.row)">编辑</el-button>
            <el-button type="success" size="mini" style="margin-top: 5px;" v-if="checkPermission(['goodsLend:del'])"
              @click="handleReturnGoodsLend(scope.row)">删除</el-button>
            <!-- v-if="checkPermission(['goodsLend:print'])" -->
            <el-button type="primary" size="mini" style="margin-top: 5px;" @click="handlePrintGoodsLendDialog(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="打印预览" :visible.sync="dialogVisible" 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> -->
            <barcode :value="item" height="20" format="CODE128" fontSize="20"></barcode>
            <!--  <h1
              class="qrcode-title"
              style="
                margin-top: 20px;
                font-family: sans-serif;
                color: black;
                font-weight: 600;
              "
            >
              {{ item }}
            </h1> -->
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogVisibleForm" width="940px" center @close="addHandleCancle">
      <el-form ref="addLendForm" :model="addLendForm" :rules="rules" label-width="90px">
        <!-- <el-form-item label="仓库编号" prop="code">
            <el-input v-model="addLendForm.code" placeholder="请输入仓库编号"></el-input>
          </el-form-item>
          <el-form-item label="仓库名称" prop="name">
            <el-input v-model="addLendForm.name" placeholder="请输入仓库名称"></el-input>
          </el-form-item> -->
        <el-form-item label="仓库" prop="warehouse_id">
          <el-select v-model="addLendForm.warehouse_id" clearable @change="selWarehouse">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <span style="
              color: red;
              margin-left: 20px;
              cursor: pointer;
              text-decoration: underline;
            " v-if="warehouseList.length == 0" @click="gowareHouse">新增仓库</span>
        </el-form-item>
        <el-form-item label="库位区域" prop="type">
          <el-select v-model="addLendForm.type" clearable @change="selAreaTableData">
            <el-option v-for="item in AreaTableData" :key="item.id" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="库位号" prop="code">
          <el-input v-model="addLendForm.code" maxlength="12" placeholder="请输入库位号" style="width: 270px">
            <template slot="prepend">{{ warehouseSn }}-{{ AreaTab }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库位说明">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
            v-model="addLendForm.intro">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addHandleCancle">取 消</el-button>
        <el-button type="primary" @click="lendCommit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsLend from "@/api/goodsLend";
import Print from "print-js";
import * as API_Setting from "@/api/setting";
import { Foundation } from "~/ui-utils";
import QRCode from "qrcodejs2";
export default {
  name: "goodsLend",
  data() {
    return {
      warehouseSn: "",
      warehouseList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: "",
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsLendForm: {},
      codeList: [],
      title: "",
      dialogVisibleForm: false,
      // 新增数据
      addLendForm: {},
      rules: {
        warehouse_id: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
        name: [
          { required: true, message: "请选择输入仓库名称", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请选择输入库位号", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择仓库类型", trigger: "change" },
        ],
      },
      typeList: [],
      AreaTableData: [],
      AreaTab: ''
    };
  },
  mounted() {
    this.GET_GoodsLendList();
    this.GET_DeptList();
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.query.status) {
          this.params.status = newVal.query.status;
          this.advancedForm.status = newVal.query.status;
        }
        this.params.page_no = 1;
        this.GET_GoodsLendList();
      },
    },
  },
  methods: {
    //查看已选中商品
    introGoodsLend(row) {
      /* API_GoodsLend.getInfo({id:row.warehouse_id}).then(res=>{
        console.log(res);
      }) */
      this.$router.push({
        name: "inventoryItem",
        params: {
          id: row.id,
          type: 'check',
          code: row.code
        },
      });
    },
    AddGoodsLend(row) {
      this.$router.push({
        name: "bindAreaStock",
        params: {
          id: row.id,
          warehouse_id: row.warehouse_id,
          code: row.code
        },
      });
    },
    gowareHouse() {
      this.dialogVisibleForm = false;
      this.$router.push({ name: "warehouseList" });
    },
    /* 选中仓库 */
    selWarehouse(val) {
      const list = this.warehouseList.filter((el) => {
        return el.id === val;
      });
      let obj = list[0];
      this.warehouseSn = obj.sn;
    },
    selAreaTableData(val) {
      const list = this.AreaTableData.filter((el) => {
        return el.code === val;
      });
      let obj = list[0];
      console.log(list[0]);
      this.AreaTab = obj.code;
    },
    // 确认提交
    lendCommit() {
      this.$refs.addLendForm.validate((valid) => {
        if (valid) {
          if (this.title === "新增") {
            this.addLendForm.code =
              this.warehouseSn + this.addLendForm.type + "-" + this.addLendForm.code;
            API_GoodsLend.create(this.addLendForm).then((res) => {
              this.$message.success("添加成功!");
              this.dialogVisibleForm = false;
              this.warehouseSn = "";
              this.addLendForm = {};
              this.GET_GoodsLendList();
            });
          } else if (this.title === "编辑") {
            this.addLendForm.code =
              this.warehouseSn + this.addLendForm.type + "-" + this.addLendForm.code;
            API_GoodsLend.update(this.addLendForm).then((res) => {
              this.$message.success("修改成功!");
              this.dialogVisibleForm = false;
              this.addLendForm = {};
              this.GET_GoodsLendList();
            });
          }
        } else {
          this.$message.error("提交失败");
          return false;
        }
      });
    },
    addHandleCancle() {
      this.dialogVisibleForm = false;
      /* this.addLendForm = {}; */
    },
    handleCancle() {
      this.dialogVisible = false;
      this.codeList = [];
    },
    // 二维码生成
    creatQrCode() {
      this.$nextTick(() => {
        this.codeList.forEach((item, index) => {
          this.$refs.codeItem[index].innerHTML = "";
          var qrcode = new QRCode(this.$refs.codeItem[index], {
            text: item, //二维码内容
            width: 600,
            height: 660,
            render: "table",
            colorDark: "#333333", //二维码颜色
            colorLight: "#ffffff", //二维码背景色
            correctLevel: QRCode.CorrectLevel.H,
          });
        });
      }, 500);
    },
    handleEditGoodsLend(row) {
      this.title = "编辑";
      const str = row.code;
      //row.code = str.split('-').pop();
      this.warehouseSn=str.split('-')[0]
      this.AreaTab=str.split('-')[1]
      this.addLendForm = this.MixinClone(row);
      this.addLendForm.code= str.split('-').pop();
      this.dialogVisibleForm = true;
      // this.$router.push({ name: 'goodsLendEdit', params: { id: row.id }})
    },
    handleReturnGoodsLend(row) {
      this.$confirm("确定要删除吗？", "提示", { type: "warning" })
        .then(() => {
          API_GoodsLend.deletes({ id: row.id }).then(() => {
            this.$message.success("删除成功！");
            this.GET_GoodsLendList();
          });
        })
        .catch(() => { });
    },
    /** 状态 */
    statusFilter(val) {
      const obj = this.AreaTableData.filter((el) => {
        return el.code === val;
      });
      if (obj.length !== 0) {
        return obj[0].name;
      } else {
        return "";
      }
    },
    handleConfirmGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length)
        return this.$message.error("请先选择！");
      const ids = this.multipleSelection.map((item) => item.code);
      this.codeList = ids;
      this.dialogVisible = true;
      this.creatQrCode();
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getListAll().then((response) => {
        this.warehouseList = response;
        console.log(response);
      });
      API_Setting.getPage({
        dictType: "Warehouse_location_type",
        page_no: 1,
        page_size: 50,
      }).then((res) => {
        this.typeList = res.data;
      });
      API_GoodsLend.getListAreaType().then(response => {
        this.loading = false
        this.AreaTableData = response
      }).catch(() => { this.loading = false })
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      Print({
        printable: "deliverySheet",
        type: "html",
        targetStyles: ["*"],
        //style: 'body, html {font-size:300px !important;color:red;}', // 确保打印时应用这个样式
        ignoreElements: ["no-logs", "goods-image", "no-btn", "elementToIgnore"],
      });
    },
    handleDeleteGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length)
        return this.$message.error("请先选择！");
      this.$confirm("确定要删除这些借出单吗？", "提示", { type: "warning" })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          API_GoodsLend.deleteGoodsLend(ids).then(() => {
            this.$message.success("删除成功！");
            this.GET_GoodsLendList();
          });
        })
        .catch(() => { });
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_GoodsLendList();
    },

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

    /** 添加调整单 */
    handleAddGoodsLend() {
      this.title = "新增";
      this.dialogVisibleForm = true;
      // this.$router.push({ name: 'goodsLendAdd'})
    },
    /** 打印调整单 */
    handlePrintGoodsLendDialog(row) {
      // this.GET_GoodsLendDetail(row.id)
      this.dialogVisible = true;
      this.codeList.push(row.code);
      this.creatQrCode();
    },
    /** 获取调整单详情页面数据 */
    GET_GoodsLendDetail(id) {
      API_GoodsLend.getGoodsLendInfo(id).then((response) => {
        this.goodsLendForm = response;
        if (response.product_list && response.product_list.length) {
          var str = "";
          response.product_list.forEach(function (i) {
            str += i.product_name + "、";
          });
        }
        // 生成库位号二维码
        this.goodsLendForm.illustrate = str;
      });
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data,
      };
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key]);
      this.params.page_no = 1;
      this.GET_GoodsLendList();
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm,
      };
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.goodsLend_time_range) {
        this.params.start_time = parseInt(
          Number(this.advancedForm.goodsLend_time_range[0]) / 1000
        );
        this.params.end_time = parseInt(
          Number(this.advancedForm.goodsLend_time_range[1]) / 1000
        );
      }
      delete this.params.goodsLend_time_range;
      this.params.page_no = 1;
      this.GET_GoodsLendList();
    },
    /** 获取调整单列表 */
    GET_GoodsLendList() {
      this.loading = true;
      API_GoodsLend.query(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;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    // text-align: left;
    //padding-left: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
}

.tips-f {
  padding: 20px 0;
}

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

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

/deep/.el-form {
  .el-form-item__content {
    display: flex;
  }
}

/* @media print {
  html, body {
    font-size: 60pt !important;
    color: red;
  }
} */
</style>
