<!-- 盘点 -->
<template>
  <div class="stock-order">
    <template v-if="!inventoryAddVisible && !inventoryDetailVisible && !detailVisible">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="queryData()">
        <el-form-item label="盘点日期">
          <el-date-picker
            v-model="dataForm.date"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="queryData()">查询</el-button>
          <el-button v-if="isAuth('wh:inventory:save')" @click="inventoryAdd()"  type="primary">新增盘点</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          label="序号"
          type="index"
          width="50"
          align="center">
        </el-table-column>
        <el-table-column
          prop="inventoryCode"
          header-align="center"
          align="center"
          width="140"
          :show-tooltip-when-overflow="true"
          label="编码">
        </el-table-column>
        <el-table-column
          prop="createTime"
          header-align="center"
          align="center"
          width="160"
          :show-tooltip-when-overflow="true"
          label="开始日期">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          header-align="center"
          align="center"
          min-width="160"
          label="结束日期">
        </el-table-column>
        <el-table-column
          prop="state"
          header-align="center"
          align="center"
          min-width="100"
          :formatter="formatState"
          label="状态">
        </el-table-column>
        <el-table-column
          prop="approverState"
          header-align="center"
          align="center"
          min-width="100"
          :formatter="formatApproveState"
          label="审批状态">
        </el-table-column>
        <el-table-column
          prop="approver"
          header-align="center"
          align="center"
          min-width="100"
          label="当前处理人">
        </el-table-column>
        <el-table-column
          prop="checkerName"
          header-align="center"
          align="center"
          label="盘点员">
        </el-table-column>
        <el-table-column
          prop="dcheckerName"
          header-align="center"
          align="center"
          label="复核员">
        </el-table-column>
        <el-table-column
          prop="notes"
          header-align="center"
          align="center"
          width="120"
          :show-tooltip-when-overflow="true"
          label="备注">
        </el-table-column>
        <el-table-column
          prop="attachList"
          header-align="center"
          align="center"
          min-width="120"
          label="导入文件记录">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.attachList" style="display: inline">
              <span v-if="index > 0">,</span>
              <a :key="item.fileName + index" type="primary" href="#" @click="previewFile(item.fileName, item.url)">{{ item.fileName }}</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="100"
          label="操作">
          <template slot-scope="scope">
            <el-button v-if="isAuth('wh:inventory:info')" type="text" size="small" @click="detailHandle(scope.row.inventoryId)">查看</el-button>
<!--            <el-button v-if="isAuth('wh:inventory:export') && Number(scope.row.state) === 0" type="text" size="small" @click="exportExcel(scope.row.inventoryId)">导出</el-button>-->
            <el-button v-if="isAuth('wh:inventory:import') && Number(scope.row.state) === 0" type="text" size="small" @click="importExcel()">导入</el-button>
<!--            <el-button v-if="isAuth('wh:inventory:start') && Number(scope.row.state) === 0" type="text" size="small" @click="addOrUpdateHandle(scope.row.inventoryId, false)">盘点</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </template>
    <!--    入库-->
    <inventory-add v-if="inventoryAddVisible" ref="inventoryAdd" @refreshDataList="getDataList" @onChose="onChose"></inventory-add>
    <inventory-begin v-if="inventoryDetailVisible" ref="inventoryDetail" @refreshDataList="getDataList" @onChose="onChose"></inventory-begin>
    <detail v-if="detailVisible" ref="detail" @onChose="onChose"/>
    <!-- 文件预览 -->
    <preview-component v-if="previewVisible" ref="preview"/>
    <!-- 文件选择 -->
    <input v-show="false" ref="fileRef" type="file" @change="fileChange"/>
  </div>
</template>

<script>
  import inventoryAdd from './inventory-add'
  import inventoryBegin from './inventory-begin'
  import Detail from './inventory-detail'
  import {getInventoryList} from '@/api/warehouse'
  import PreviewComponent from '@/views/modules/common/preview-component'

  export default {
    name: 'stock-order',
    components: {PreviewComponent, inventoryAdd, inventoryBegin, Detail},
    data () {
      return {
        inventoryAddVisible: false,
        inventoryDetailVisible: false,
        detailVisible: false,
        previewVisible: false,
        dataForm: {},
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        // 状态
        optionsState: [
          {
            code: '0',
            value: '正在进行中'
          },
          {
            code: '1',
            value: '完成'
          }
        ],
        // 审批状态：0 待提交 1 待审批 2 审批中 3 审批完成 4 审批不通过
        optionsApproveState: []
      }
    },
    created () {
      this.optionsApproveState = this.$store.state.common.approveStates
      this.getDataList()
    },
    methods: {
      onChose () {
        this.inventoryAddVisible = false
        this.inventoryDetailVisible = false
        this.detailVisible = false
      },
      // 查询
      queryData () {
        this.pageIndex = 1
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        let params = {
          'current': this.pageIndex,
          'size': this.pageSize,
          'beginTime': this.dataForm.date ? this.dataForm.date[0] : null,
          'endTime': this.dataForm.date ? this.dataForm.date[1] : null
        }
        getInventoryList(params).then(({data}) => {
          if (data && data.code === '200') {
            this.dataList = data.data.records
            this.totalPage = Number(data.data.total)
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 盘点详情
      addOrUpdateHandle (id, display) {
        this.inventoryDetailVisible = true
        this.$nextTick(() => {
          this.$refs.inventoryDetail.init(id, display)
        })
      },
      // 新增盘点
      inventoryAdd () {
        this.inventoryAddVisible = true
        this.$nextTick(() => {
          this.$refs.inventoryAdd.init()
        })
      },
      // 转换属性“状态”
      formatState (row) {
        if (!row.state) return ''
        const item1 = this.optionsState.find((item) => item.code === row.state.toString())
        return item1 ? item1.value : ''
      },
      // 转换属性“审批状态”
      formatApproveState (row) {
        if (!row.approverState) return ''
        const item1 = this.optionsApproveState.find((item) => item.code === row.approverState.toString())
        return item1 ? item1.value : ''
      },
      // 预览
      previewFile (fileName, url) {
        this.previewVisible = true
        this.$nextTick(() => {
          this.$refs.preview.init(fileName, url)
        })
      },
      detailHandle (id) {
        this.detailVisible = true
        this.$nextTick(() => {
          this.$refs.detail.init(id)
        })
      },
      // 导出文件
      exportExcel (inventoryId) {
        this.$http({
          url: this.$http.adornUrl('/biz-service/inventory-checking-ctl/exportExcel'),
          method: 'get',
          params: this.$http.adornParams({
            'inventoryId': inventoryId
          })
        }).then((res) => {
          let data = res.data
          if (!data) {
            return
          }
          const url = window.URL.createObjectURL(new Blob([data]))
          let a = document.createElement('a')
          let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]
          a.style.display = 'none'
          a.href = url
          a.setAttribute('download', _fileName)
          document.body.appendChild(a)
          a.click() // 执行下载
          window.URL.revokeObjectURL(a.href)
          document.body.removeChild(a)
        }).catch((error) => { console.log(error) })
      },
      // 导入文件
      importExcel () {
        this.$refs.fileRef.dispatchEvent(new MouseEvent('click'))
      },
      fileChange (e) {
        const file = e.target.files[0]
        const formData = new FormData()
        formData.append('importFile', file)
        this.$http({
          url: this.$http.adornUrl('/biz-service/inventory-checking-ctl/importExcel'),
          method: 'post',
          data: formData
        }).then(({data}) => {
          if (data && data.code === '200') {
            this.$message.success('上传成功')
            this.getDataList()
          } else {
            this.$message.error('上传失败')
          }
        }).catch((e) => { console.log(e) })
      }
    }
  }
</script>

<style scoped>

</style>
