<template>
  <div>
    <div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="入库明细" name="second"></el-tab-pane>
        <el-tab-pane label="出库明细" name="first"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="btn">
    </div>
    <div class="search">
      <el-form ref="advancedForm" :model="advancedForm" label-width="160px">
        <el-row>
          <el-col :span="activeName=='first'?12:8">
            <el-form-item label="出入时间">
              <el-date-picker v-model="advancedForm.goodsExchange_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-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-select v-model="advancedForm.warehouse_id" clearable>
                <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="6" v-if="activeName == 'second'">
            <el-form-item label="入库类型">
              <el-select v-model="advancedForm.type" clearable>
                <el-option v-for="item in entryList" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="activeName == 'second'">
            <el-form-item label="客户名称">
              <el-input v-model="advancedForm.customer_name" clearable placeholder="请输入客户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="activeName == 'second'">
            <el-form-item label="手机号">
              <el-input v-model="advancedForm.customer_phone" clearable placeholder="请输入手机号"></el-input>
            </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(['addInventory']) && activeName == 'second'
          " type="primary" @click="handleAddGoodsExchange">新增入库</el-button>
          <el-button size="mini" v-if="
            checkPermission(['goodsExchangeAdd']) && 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_id" label="仓库名称">
          <template slot-scope="scope">
            {{ warehouseName(scope.row.warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_id" label="客户名称">
          <template slot-scope="scope">
            {{ scope.row.customer_name }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_id" label="客户手机号">
          <template slot-scope="scope">
            {{ scope.row.customer_phone }}
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="出库类型" v-if="activeName == 'first'">
          <template slot-scope="scope">
            <span>{{ outName(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="入库类型" v-else>
          <template slot-scope="scope">
            <span>{{ entryName(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="入库时间" v-if="activeName == 'second'">
          <template slot-scope="scope">
            <span>{{ scope.row.create_time | unixToDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="order_id_list" label="订单编号" />
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="activeName == 'first'">{{ scope.row.has_submit == 'Y' ? '已出库' : '未出库' }}</span>
            <span v-else>{{ scope.row.has_submit == 'Y' ? '已入库' : '未入库' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="出库时间" v-if="activeName == 'first'">
          <template slot-scope="scope">
            <span>{{ scope.row.create_time | unixToDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="备注">
          <template slot-scope="scope">
            <span v-if="activeName == 'first'">{{ scope.row.notes }}</span>
            <span v-else>{{ scope.row.memo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['checkInventory'])"
              @click="handleAuditGoodsExchange(scope.row)">查看</el-button>
            <el-button size="mini"
              v-if="scope.row.has_submit == 'N' && checkPermission(['editInventory']) && checkPermission(['goodsExchangeEdit']) && activeName == 'first'"
              @click="handleEditGoodsExchange(scope.row)">出库</el-button>
            <el-button size="mini"
              v-if="scope.row.has_submit == 'N' && checkPermission(['editInventory']) && checkPermission(['goodsExchangeEdit']) && activeName == 'second'"
              @click="handleEditGoodsExchange(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>
  </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: "second",
      entryList: [],
      outList: []
    };
  },
  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: {
    //获取仓库名称
    outName(val) {
      let name = ''
      this.outList.map(el => {
        if (el.value == val) {
          return name = el.label
        }
      })
      return name
    },
    //获取仓库名称
    entryName(val) {
      let name = ''
      this.entryList.map(el => {
        if (el.value == val) {
          return name = el.label
        }
      })
      return name
    },
    //获取仓库名称
    warehouseName(val) {
      let name = ''
      this.warehouseList.map(el => {
        if (el.id == val) {
          return name = el.name
        }
      })
      return name
    },

    handleClick(tab, event) {
      this.activeName = tab.name;
      this.params.page_no = 1
      if (tab.name == "first") {
        this.GET_GoodsExchangeList();
      } else {
        this.GET_WarehouseEntry();
      }
    },
    /** 状态 */
    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");
      }); */
      /* 入库类型 */
      API_Setting.getPage({ dictType: "warehouse_entry_type" }).then((res) => {
        this.entryList = res.data;
      });
      /* 出库类型 */
      API_Setting.getPage({ dictType: "out_warehouse_type" }).then((res) => {
        this.outList = res.data;
      });
    },
    /** 打印对账详情 */
    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;
      if (this.activeName == "first") {
        this.GET_GoodsExchangeList();
      } else {
        this.GET_WarehouseEntry();
      }
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      if (this.activeName == "first") {
        this.GET_GoodsExchangeList();
      } else {
        this.GET_WarehouseEntry();
      }
    },
    // 新增出库
    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;
}

.el-table {
  min-height: 500px !important;
}
</style>
