<template>
  <div class="container">
    <el-row>
      <el-col :span="20">
        <h2 class="bg-left title">&nbsp;&nbsp;盘损当期仓损</h2>
      </el-col>
      <el-col :span="4" class="bg-right">
        <el-button
          class="bg-bottom"
          type="primary"
          size="small"
          @click="returnWarehouse()"
          ><img
            width="6"
            height="10"
            style="vertical-align: bottom; margin-right: 3px"
            src="../../../public/img/lujing.png"
            alt=""
          />返回</el-button
        >
      </el-col>
    </el-row>
    <div class="center">
      <ws-form ref="deptBudgetList" :model="deptBudgetList" :rules="rules">
        <h2>
          {{ deptBudgetList1.warehouseName }}库
          <span class="position"> {{ deptBudgetList1.binNumber }}仓位 </span>
        </h2>
        <!-- 货名 -->
        <ws-form-item
          label="货名："
          span="1"
          prop="goodsName"
          class="goodsname"
        >
          <ws-select
            v-model="deptBudgetList.goodsName"
            placeholder=""
            class="typeselect"
            @change="changeioss"
          >
            <ws-option
              v-for="item in goodnameList"
              :key="item.constKey"
              :label="item.goodsName"
              :value="item.goodsName"
            />
          </ws-select>
        </ws-form-item>
        <!--当期累计入库量-->
        <ws-form-item
          label="当期累计入库量（吨）："
          span="1"
          prop="cumulativeStockIn"
          class="readonly"
        >
          {{ deptBudgetList.cumulativeStockIn }}
        </ws-form-item>
        <!--实际库存（吨）-->
        <ws-form-item
          label="实际库存（吨）："
          span="1"
          prop="physicalInventory"
          class="readonly"
        >
          <ws-input
            v-model="deptBudgetList.physicalInventory"
            placeholder=""
            maxlength="100"
            size="small"
          />
        </ws-form-item>
        <!--当期累计出库量（吨）-->
        <ws-form-item
          label="当期累计出库量（吨）："
          span="1"
          prop="cumulativeStockOut"
          class="readonly"
        >
          {{ deptBudgetList.cumulativeStockOut }}
        </ws-form-item>
        <!--损耗量（吨）-->
        <ws-form-item
          label="损耗量（吨）："
          span="1"
          prop="ioss"
          class="readonly"
        >
          {{ ioss1 > 0 ? ioss1 : 0 }}
        </ws-form-item>
        <!--应余库存（吨）-->
        <ws-form-item
          label="应余库存（吨）："
          span="1"
          prop="surplusInventory"
          class="readonly"
        >
          {{ surplusInventory1 > 0 ? surplusInventory1 : 0 }}
        </ws-form-item>
        <!--库损比例-->
        <ws-form-item
          label="库损比例："
          span="1"
          prop="inventoryRatio"
          class="readonly"
        >
          <!-- .占比=损耗量÷（累计入库-实际库存） -->
          <span class="proportion" v-show="inventoryRatio1 > 3"
            >{{ inventoryRatio1 > 0 ? inventoryRatio1 : 0 }} {{ '‰' }}</span
          >
          <span class="proportion1" v-show="inventoryRatio1 < 3"
            >{{ inventoryRatio1 > 0 ? inventoryRatio1 : 0 }} {{ '‰' }}</span
          >
        </ws-form-item>
        <p class="fontsize">
          注：提交成功后，当期实际库存将作为下一期的初始库存。
        </p>
      </ws-form>

      <div style="text-align: right; padding: 10px">
        <el-button
          class="bg-bottom-up"
          type="primary"
          size="small"
          @click="submit()"
          >提交</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { goodsname, ioss, submitioss } from '@/model/warehouse/index'

import Pagination from '@/components/Pagination'
import WsUpload from '@/components/WsUpload'
import { mapActions, mapGetters, mapState } from 'vuex'
// import { dayjs, fmoney, EventBus } from 'base-core-lib'
import { dayjs } from 'base-core-lib'
export default {
  name: 'viewSpareMoney',
  components: {
    WsUpload,
    Pagination,
  },
  watch: {
    vesselId(val) {
      this.loaddata()
    },
    isShow(val) {
      this.showType = val
    },
  },
  data() {
    return {
      //弹出框
      dialogViewSpareMoney: false,
      dialogApproveFormVisible: false,
      // 船舶类型
      monetaryKey: null,
      // 表格显示数据
      tableDate: [],
      // 是否显示
      showType: true,
      // 年
      year: '',
      deptBudgetTotal: 0,
      currentPage: 1,
      pageSize: 10,
      searchType: 1,
      searchKeyWord: '',
      contractType: 2,
      startDate: null,
      endDate: null,
      // 提交类型
      submitType: true,
      selectpackingMethod: {},
      goodnameList: [],
      size: 10,

      compId: sessionStorage.getItem('ws-pf_compId'),
      deptCircularPage: {},
      packtypeList: {},
      deptBudgetList1: [],
      date: {
        year: dayjs().format('YYYY'),
        month: dayjs().format('MM'),
      },
      contractList: [],
      deptBudgetList: {
        physicalInventory: 0,
      },
      historyList: [],
      rules: {
        netWeight: [
          {
            required: true,
            type: 'number',
            message: '请输入活动名称',
            trigger: 'blur',
          },
        ],
      },
      pickerBeginDateBefore: {
        disabledDate: (time) => {
          return time.getTime() > Date.now()
        },
      },
      accessoryTFs: false,
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'isFullScren',
      'tagWel',
      'tagList',
      'isCollapse',
      'tag',
      'logsLen',
      'logsFlag',
      'language',
    ]),
    ioss1: function () {
      return (
        this.deptBudgetList.cumulativeStockIn -
        this.deptBudgetList.cumulativeStockOut -
        this.deptBudgetList.physicalInventory
      )
    },
    surplusInventory1: function () {
      return (
        this.deptBudgetList.cumulativeStockIn -
        this.deptBudgetList.cumulativeStockOut
      )
    },
    inventoryRatio1: function () {
      var loss =
        this.deptBudgetList.cumulativeStockIn -
        this.deptBudgetList.cumulativeStockOut -
        this.deptBudgetList.physicalInventory
      var defect =
        this.deptBudgetList.cumulativeStockIn -
        this.deptBudgetList.physicalInventory
      if (loss / defect == 1) {
        var num = 0
      } else {
        // .占比=损耗量÷（累计入库-实际库存）
        num = Math.floor((loss / defect) * 1000000) / 1000
      }

      return num
    },
  },
  activated() {
    //cg.viewBudget
    //cg.viewSpareMoney
    // this.getVesselData();
    this.loaddata()
    this.showType = this.isShow
  },

  mounted() {
    this.deptBudgetList.baseId = this.$route.query.baseId
    this.deptBudgetList.positionId = this.$route.query.positionId
    this.deptBudgetList.warehouseName = this.$route.query.warehouseName
    this.deptBudgetList.binNumber = this.$route.query.binNumber
    this.deptBudgetList1.warehouseName = this.$route.query.warehouseName
    this.deptBudgetList1.binNumber = this.deptBudgetList.binNumber
    this.deptBudgetList1.baseId = this.$route.query.baseId
    this.deptBudgetList1.positionId = this.deptBudgetList.positionId
    this.loaddata() 
      // 货名
    // this.deptBudgetList.inventoryRatio=((deptBudgetList.cumulativeStockIn-deptBudgetList.cumulativeStockOut)-deptBudgetList.physicalInventory)/(deptBudgetList.cumulativeStockIn-deptBudgetList.physicalInventory)*100
    // this.deptBudgetList.ioss=(deptBudgetList.cumulativeStockIn-deptBudgetList.cumulativeStockOut)-deptBudgetList.physicalInventory
    // this.deptBudgetList1.goodsNameKey=this.deptBudgetList.goodsNameKey
    // this.getList()
  },
  methods: {
    //返回按钮
    returnWarehouse() {
       this.deptBudgetList.goodsName = ""
      this.$router.push({ path: 'warehouseManagementList' })
    },
    //提交按钮
    submit() {
      this.$refs.deptBudgetList.validate((valid) => {
        if (valid) {
          this.deptBudgetList.surplusInventory =
            this.deptBudgetList.cumulativeStockIn -
            this.deptBudgetList.cumulativeStockOut
          this.deptBudgetList.loss =
            this.deptBudgetList.cumulativeStockIn -
            this.deptBudgetList.cumulativeStockOut -
            this.deptBudgetList.physicalInventory
          this.deptBudgetList.inventoryRatio =
            (this.deptBudgetList.cumulativeStockIn -
              this.deptBudgetList.cumulativeStockOut -
              this.deptBudgetList.physicalInventory) /
            (this.deptBudgetList.cumulativeStockIn -
              this.deptBudgetList.physicalInventory)
          this.deptBudgetList.baseId = this.deptBudgetList1.baseId
          this.deptBudgetList.positionId = this.deptBudgetList1.positionId
          this.deptBudgetList.binNumber = this.deptBudgetList1.binNumber
          this.deptBudgetList.warehouseName = this.deptBudgetList1.warehouseName
          this.deptBudgetList.qualityInspector = this.userInfo.showRoleName
          for (var i = 0; i < this.goodnameList.length; i++) {
            if (
              this.goodnameList[i].goodsName == this.deptBudgetList.goodsName
            ) {
              this.deptBudgetList.goodsNameKey = this.goodnameList[
                i
              ].goodsNameKey
            }
          }
          this.deptBudgetList.compId = this.compId
          this.deptBudgetList.contractType = 1

          submitioss(this.deptBudgetList)
            .toPromise()
            .then((response) => {
              this.$message.success('提交成功')
              this.deptBudgetList.goodsName = ""
              this.$router.push({ path: 'warehouseManagementList' })
            })
        } else {
          //EventBus.$emit('error', this.$t('showMessage.asteriskRequired'))
          return false
        }
      })
    },
    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()
    },
    changeioss(e) {
      if(!this.deptBudgetList.baseId){
        this.deptBudgetList.baseId = this.$route.query.baseId
        this.deptBudgetList.positionId = this.deptBudgetList1.positionId
        this.deptBudgetList.binNumber = this.deptBudgetList1.binNumber
      }
      for (var i = 0; i < this.goodnameList.length; i++) {
        if (this.goodnameList[i].goodsName == e) {
          this.deptBudgetList.goodsNameKey = this.goodnameList[i].goodsNameKey
        }
      }
      this.ioss()
    },
    ioss() {
      ioss(this.deptBudgetList)
        .toPromise()
        .then((response) => {
          this.deptBudgetList = response
        })
    },
    loaddata() {
     
      // 货名
      goodsname({ positionId: this.$route.query.positionId })
        .toPromise()
        .then((response) => {
          this.goodnameList = response
        })
    },
    selecttaskType(e) {
      for (var i = 0; i < this.taskTypeList.length; i++) {
        if (this.taskTypeList[i].value == e) {
          this.searchType = this.taskTypeList[i].type
        }
      }
    },
    // // 关闭 dialog时 处理文件url 初始化upload组件
    // handleCloe() {
    //   this.dialogViewSpareMoney = false
    // },
    // history(row) {
    //   console.log(row)
    //   billoperatehis({ id: row.id })
    //     .toPromise()
    //     .then((response) => {
    //       this.historyList = response
    //     })
    // },

    //删除
    // approve() {},
    // listQuery() {},
    // total() {},
    // clearfiltQuery() {},
    // selectCrtDuty() {},
  },
}
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
}
.center {
  top: 50px;
  width: 40%;
  height: 700px;
  margin: 0 auto;
}
/deep/.el-form-item__label {
  width: 160px;
}
/deep/.el-input--small {
  width: 70%;
}
/deep/.bg-right {
  padding-right: 10px;
  text-align: right;
}
.container .bg-bottom {
  margin: 15px 0px;
}

//仓位
.position {
  background: #afb5cb;
  border-radius: 2px;
  font-size: 12px;
  color: #ffffff;
  line-height: 20px;
  display: inline-grid;
  padding: 2px 4px;
}
//表格
.readonly {
  width: 49%;
  display: inline-flex;
  height: 40px;
}
/deep/.el-form-item__label {
  width: 170px;
  text-align: left;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #8890b1;
  line-height: 16px;
}
//下拉框
.goodsname {
  width: 40%;
}
.goodsname:first-child {
  width: 140px;
}
//注意字体
.fontsize {
  width: 312px;
  height: 17px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #afb5cb;
  line-height: 17px;
}
//比例文字
.proportion {
  color: #ff2c58;
}
.proportion1 {
  color: black;
}
.title {
  position: relative;
}
.title::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 30px;
  background: #5473e8;
  position: absolute;
  left: 0;
}
</style>
