<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="门店" prop="channelId">
        <el-select v-model="queryParams.channelId" placeholder="请选择门店" style="width: 100%;" filterable clearable :filter-method="dataFilter" @change="pageParams.pageNum = 1;handleQuery()">
          <el-option v-for="(item) in siteList" :key="item.channelId" :label="item.name" :value="item.channelId">
            <div>
              <span style="float: left;">{{item.name}} </span>
              <span style="float: right;">{{item.mobile}}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称">
        <el-input v-model="queryParams.title" placeholder="请输入商品名称" clearable size="small" style="width: 240px" @change="pageParams.pageNum = 1;handleQuery()" />
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model="queryParams.orderId" placeholder="输入订单编号" clearable size="small" style="width: 240px" @change="pageParams.pageNum = 1;handleQuery()" />
      </el-form-item>
      <el-form-item label="入库时间">
        <el-date-picker v-model="tradeTimeArr" type="datetimerange" size="small" value-format="timestamp" range-separator="至" start-placeholder="时间选择" end-placeholder="时间选择" @change="tardeTime">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="手机号码">
        <el-input v-model="queryParams.tel" placeholder="输入手机号" clearable size="small" style="width: 240px" @change="pageParams.pageNum = 1;handleQuery()" />
      </el-form-item> -->
      <el-form-item label="状态">
        <el-select v-model="queryParams.settleStatus" placeholder="请选择" clearable @change="pageParams.pageNum = 1;handleQuery()">
          <el-option label="全部" value="" />
          <el-option label="未结算" value="1" />
          <el-option label="结算中" value="3" />
          <el-option label="已结算" value="2" />
          <el-option label="核销完成" value="4" />
        </el-select>
      </el-form-item>
      <br>
      <el-form-item label="剩余库存">
        <el-input v-model="queryParams.minStock" placeholder="最小值" @change="pageParams.pageNum = 1;handleQuery()" clearable @keyup.enter.native="pageParams.pageNum = 1;handleQuery()" />
      </el-form-item>
      <el-form-item label="-" label-width="6px">
        <el-input v-model="queryParams.maxStock" placeholder="最大值" @change="pageParams.pageNum = 1;handleQuery()" clearable @keyup.enter.native="pageParams.pageNum = 1;handleQuery()" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="pageParams.pageNum = 1;handleQuery()">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 导出、刷新 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 列表 -->
    <el-table ref="table" v-loading="loading" :data="list">
      <!-- 展开盲票组列表 -->
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-table :data="row.items" row-key="itemId">
            <el-table-column label="商品图片" min-width="80">
              <div slot-scope="{ row }">
                <el-image style="width: 100px; height: 100px" :src="row.picUrl" :preview-src-list="[row.picUrl]" />
              </div>
            </el-table-column>
            <el-table-column label="商品名称" prop="title" min-width="80" />
            <el-table-column label="规格" min-width="100">
              <template slot-scope="{ row }">
                <div>{{ row.properties || "--" }}</div>
              </template>
            </el-table-column>
            <el-table-column label="采购成本（单价）" prop="purchaseCost" min-width="80" >
              <template slot-scope="{ row }">
                <div>￥{{ $numberFormat(row.purchaseCost) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="quantity" min-width="80" />
            <el-table-column label="已核销" prop="verifyQty" min-width="80" />
            <el-table-column label="剩余库存" prop="remainQty" min-width="80" />
          </el-table>
        </template>
      </el-table-column>
      <!-- 不展开列表 -->
      <el-table-column label="订单号" prop="orderId" min-width="110" />
      <el-table-column label="入库时间" min-width="110">
        <template slot-scope="{ row }">
          <div>{{ row.items && row.items[0] && parseTime(row.items[0].createdTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="门店(手机号)" prop="channelName" min-width="120" >
        <template slot-scope="{ row }">
          <div>{{ row.channelName+'（'+row.mobile+'）' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="总库存" prop="totalQuantity" min-width="50" />
      <el-table-column label="总已核销" prop="totalVerifyQty" min-width="50" />
      <el-table-column label="剩余总库存" prop="totalRemainQty" min-width="55" />
      <!-- <el-table-column label="总采购成本" min-width="70">
        <template slot-scope="{ row }">
          <div>￥{{ $numberFormat(row.totalPurchaseCost) }}</div>
        </template>
      </el-table-column> -->
      <el-table-column label="结算库存" prop="totalSettleQty" min-width="50" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <div>
            <el-tag :type="row.status.value == 1? 'success' : 'info'" v-if="row.status">{{
                row.status.desc
              }}
            </el-tag>
            <el-tag type="info" v-else>--</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="80">
        <template slot-scope="{ row }">
          <div>
            <el-button v-hasPermi="['business:channelGoods:query']" type="text" @click="getDetail(row)">查看详情
            </el-button>
            <el-button v-hasPermi="['business:channelGoodsOrder:push']" v-if="row.status && row.status.value == 1" type="text" @click="toInventory(row)">去结算
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <div v-html="responseData"></div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize" @pagination="getList" />

    <!-- 结算 -->
    <inventory-goods :inventory-show="inventoryShow" :inventory-info="info" @close="close" v-if="inventoryShow"/>
  </div>
</template>
<script>
import { getInventoryList } from "@/api/business/inventory";
import { listAllSaleSite } from "@/api/admin/salesite";
import { publicFileGetUrl } from "@/api/common";
import InventoryGoods from "./components/InventoryGoods";
export default {
  name: "Inventory",
  components: {
    InventoryGoods,
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      dialogVisible: false,
      // 筛选
      queryParams: {
        minStock: "",
        maxStock: "",
        channelId: "",
        title: "",
        orderId: "",
        startTime: "",
        endTime: "",
        settleStatus: "",
        tel: "",
      },
      // 分页
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      list: [],
      // 门店
      merchantArr: [],
      // 下单时间
      tradeTimeArr: [],
      // 结算弹窗显示
      inventoryShow: false,
      // 订单详情
      info: {},
      fileSaveUrl: '',
      reqData: {},
      responseData: '',
      siteList: [],
      siteCopyList: [],
    };
  },
  created() {
    this.getList();
    this.getSaleSiteList()
  },
  methods: {
    // 获取门店下拉列表
    getSaleSiteList() {
      listAllSaleSite({}).then(response => {
        this.siteList = response.data || [];
        this.siteCopyList = response.data || [];
      });
    },
    dataFilter(val) {
      if (val) { //val存在
        this.siteList = this.siteCopyList.filter((item) => {
          if (!!~item.mobile.indexOf(val) || !!~item.mobile.toUpperCase().indexOf(val.toUpperCase())
            || !!~item.name.indexOf(val) || !!~item.name.indexOf(val)) {
            return true
          }
        })
      } else { //val为空时，还原数组
        this.siteList = this.siteCopyList;
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    // 订单列表
    getList() {
      let data = {
        ...this.queryParams,
      }
      this.loading = true;
      getInventoryList(
        "pageNum=" +
        this.pageParams.pageNum +
        "&pageSize=" +
        this.pageParams.pageSize +
        "&",
        data
      )
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
            res.rows.forEach((item) => {
              let items = item.items;
              items.forEach((item) => {
                let picUrlArr = item.picUrl.split(",");
                item.picUrl = publicFileGetUrl + picUrlArr[0];
              });
              item.status = JSON.parse(item.status);
            });
            this.total = res.total;
            this.list = res.rows;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    //搜索
    handleQuery() {
      this.siteList = this.siteCopyList;
      this.pageParams.pageNum = 1;
      this.getList();
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        minStock: "",
        maxStock: "",
        channelId: "",
        title: "",
        orderId: "",
        startTime: "",
        endTime: "",
        settleStatus: "",
        tel: "",
      };
      this.tradeTimeArr = [];
      this.getList();
    },

    // 选择下单时间
    tardeTime(e) {
      if (e) {
        this.queryParams.startTime = e[0];
        this.queryParams.endTime = e[1];
        this.pageParams.pageNum = 1
        this.handleQuery();
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
        this.pageParams.pageNum = 1
        this.handleQuery();
      }
    },

    // 查看详情
    getDetail(row) {
      this.$router.push({ name: "InventoryDetail", query: { id: row.orderId } });
    },

    // 点击去结算
    toInventory(row) {
      this.info = row;
      this.inventoryShow = true;
    },

    // 关闭结算
    close() {
      this.inventoryShow = false;
      this.getList();
    },

  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}
</style>
<style  lang="scss">
.msgbox {
  width: 60%;
}
</style>
