<template>
  <div class="pageBox">
    <div class="cardBox">
      <div class="searchBox">
        <div class="row">
          <span>商品名称：</span>
          <el-input v-model="filter.title" clearable @keyup.enter.native="handleSearch"></el-input>
        </div>
        <div class="row">
          <span>商品编码：</span>
          <el-input v-model="filter.external_sku_id" clearable @keyup.enter.native="handleSearch"></el-input>
        </div>
        <div class="row">
          <span>创建时间：</span>
          <el-date-picker
            v-model="addTime"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 340px"
            @change="handleSearch()">
          </el-date-picker>
        </div>
        <div class="row">
          <span>审核状态：</span>
          <el-select v-model="filter.status" placeholder="请选择" clearable @change="handleSearch()">
            <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="row">
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">筛选</el-button>
        </div>
      </div>
    </div>
    <el-card>
      <div class="opaBox">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="warning" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </div>
      <el-table v-loading="loading" :data="procureList" style="width: 100%" border>
        <el-table-column prop="goods_sku.id" label="商品id" width="80" align="center" />
        <el-table-column prop="goods_sku.name" label="商品名称" />
        <el-table-column prop="external_sku_id" label="商品编码" />
        <el-table-column prop="num" label="采购数量" />
        <el-table-column prop="cost" label="采购成本" />
        <el-table-column prop="buyer_name" label="采购人名称" />
        <!-- <el-table-column prop="status" label="状态" /> -->
        <el-table-column prop="arrived_time" label="到货时间" />
        <el-table-column prop="supplier_name" label="供应商">
          <template slot-scope="scope">
            <span v-if="scope.row.supplier_name">{{ scope.row.supplier_name }}（{{scope.row.supplier_id}}）</span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="采购时间" align="center" />
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">待审核</span>
            <span v-else-if="scope.row.status == 1" style="color: #6DD230;">审核通过</span>
            <span v-else-if="scope.row.status == 2" style="color: #f00;">审核不通过</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit" size="mini">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="pageSize"
          layout="prev, pager, next, jumper, sizes, total"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog title="新增" :visible.sync="dialogVisible" width="900px">
      <el-form label-width="90px" :inline="true">
        <el-form-item label="采购人:">
          <el-select v-model="curInfo.buyer_user_id" clearable filterable ref="userBatchRef">
            <el-option v-for="item in usersList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商:">
          <el-select v-model="curInfo.supplier_id" clearable filterable ref="supplierBatchRef">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.supplier_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div v-for="(item, index) in purchaseOrders" :key="index" class="bgBox">
        <div class="close" @click="delItem(index)"><i class="el-icon-delete-solid"></i></div>
        <el-form label-width="90px" :inline="true">
          <el-form-item label="商品名称:">
            <el-select v-model="item.external_sku_id" filterable remote reserve-keyword placeholder="商品名称" clearable
              :remote-method="remoteMethod" :loading="searchLoading">
              <el-option v-for="it in goodsList" :key="it.external_sku_id" :label="it.title" :value="it.external_sku_id">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="商品编码:">
            <el-input v-model="item.external_sku_id" disabled></el-input>
          </el-form-item> -->
          <el-form-item label="数量:">
            <el-input v-model="item.num" clearable @input="changeInput(index, item)"></el-input>
          </el-form-item>
          <el-form-item label="成本:">
            <el-input v-model="item.cost" clearable @input="changeInput(index, item)" style="width: 215px;">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品总价:">
            <el-input v-model="item.total_price" style="width: 215px;">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="采购日期:">
            <el-date-picker
              v-model="item.date"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="到货时间:">
            <el-date-picker
              v-model="item.arrived_time"
              type="datetime"
              placeholder="选择日期"
              format="yyyy-MM-dd hh:mm:ss"
              value-format="yyyy-MM-dd hh:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn" @click="addItem()"><i class="el-icon-plus"></i>添加采购商品</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitAddPurchase" :loading="commitloading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="editDialog" width="600px">
      <el-form label-width="90px">
        <el-form-item label="采购人">
          <el-select v-model="curInfo.buyer_user_id" clearable filterable ref="userRef" disabled>
            <el-option v-for="item in usersList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="curInfo.supplier_id" clearable filterable ref="supplierRef">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.supplier_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-select v-model="curInfo.external_sku_id" filterable remote reserve-keyword placeholder="商品名称" clearable
            :remote-method="editRemoteMethod" :loading="searchLoading">
            <el-option v-for="it in editGoodsList" :key="it.external_sku_id" :label="it.title" :value="it.external_sku_id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品编码">
          <el-input v-model="curInfo.external_sku_id" disabled></el-input>
        </el-form-item> -->
        <el-form-item label="数量">
          <el-input v-model="curInfo.num" :disabled="curInfo.status == 1"></el-input>
        </el-form-item>
        <el-form-item label="成本">
          <el-input v-model="curInfo.cost" :disabled="curInfo.status == 1"></el-input>
        </el-form-item>
        <el-form-item label="商品总价">
          <el-input v-model="curInfo.total_price" :disabled="curInfo.status == 1">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="采购时间">
          <el-date-picker
            v-model="curInfo.date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间">
          <el-date-picker
            v-model="curInfo.arrived_time"
            type="datetime"
            placeholder="到货时间"
            format="yyyy-MM-dd hh:mm:ss"
            value-format="yyyy-MM-dd hh:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="commitEdit" :loading="commitloading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="导入" :visible.sync="showImport" width="500px">
      <div style="text-align: center;">
        <el-upload class="upload-demo" drag action="" :limit="1" :multiple="false"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :file-list="fileList" :auto-upload="false" :on-change="importFileChange" :on-remove="fileRemove">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showImport = false">取 消</el-button>
        <el-button type="primary" @click="commitUpload" :loading="commitloading">上 传</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getPurchaseLog, updatePurchaseLog, getSupplier, batchAddPurchaseLog } from "@/api/supplyChain"
import axios from "axios"
import { userList } from "@/api/user"
import { goodsSkusList } from "@/api/goods"
import dayjs from 'dayjs'

export default {
  data() {
    return {
      loading: false,
      page: 1,
      pageSize: 15,
      total: 0,
      procureList: [],
      filter: {
        title: '',
        external_sku_id: '',
        status: ''
      },
      addTime: [],
      commitloading: false,
      dialogVisible: false,
      curInfo: {},
      showImport: false,
      fileList: [],
      usersList: [],
      supplierList: [],
      purchaseOrders: [],
      editDialog: false,
      goodsList: [],
      searchLoading: false,
      statusList: [
        { id: 0, name: '待审核' },
        { id: 1, name: '审核通过' },
        { id: 2, name: '审核不通过' }
      ],
      editGoodsList: []
    }
  },
  methods: {
    fetchList() {
      this.loading = true
      let params = {
        page: this.page,
        per_page: this.pageSize,
        ...this.filter,
        start_time: this.addTime ? this.addTime[0] : '',
        end_time: this.addTime ? this.addTime[1] : ''
      }
      getPurchaseLog(params).then((res) => {
        this.procureList = res.data.data
        this.total = res.data.meta.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleSizeChange(val) {
      this.page = 1
      this.pageSize = val
      this.fetchList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchList()
    },
    handleSearch() {
      this.page = 1
      this.fetchList()
    },
    // 新增供应商
    handleAdd() {
      this.curInfo = {
        buyer_user_id: localStorage.getItem("userId") * 1,
        supplier_id: ''
      }
      this.purchaseOrders = [{
        external_sku_id: '',
        num: '',
        cost: '',
        total_price: '',
        date: dayjs().format('YYYY-MM-DD'),
        arrived_time: ''
      }]
      this.dialogVisible = true
    },
    delItem(i) {
      this.purchaseOrders.splice(i, 1)
    },
    addItem() {
      this.purchaseOrders.push({
        external_sku_id: '',
        num: '',
        cost: '',
        total_price: '',
        date: dayjs().format('YYYY-MM-DD'),
        arrived_time: ''
      })
    },
    handleEdit(row) {
      this.curInfo = JSON.parse(JSON.stringify(row))
      this.editGoodsList = [{
        external_sku_id: row.external_sku_id,
        title: row.goods_sku && row.goods_sku.name
      }]
      this.curInfo.total_price = (row.cost * 1) * (row.num * 1)
      this.editDialog = true
    },
    commitAddPurchase() {
      this.commitloading = true
      let list = []
      let params = {
        ...this.curInfo
      }
      params.buyer_name = ''
      params.supplier_name = ''
      if(params.buyer_user_id) {
        params.buyer_name = this.$refs.userBatchRef.selectedLabel
      }
      if(params.supplier_id) {
        params.supplier_name = this.$refs.supplierBatchRef.selectedLabel
      }
      this.purchaseOrders.forEach((item) => {
        list.push({
          ...item,
          buyer_name: params.buyer_name,
          buyer_user_id: params.buyer_user_id,
          supplier_id: params.supplier_id,
          supplier_name: params.supplier_name
        })
      })
      batchAddPurchaseLog({purchaseOrders: list}).then((res) => {
        this.page = 1
        this.fetchList()
        this.$message({ type: "success", message: "新增成功!" })
        this.dialogVisible = false
        this.commitloading = false
      }).catch(() => {
        this.commitloading = false
      })
    },
    commitEdit() {
      this.commitloading = true
      let params = {
        ...this.curInfo
      }
      params.buyer_name = ''
      params.supplier_name = ''
      if(params.buyer_user_id) {
        params.buyer_name = this.$refs.userRef.selectedLabel
      }
      if(params.supplier_id) {
        params.supplier_name = this.$refs.supplierRef.selectedLabel
      }
      updatePurchaseLog(this.curInfo.id, params).then((res) => {
        this.fetchList()
        this.$message({ type: "success", message: "更新成功!" })
        this.editDialog = false
        this.commitloading = false
      }).catch(() => {
        this.commitloading = false
      })
    },
    handleImport() {
      this.fileList = []
      this.showImport = true
    },
    importFileChange(file, fileList) {
      console.log(fileList)
      this.fileList = fileList
    },
    fileRemove() {
      this.fileList = []
    },
    commitUpload() {
      if(this.fileList.length) {
        this.commitloading = true
        const params = new FormData();
        params.append("purchaseFile", this.fileList[0].raw)
        let token = localStorage.getItem("token")
        axios.post("/api/purchase_record/purchase_import", params, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }).then((res) => {
          if (res.status === 200) {
            this.$message.success("导入成功")
            this.page = 1
            this.fetchList()
            this.commitloading = false
            this.showImport = false
          } else {
            this.commitloading = false
          }
        }).catch(() => {
          this.commitloading = false
        })
      } else {
        this.$message.error("请先上传文件");
      }
    },
    getUserList() {
      let params = {
        page: 1,
        per_page: 9999
      }
      userList(params).then((res) => {
        this.usersList = res.data.data
      })
    },
    getSupplierList() {
      let params = {
        page: 1,
        per_page: 9999
      }
      getSupplier(params).then((res) => {
        this.supplierList = res.data.data
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true
        setTimeout(() => {
          this.searchLoading = false
          goodsSkusList(query).then((res) => {
            this.goodsList = res.data.filter(item => {
              return item.title.toLowerCase().indexOf(query.toLowerCase()) > -1
            })
          })
        }, 200)
      } else {
        this.goodsList = []
      }
    },
    changeInput(index, row) {
      this.$set(this.purchaseOrders[index], 'total_price', ((row.num * 1) * (row.cost * 1)))
    },
    editRemoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true
        setTimeout(() => {
          this.searchLoading = false
          goodsSkusList(query).then((res) => {
            this.editGoodsList = res.data.filter(item => {
              return item.title.toLowerCase().indexOf(query.toLowerCase()) > -1
            })
          })
        }, 200)
      } else {
        this.editGoodsList = []
      }
    }
  },
  mounted() {
    this.fetchList()
    this.getSupplierList()
    this.getUserList()
  }
}
</script>

<style lang="scss" scoped>
  .searchBox{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    white-space: nowrap;
    .row{
      font-size: 14px;
      margin-bottom: 20px;
      margin-right: 15px;
      display: flex;
      align-items: center;
    }
  }
  .opaBox{
    margin-bottom: 15px;
  }
  .bgBox{
    position: relative;
    border-radius: 5px;
    background-color: #f5f2f2;
    margin-bottom: 15px;
    padding: 15px 30px 15px 0;
    .close{
      color: #f00;
      position: absolute;
      right: 5px;
      top: 5px;
      font-size: 20px;
      cursor: pointer;
    }
  }
  .btn{
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #409eff;
    cursor: pointer;
    width: fit-content;
  }
</style>
