<template>
  <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="searchTime" type="daterange" align="center"
                value-format="yyyy-MM-dd hh:mm:ss" :editable="false" unlink-panels :clearable="true"
                :default-time="['00:00:00', '23:59:59']" range-separator="-" start-placeholder="开始日期"
                end-placeholder="结束日期"
                :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-date-picker v-model="searchTime" 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="yyyy-MM-dd hh:mm:ss">
              </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="8">
            <el-form-item label="盘点人">
              <!--  <el-input
                v-model="advancedForm.inventory_person"
                placeholder="请输入内容"
                width="200px"
              ></el-input> -->
              <el-select v-model="advancedForm.inventory_person_id" clearable>
                <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
              </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(['goodsInventory:add'])" type="primary"
            @click="handleAddGoodsInventory">新增</el-button>
          <!--   <el-button v-if="checkPermission(['goodsInventory:del'])" size="mini" @click="handleDeleteGoodsInventory()"
            type="danger" :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>
            </template>
</en-table-search>
</div>-->
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="盘点单编号">
          <template slot-scope="scope">
            <!-- <router-link
              v-if="checkPermission(['goodsInventory'])"
              style="color: #409eff;"
              :to="{ name: 'goodsInventoryDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
             </router-link> -->
            <span>{{ scope.row.sn }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inventory_time" label="盘点日期">
          <template slot-scope="scope">{{ scope.row.inventory_time }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="仓库">
          <template slot-scope="scope">{{ warehouseName(scope.row.warehouse_id) }}</template>
        </el-table-column>
        <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 size="mini" @click="handleCheckGoodsInventory(scope.row)"
              v-if="checkPermission(['goodsInventoryCheck'])">查看</el-button>
            <el-button v-if="scope.row.status == 'NOT_HANDLE' && checkPermission(['goodsInventoryEdit'])" size="mini"
              @click=" handleEditGoodsInventory(scope.row)">编辑</el-button>
            <el-button type="mini" size="mini"
              v-if="scope.row.status == 'NOT_HANDLE' && checkPermission(['goodsInventory:sync'])"
              @click="handleSubmitGoodsInventory(scope.row)">同步</el-button>
            <!-- <el-button v-if="scope.row.allowable.allow_audit && checkPermission(['goodsInventory:audit'])" type="mini"
              size="mini" @click="handleAuditGoodsInventory(scope.row)">审核</el-button>

            <el-button v-if="scope.row.allowable.allow_cancel && checkPermission(['goodsInventory:cancel'])" type="mini"
              size="mini" @click="handleCancelGoodsInventory(scope.row)">撤回</el-button>
            -->
            <!-- <el-button v-if="checkPermission(['goodsInventory:print'])" type="primary" size="mini"
              @click="handlePrintGoodsInventoryDialog(scope.row)">打印</el-button> -->
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-inventory="handlePageSizeChange"
        @current-inventory="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 :visible.sync="dialogVisible" width="940px" center>
      <div style="width:900px">
        <el-button size="mini" type="primary" @click="handlePrintGoodsInventory" class="print no-btn">打印</el-button>
        <div id="deliverySheet" slot="header" class="deliverySheet-header">
          <h3>产品库存盘点单</h3>
        </div>
        <div class="tips-t">
          <div>
            仓库名称编码:{{ goodsInventoryForm.dept_name }}{{ goodsInventoryForm.warehouse_name }}
          </div>
          <div>
            日期:{{ goodsInventoryForm.inventory_time | unixToDateStr }}
          </div>
          <div>
            编号:{{ goodsInventoryForm.sn }}
          </div>
        </div>
        <!-- <div class="tips-t">
          <div>
            盘点说明:{{ goodsInventoryForm.inventory_desc }}
          </div>
          <div></div>
          <div></div>
        </div> -->
        <el-table :data="goodsInventoryForm.product_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }" style=" width:100%;">
          <el-table-column label="序号" width="179">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="商品编号" width="170">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="170">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" width="110">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="50">
            <template slot-scope="scope">
              {{ scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="上期盘点库存" width="110">
            <template slot-scope="scope">
              {{ scope.row.stock_num }}
            </template>
          </el-table-column>
          <el-table-column label="本期盘点库存" width="110">
            <template slot-scope="scope">
              {{ scope.row.inventory_num }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-t">
          <div>
            盘点人:{{ goodsInventoryForm.inventory_person }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsInventory from '@/api/goodsInventory'
import Print from 'print-js'
import * as API_Auth from '@/api/auth'
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from "@/api/basicSetting";
import { Foundation } from '~/ui-utils'
export default {
  name: 'goodsInventory',
  data() {
    return {
      warehouseList: [],
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsInventoryForm: {},
      adminList: [],
      searchTime: [],
    }
  },
  mounted() {
    this.GET_GoodsInventoryList()
    this.GET_DeptList()
    this.GET_WarehouseList();
  },
  watch: {
    $route: function ({ query }) {
      this.params.page_no = 1
      this.GET_GoodsInventoryList()
    }
  },
  methods: {
    /** 获取仓库 */
    GET_WarehouseList() {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    // 查看
    handleCheckGoodsInventory(row) {
      this.$router.push({
        name: 'goodsInventoryCheck',
        params: {
          id: row.id
        }
      })
    },
    handleAuditGoodsInventory(row) {
      this.$router.push({
        name: 'goodsInventoryAudit',
        params: {
          id: row.id
        }
      })
    },
    handleEditGoodsInventory(row) {
      this.$router.push({
        name: 'goodsInventoryEdit',
        params: { id: row.id }
      })
    },
    /** 提交 */
    handleSubmitGoodsInventory(row) {
      API_GoodsInventory.getSyncStock(row.id).then(() => {
        this.$message.success('处理成功！')
        this.GET_GoodsInventoryList()
      })
    },
    /** 撤回 */
    handleCancelGoodsInventory(row) {
      API_GoodsInventory.cancelGoodsInventory(row.id).then(() => {
        this.$message.success('撤回成功！')
        this.GET_GoodsInventoryList()
      })
    },
    /** 确认 */
    handleConfirmGoodsInventory(row) {
      // if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定吗？', '提示', { type: 'warning' }).then(() => {
        // const ids = this.multipleSelection.map(item => item.id)
        API_GoodsInventory.inventoryFormConfirm(row.id).then(() => {
          this.$message.success('确认成功！')
          this.GET_GoodsInventoryList()
        })
      }).catch(() => { })
    },
    /** 添加盘点单 */
    handleAddGoodsInventory() {
      this.$router.push({
        name: 'goodsInventoryAdd',
        params: { callback: this.GET_GoodsInventoryList }
      })
    },
    /** 打印盘点单 */
    handlePrintGoodsInventoryDialog(row) {
      this.GET_GoodsInventoryDetail(row.id)
    },
    /** 删除 */
    handleDeleteGoodsInventory() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除当前盘点单吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_GoodsInventory.deleteGoodsInventory(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_GoodsInventoryList()
        })
      }).catch(() => { })
    },
    /** 状态 */
    statusFilter(val) {
      switch (val) {
        case 'NOT_HANDLE':
          return '未处理'
        case 'HAS_HANDLE':
          return '已处理'
      }
    },
    //获取仓库名称
    warehouseName(val) {
      let name = ''
      this.warehouseList.map(el => {
        if (el.id == val) {
          return name = el.name
        }
      })
      return name
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintGoodsInventory() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      console.log('val=-', val)
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_GoodsInventoryList()
    },
    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_GoodsInventoryList()
    },
    /** 获取盘点单详情页面数据 */
    GET_GoodsInventoryDetail(id) {
      API_GoodsInventory.getGoodsInventoryInfo(id).then(response => {
        this.goodsInventoryForm = response
        if (response.product_list && response.product_list.length) {
          var str = ''
          response.product_list.forEach(function (i) {
            str += i.product_name + '、'
          })
        }
        this.goodsInventoryForm.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_GoodsInventoryList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      if (this.searchTime) {
        this.advancedForm.start_time = this.searchTime[0];
        this.advancedForm.end_time = this.searchTime[1];
      }
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      this.params.page_no = 1
      this.GET_GoodsInventoryList()
    },
    /** 获取盘点单列表 */
    GET_GoodsInventoryList() {
      this.loading = true
      API_GoodsInventory.getGoodsInventoryList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.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;
}

.deliverySheet-header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.tips-t {
  display: flex;
  padding: 30px 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>
