<!--仓库管理-->
<template>
  <div>
    <BaseHeaderLayout :leftSpan="20">
      <template slot="left">
        <ws-button
          type="primary"
          @click="handleLook()"
          v-hasPermission="
            `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
          "
          >查看</ws-button
        >
        <ws-button
          type="primary"
          @click="handleAdd()"
          v-hasPermission="
            `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
          "
          >添加</ws-button
        >
        <ws-button
          type="primary"
          @click="handleEdit()"
          v-hasPermission="
            `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
          "
          >编辑</ws-button
        >
        <ws-button
          type="primary"
          @click="handleDelete()"
          v-hasPermission="
            `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
          "
          >删除</ws-button
        >
      </template>
      <template slot="right">
        <ws-input
          v-model="searchKeyWord"
          placeholder="请输入仓库名"
          clearable
          maxlength="500"
          type="input"
          class="findValue"
        ></ws-input>
        <!-- v-hasPermission="'procurement.sparepart.directShip'" -->
        <ws-button
          class="find"
          type="primary"
          @click="find()"
          v-hasPermission="
            `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
          "
          ><img
            width="16"
            height="16"
            style="
              vertical-align: text-top;
              position: relative;
              top: 0px;
              left: -8px;
            "
            src="../../../public/img/sousuo.png"
            alt=""
        /></ws-button>
      </template>
    </BaseHeaderLayout>
    <div class="connert">
      <el-table
        class="wenzi"
        :data="warehouseList"
        style="width: 100%; margin-top: 20px"
        height="780"
      >
        <el-table-column prop="warehouseName" label="库房名" width="80">
        </el-table-column>
        <el-table-column prop="binNumber" label="仓位编号" width="80">
        </el-table-column>
        <el-table-column prop="capacity" label="容量（吨）">
          <template slot-scope="scope">
            <div
              v-if="scope.row.capacity != 'null' && scope.row.capacity != null"
            >
              {{ scope.row.capacity }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品种">
          <template slot-scope="scope">
            <div v-for="(item, i) in scope.row.warehouseNumViewList">
              {{ item.goodsName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入库量（吨）">
          <template slot-scope="scope">
            <div v-for="(item, i) in scope.row.warehouseNumViewList">
              {{ item.inNetWeight }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="出库量（吨）">
          <template slot-scope="scope">
            <div v-for="(item, i) in scope.row.warehouseNumViewList">
              {{ item.outNetWeight }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="应余量（吨）">
          <template slot-scope="scope">
            <div v-for="(item, i) in scope.row.warehouseNumViewList">
              {{ item.storage }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="seller" label="出入库" width="300">
          <template slot-scope="scope">
            <ws-button
              type="primary"
              @click="nocomplete()"
              v-hasPermission="
                `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
              "
            >
              待完成（{{ scope.row.number }}）
            </ws-button>
            <ws-button
              type="primary"
              @click="warehousing(scope.row)"
              v-hasPermission="
                `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
              "
            >
              入库
            </ws-button>
            <ws-button
              type="primary"
              @click="delivery(scope.row)"
              v-hasPermission="
                `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
              "
            >
              出库
            </ws-button>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="200">
          <!-- <template slot-scope="scope"> -->
          <ws-button
            type="primary"
            @click="record()"
            v-hasPermission="
              `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
            "
            >记录</ws-button
          >

          <ws-button
            type="primary"
            @click="loss()"
            v-hasPermission="
              `${$permission('PERMISSIONS.PURSPAPPLINFO_CREATEINSTORE')}`
            "
            >盘损</ws-button
          >
          <!-- </template> -->
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import {
  getList,
  export1,
  editstatus,
  billoperatehis,
} from '@/model/warehouse/index'
import { downloadFile } from '@/utils/batchDown'
import Pagination from '@/components/Pagination'
import WsUpload from '@/components/WsUpload'
import { dayjs, fmoney, EventBus } from 'base-core-lib'
export default {
  name: 'viewSpareMoney',
  components: {
    WsUpload,
    Pagination,
  },
  watch: {
    vesselId(val) {
      this.getList()
    },
    isShow(val) {
      this.showType = val
    },
  },
  data() {
    return {
      //弹出框
      dialogViewSpareMoney: false,
      dialogApproveFormVisible: false,
      // 船舶类型
      monetaryKey: null,
      // 表格显示数据
      tableDate: [],

      // 是否显示
      showType: true,
      // 年
      year: '',
      currentPage: 1,
      pageSize: 10,
      searchType: 1,
      searchTypeText: '未完成',
      searchKeyWord: '',
      contractType: 2,
      startDate: null,
      endDate: null,
      // 提交类型
      submitType: true,
      size: 10,
      spanArr: [],
      compId: sessionStorage.getItem('ws-pf_compId'),
      deptCircularPage: {},
      date: {
        year: dayjs().format('YYYY'),
        month: dayjs().format('MM'),
      },
      warehouseList: [],
      deptBudgetList: {},
      historyList: [],
      pickerBeginDateBefore: {
        disabledDate: (time) => {
          return time.getTime() > Date.now()
        },
      },
      accessoryTFs: false,
    }
  },
  activated() {
    //cg.viewBudget
    //cg.viewSpareMoney
    // this.getVesselData();
    this.getList()
    this.showType = this.isShow
  },
  methods: {
    //出库
    delivery(item) {
      this.$router.push({
        path: 'warehouseManagementDelivery',
        query: {
          baseId: item.warehouseId,
          positionId: item.binNumberId,
          warehouseName: item.warehouseName,
          binNumber: item.binNumber,
        },
      })
    },
    //入库
    warehousing(item) {
      this.$router.push({
        path: 'warehouseManagementPut',
        query: {
          baseId: item.warehouseId,
          positionId: item.binNumberId,
          warehouseName: item.warehouseName,
          binNumber: item.binNumber,
        },
      })
    },
    getSpanArr(data) {
      let that = this

      //页面展示的数据，不一定是全部的数据，所以每次都清空之前存储的 保证遍历的数据是最新的数据。以免造成数据渲染混乱

      that.spanArr = []

      that.pos = 0

      //遍历数据

      data.forEach((item, index) => {
        //判断是否是第一项

        // if (index === 0) {
        //   this.spanArr.push(1)
        //   this.pos = 0
        // } else {
        //不是第一项时，就根据标识去存储
        console.log(data[index].warehouseNumViewList.length)
        if (data[index].warehouseNumViewList.length > 1) {
          // 查找到符合条件的数据时每次要把之前存储的数据+1
          this.spanArr[this.pos] = data[index].warehouseNumViewList.length
          this.spanArr.push(0)
        } else {
          // 没有符合的数据时，要记住当前的index

          this.spanArr.push(1)

          this.pos = index
        }
        // }
      })
    },
    //待完成
    nocomplete() {
      this.$router.push({ path: 'warehouseManagementNoComplete' })
    },
    //记录
    record() {
      this.$router.push({ path: 'warehouseManagementRecord' })
    },
    //盘损
    loss() {
      // console.log(row.positionId)
      // this.$router.push({
      //   name: 'warehouseManagementIoss',
      //   params: {positionId: row.positionId },
      // })
       this.$router.push({ path: 'warehouseManagementIoss' })
    },
    //查看
    handleLook() {
      this.$router.push({ path: 'warehouseManagementLook' })
    },
    //添加
    handleAdd() {
      this.$router.push({ path: 'warehouseManagementAdd' })
    },
    //编辑
    handleEdit() {
      this.$router.push({ path: 'warehouseManagementEdit' })
    },
    handleDelete() {
      this.$router.push({ path: 'warehouseManagementDelete' })
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        // "M+": date.getMinutes().toString(),         // 分
        // "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    },
    handleClose() {
      this.accessoryTFs = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
      this.getList()
    },
    getList() {
      getList({
        compId: sessionStorage.getItem('ws-pf_compId'),
      })
        .toPromise()
        .then((response) => {
          this.getSpanArr(response)
          // for (var i = 0; i < response.records.length; i++) {
          //   if (response.records[i].addressUrl != null) {
          //     response.records[i].addressUrlArray = response.records[
          //       i
          //     ].addressUrl.split(',')
          //   } else {
          //     response.records[i].addressUrlArray = []
          //   }
          // }
          // this.deptCircularPage.currentPage = response.current
          // this.deptCircularPage.pageSize = response.size
          // this.deptBudgetTotal = response.total
          this.warehouseList = response
        })
    },
    editClick(row) {
      var status = ''
      if (row.status == '待执行' || row.status == '已完成') {
        status = '执行中'
      } else if (row.status == '执行中') {
        status = '已完成'
      }
      //cancelButtonClass: "btn-custom-cancel"
      this.$confirm(`是否将状态改为${status}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          editstatus({ id: row.id })
            .toPromise()
            .then((response) => {
              this.$notify.success({
                title: '成功',
                message: '状态修改成功',
              })
              this.getList()
            })
            .catch((response) => {
              // EventBus.$emit('error', this.$t('showMessage.asteriskRequired'))
            })
        })
        .catch(() => {
          return false
        })
    },
    selecttaskType(e) {
      for (var i = 0; i < this.taskTypeList.length; i++) {
        if (this.taskTypeList[i].value == e) {
          this.searchType = this.taskTypeList[i].type
        }
      }
    },
    fujian(row) {
      if (
        row.receiveAttachmentPath === null ||
        row.receiveAttachmentPath === ''
      ) {
        EventBus.$emit(
          'warning',
          this.$t('system.noticeCircular.NoInformation')
        )
      } else {
        this.accessoryTFs = true
      }
      this.appendixIdss = row.receiveAttachmentPath
    },
    handleExamine(row) {
      this.$router.push({
        name: 'salesContractExamine',
        query: { id: row.id },
      })
    },
    // 关闭 dialog时 处理文件url 初始化upload组件
    handleCloe() {
      this.dialogViewSpareMoney = false
    },
    history(row) {
      console.log(row)
      billoperatehis({ id: row.id })
        .toPromise()
        .then((response) => {
          this.historyList = response
        })
    },
    find() {
      this.startDate = this.dateFormat('YYYY-mm-dd', this.value2[0])
      this.endDate = this.dateFormat('YYYY-mm-dd', this.value2[1])
      this.currentPage = 1
      this.getList()
    },
    async exportlist() {
      const { data } = await export1(
        {
          compId: sessionStorage.getItem('ws-pf_compId'),
          contractType: this.contractType,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          searchType: this.searchType,
          searchKeyWord: this.searchKeyWord,
          startDate: this.startDate,
          endDate: this.endDate,
        },
        {},
        { responseType: 'blob' }
      ).toPromise()
      downloadFile({
        res: data,
        fileName: `${
          this.date.year + (this.date.month ? `-${this.date.month}` : '')
        }_采购合同`,
        type: 'xls',
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.connert {
  width: 90%;
  margin: 0 auto;
}
.vertical-text-left {
  width: 62px;
  text-align: right;
}
</style>
