<template>
  <div>
    <div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="出库明细" name="first"></el-tab-pane>
        <el-tab-pane label="入库明细" name="second"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="btn">
      <!-- <el-button type="primary" @click="getExport()">导 出</el-button> -->
    </div>
    <div class="search">
      <el-form ref="advancedForm" :model="advancedForm" label-width="160px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="出入时间">
              <el-date-picker
                v-model="advancedForm.goodsExchange_time_range"
                type="daterange"
                align="center"
                :editable="false"
                unlink-panels
                :clearable="false"
                :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-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-select v-model="advancedForm.warehouse_id">
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </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="advancedSearchEvent"> 搜索 </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(['goodsExchange:add']) && activeName == 'second'
            "
            type="primary"
            @click="handleAddGoodsExchange"
            >新增入库</el-button
          >
          <el-button
            size="mini"
            v-if="
              checkPermission(['goodsExchange:add']) && activeName == 'first'
            "
            type="primary"
            @click="handleShiftGoodsExchange"
            >新增出库</el-button
          >
          <el-button
            v-if="checkPermission(['goodsExchange:del'])"
            size="mini"
            @click="handleDeleteGoodsExchange()"
            type="danger"
            :disabled="multipleSelection.length === 0"
            >删除</el-button
          >
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-if="activeName == 'first'"
          prop="sn"
          label="出库单号"
        >
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column v-else prop="sn" label="入库单号">
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="仓库名称" />

        <el-table-column prop="order_id" label="订单编号" />
        <!--  <el-table-column v-if="activeName=='first'" prop="warehouse_name" label="出库">
           <template slot-scope="scope">{{
            scope.row.change_time | unixToDate
          }}</template>
        </el-table-column>
        <el-table-column v-else prop="warehouse_name" label="入库">
        </el-table-column>-->
       <!-- <el-table-column prop="goods_name" label="商品名称" />
         <el-table-column prop="goods_sn" label="商品编号" />
         <el-table-column prop="goods_category" label="商品类别" />
        <el-table-column prop="goods_sn" label="规格型号" />
        <el-table-column prop="qty" label="库存数量" /> -->
        <el-table-column prop="memo" label="备注" />
        <!-- <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column> -->
        <el-table-column label="操作" width="450">
          <template slot-scope="scope">
            <el-button
              type="success"
              size="mini"
              @click="handleAuditGoodsExchange(scope.row)"
              >查看</el-button
            >
            <el-button
              size="mini"
              @click="handleEditGoodsExchange(scope.row)"
              >编辑</el-button
            >
            <!-- <el-button v-if="scope.row.allowable.allow_submit && checkPermission(['goodsExchange:submit'])" type="success"
              size="mini" @click="handleSubmitGoodsExchange(scope.row)">提交</el-button>
            <el-button v-if="scope.row.allowable.allow_cancel && checkPermission(['goodsExchange:withdraw'])" type="danger"
              size="mini" @click="handleCancelGoodsExchange(scope.row)">撤回</el-button>

            <el-button v-if="checkPermission(['goodsExchange:print'])" type="primary" size="mini"
              @click="handlePrintGoodsExchangeDialog(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
    >
      <el-button
        size="mini"
        type="primary"
        @click="handlePrintGoodsExchange"
        class="print"
        >打印</el-button
      >
      <div id="deliverySheet" style="width: 811px">
        <div class="tips-t">
          <div>换货单号:{{ goodsExchangeForm.sn }}</div>
          <div>
            换货时间:{{ goodsExchangeForm.change_time | unixToDateStr }}
          </div>
          <div>仓库:{{ goodsExchangeForm.warehouse_name }}</div>
        </div>
        <div class="tips-t">
          <div>所属部门:{{ goodsExchangeForm.dept_name }}</div>
          <div>登记人:{{ goodsExchangeForm.handled_by }}</div>
          <div>审核人:{{ goodsExchangeForm.change_person }}</div>
        </div>
        <div class="tips-t">
          <div>换货说明:{{ goodsExchangeForm.change_desc }}</div>
          <div></div>
          <div></div>
        </div>
        <div class="mx">
          <h3>换货商品明细</h3>
        </div>
        <el-table
          :data="goodsExchangeForm.change_list"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="批次编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.stock_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="160">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="170">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="换货数量" width="90">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column label="换货金额" width="90">
            <template slot-scope="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>
        </el-table>
        <div class="mx">
          <h3>退货商品明细</h3>
        </div>
        <el-table
          :data="goodsExchangeForm.return_list"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="批次编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.stock_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="150">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="160">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="170">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="换货数量" width="90">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column label="换货金额" width="90">
            <template slot-scope="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsExchange from "@/api/goodsExchange";
import Print from "print-js";
import * as API_Setting from "@/api/setting";
import { Foundation } from "~/ui-utils";
import * as API_BasicSetting from "@/api/basicSetting";
export default {
  name: "goodsExchange",
  data() {
    return {
      warehouseList: [],
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: "",
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsExchangeForm: {},
      activeName: "first",
    };
  },
  mounted() {
    if(this.activeName=='first'){
      this.GET_GoodsExchangeList();
    }else{
      this.GET_WarehouseEntry()
    }
    this.GET_DeptList();
    this.GET_WarehouseList();
  },
  watch: {
    $route: function ({ query }) {
      this.params.page_no = 1;
      if(this.activeName=='first'){
      this.GET_GoodsExchangeList();
      }else{
        this.GET_WarehouseEntry()
      }
    },
  },
  methods: {
    handleClick(tab, event) {
      this.activeName = tab.name;
      if (tab.name == "first") {
        this.GET_GoodsExchangeList();
      } else {
        this.GET_WarehouseEntry();
      }
    },
    getExport() {
      // API_GoodsExchange.getGoodsExport().then(res=>{
      //   console.log(res);
      // })
    },
    /** 状态 */
    statusFilter(val) {
      switch (val) {
        case "WAIT":
          return "待审核";
        case "NEW":
          return "新创建";
        case "CONFIRMED":
          return "已确认";
        case "RETURNED":
          return "已归还";
        case "COMPLETE":
          return "已完成";
        case "PASS":
          return "审核通过";
        case "REJECT":
          return "审核拒绝";
        default:
          return "";
      }
    },
    /** 编辑 */
    handleEditGoodsExchange(row) {
      if (this.activeName == "first") {
        this.$router.push({
        name: "goodsExchangeEdit",
        params: { id: row.id },
      });
      }else{
        this.$router.push({
        name: "editInventory",
        params: { id: row.id },
      });
      }

    },
    /** 提交审核 */
    handleSubmitGoodsExchange(row) {
      API_GoodsExchange.submitAuditGoodsExchange(row.id).then(() => {
        this.$message.success("提交成功！");
        this.GET_GoodsExchangeList();
      });
    },
    /** 撤回审核 */
    handleCancelGoodsExchange(row) {
      API_GoodsExchange.cancelGoodsExchange(row.id).then(() => {
        this.$message.success("撤回成功！");
        this.GET_GoodsExchangeList();
      });
    },
    handleAuditGoodsExchange(row) {
      if (this.activeName == "first") {
        this.$router.push({
          name: "checkInventory",
          params: {
            id: row.id,
            type: this.activeName,
          },
        });
      }else{//auditInventory
        this.$router.push({
          name: "checkInventory",
          params: {
            id: row.id,
            type: this.activeName,
          },
        });
      }

    },
    /** 获取仓库 */
    GET_WarehouseList() {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
      });
    },
    /** 打印对账详情 */
    handlePrintGoodsExchange() {
      Print({
        printable: "deliverySheet",
        type: "html",
        targetStyles: ["*"],
        ignoreElements: ["no-logs", "goods-image", "no-btn"],
      });
    },
    handleDeleteGoodsExchange() {
      if (!this.multipleSelection || !this.multipleSelection.length)
        return this.$message.error("请先选择！");
      this.$confirm("确定要删除这些换货单吗？", "提示", { type: "warning" })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          API_GoodsExchange.deleteGoodsExchange(ids).then(() => {
            this.$message.success("删除成功！");
            this.GET_GoodsExchangeList();
          });
        })
        .catch(() => {});
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      console.log("val=-", val);
      this.multipleSelection = val;
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_GoodsExchangeList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_GoodsExchangeList();
    },
    // 新增出库
    handleShiftGoodsExchange() {
      this.$router.push({
        name: "goodsExchangeAdd",
        params: { callback: this.GET_GoodsExchangeList, type: "first" },
      });
    },
    /** 新增入库 */
    handleAddGoodsExchange() {
      this.$router.push({
        name: "addInventory",
        params: { callback: this.GET_GoodsExchangeList, type: "second" },
      });
    },
    /** 打印换货单 */
    handlePrintGoodsExchangeDialog(row) {
      this.GET_GoodsExchangeDetail(row.id);
    },
    /** 获取换货单详情页面数据 */
    GET_GoodsExchangeDetail(id) {
      API_GoodsExchange.getGoodsExchangeInfo(id).then((response) => {
        this.goodsExchangeForm = response;
        if (response.change_list && response.change_list.length) {
          var str = "";
          response.change_list.forEach(function (i) {
            str += i.product_name + "、";
          });
        }
        this.goodsExchangeForm.illustrate = str;
        this.dialogVisible = true;
      });
    },
    /** 搜索事件触发 */
    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_GoodsExchangeList();
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm,
      };
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.goodsExchange_time_range) {
        this.params.start_time = parseInt(
          Number(this.advancedForm.goodsExchange_time_range[0]) / 1000
        );
        this.params.end_time = parseInt(
          Number(this.advancedForm.goodsExchange_time_range[1]) / 1000
        );
      }
      delete this.params.goodsExchange_time_range;
      this.params.page_no = 1;
      if (this.activeName == "first") {
        this.GET_GoodsExchangeList();
      } else {
        this.GET_WarehouseEntry();
      }
    },
    /** 获取出库单列表 */
    GET_GoodsExchangeList() {
      this.loading = true;
      API_GoodsExchange.getWarehouseOut(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /* 获取入库单列表 */
    GET_WarehouseEntry() {
      this.loading = true;
      API_GoodsExchange.getWarehouseEntry(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.btn {
  padding: 30px 20px 5px;
  border-radius: 5px;
  background-color: #fff;
  .el-button {
    width: 100px;
  }
}
.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;
  }
}
.print {
  margin-left: 790px;
}

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

  div {
    flex: 1;
    text-align: left;
    padding-left: 70px;
  }
}

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

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

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