<template>
  <div class="app-container">
    <div class="operation">
      <el-button class="success" @click="form_add">新增入库单</el-button>
      <el-button class="success" @click="handleInitial">初始化库存</el-button>
    </div>
    <div class="search">
      <el-date-picker v-model="table.getdataListParm.parammaps.inputDatetime" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px;" />
      <el-button class="el-icon-arrow-left elIconArrowLeft" @click="handleBefore" />
      <el-button class="el-icon-arrow-right elIconArrowRight" @click="handleNext" />
      <el-select v-model="table.getdataListParm.parammaps.feedid" placeholder="饲料名称" class="filter-item" style="width: 150px;" clearable>
        <el-option v-for="(item,index) in feedNameList" :key="index" :label="item.fname" :value="item.id" />
      </el-select>
      <el-select v-model="table.getdataListParm.parammaps.providerid" placeholder="供应商" class="filter-item" style="width: 150px;" clearable>
        <el-option v-for="(item,index) in supplierList" :key="index" :label="item.providerName" :value="item.id" />
      </el-select>
      <el-select v-model="table.getdataListParm.parammaps.islaid" placeholder="是否入库" class="filter-item" style="width: 150px;" clearable>
        <el-option v-for="(item,index) in islaidList" :key="index" :label="item.name" :value="item.name" />
      </el-select>
      <el-button class="successBorder" @click="form_search">查询</el-button>
      <el-button class="successBorder" @click="form_clear">重置</el-button>
    </div>

    <div class="table">
      <el-table :key="table.tableKey" v-loading="table.listLoading" element-loading-text="给我一点时间" :data="table.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed">
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库日期" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.laiddate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="饲料名称" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.feedname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.providername }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库重量（kg）" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.operateweight }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总价（元）" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sumprice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批号" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pcpde }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否入库" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.islaid }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createemp }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createdate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button class="miniPrimary" @click="form_see(row)">查看</el-button>
            <el-button v-if="row.islaid == '否'" class="miniSuccess" @click="form_edit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>

    <!-- 新增入库单 -->
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <div class="app-add">
        <el-form ref="createTemp" :rules="create.rules" :model="create.createTemp" label-position="right" label-width="160px" style="width: 90%;margin:0 auto 50px">
          <el-row>
            <el-col :span="24">
              <h3 style="width: 160px;text-align: right;">基础信息</h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="入库日期:" prop="laiddate">
                <el-date-picker v-model="create.createTemp.laiddate" :disabled="create.dialogStatus=='see'" class="filter-item" type="date" placeholder="入库日期" :clearable="false" :picker-options="create.pickerOptions1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="送货单编号:" prop="wagonnumber">
                <el-input ref="wagonnumber" v-model="create.createTemp.wagonnumber" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="送货单编号" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="饲料名称:" prop="feedname">
                <el-autocomplete v-model="create.createTemp.feedname" value-key="fname" class="inline-input" :fetch-suggestions="feedNameSearch" placeholder="请选择饲料名称" style="width:98%" :disabled="create.dialogStatus=='see' || create.dialogStatus=='update'" @select="handleSelectFeedName" @blur="blurFeedName">
                  <template slot-scope="{ item }">
                    <span>{{ item.fname }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="入库重量(kg):" prop="operateweight">
                <el-input ref="operateweight" v-model.trim="create.createTemp.operateweight" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="最多两位小数" type="number" :step="0.01" @blur="blurOperateweight" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商:" prop="providerid">
                <el-select v-model="create.createTemp.providerid" clearable placeholder="请选择供应商" :disabled="create.dialogStatus=='see'" class="filter-item" style="width: 100%" @change="changeSupplier">
                  <el-option v-for="(item,index) in supplierList" :key="index" :label="item.providerName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同编号:" prop="contractcode">
                <el-select v-model="create.createTemp.contractcode" clearable placeholder="请选择合同编号" :disabled="create.dialogStatus=='see'" class="filter-item" style="width: 100%" @change="changeContractNo">
                  <el-option v-for="(item,index) in contractNoList" :key="index" :label="item.contractcodeCat" :value="item.contractcode" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3 style="width: 160px;text-align: right;">价格信息</h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="单价(元):" prop="pricenew">
                <el-input ref="pricenew" v-model="create.createTemp.pricenew" :disabled="create.createTemp.contractcode !=='' || create.dialogStatus=='see'" class="filter-item" placeholder="最多两位小数" type="number" :step="0.01" @blur="blurPricenew" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总价(元):" prop="sumprice">
                <el-input ref="sumprice" v-model="create.createTemp.sumprice" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="最多两位小数" type="number" :step="0.01" @blur="blurSumprice" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3 style="width: 160px;text-align: right;">饲料信息</h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="毛重:" prop="grossweight">
                <el-input ref="grossweight" v-model.trim="create.createTemp.grossweight" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="最多两位小数" type="number" :step="0.01" @blur="blurGrossweight" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="皮重:" prop="tareweight">
                <el-input ref="tareweight" v-model.trim="create.createTemp.tareweight" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="最多两位小数" type="number" :step="0.01" @blur="blurTareweight" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="许可证号:" prop="licence">
                <el-input ref="licence" v-model="create.createTemp.licence" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="许可证号" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="批号:" prop="pcpde">
                <el-input ref="pcpde" v-model="create.createTemp.pcpde" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="批号" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3 style="width: 160px;text-align: right;">操作信息</h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="创建人:" prop="createemp">
                <el-input ref="createemp" v-model="create.createTemp.createemp" class="filter-item" placeholder="创建人" type="text" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建日期:" prop="createdate">
                <el-date-picker v-model="create.createTemp.createdate" class="filter-item" type="date" placeholder="创建日期" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注:" prop="remark">
                <el-input ref="remark" v-model="create.createTemp.remark" :disabled="create.dialogStatus=='see'" class="filter-item" placeholder="1-255字符" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;get_table_data(); ">关闭</el-button>
          <el-button v-if="create.dialogStatus !== 'see' " class="success" :disabled="isokDisable" @click="create.dialogStatus==='create'?add_dialog_save():form_edit_save()">确认</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 初始化库存 -->
    <el-dialog :title="textMap[initial.dialogStatus]" :visible.sync="initial.dialogFormVisible" :close-on-click-modal="false" width="80%" height="55%">
      <div class="app-add" style="height: 100%;margin: 0 auto 60px;">
        <div class="operation">
          <el-button style="float: left;margin-bottom:10px;" class="success" @click="handleInitialExport">模板下载</el-button>
          <el-upload style="float: left;margin-left: 10px;margin-bottom:10px;" action="" :auto-upload="false" accept=".xlsx, .xls" :show-file-list="false" :on-change="handleInitialImport">
            <el-button class="success">导入</el-button>
          </el-upload>
        </div>
        <div class="table">
          <el-table :key="initial.tableKey" v-loading="initial.listLoading" element-loading-text="给我一点时间" :data="initial.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed">
            <el-table-column label="序号" align="center" type="index" width="50px" />
            <el-table-column label="饲料名称" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存重量" min-width="130px" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stockweight" placeholder="最多两位小数" type="number" :step="0.01" style="width:95%;padding:10px 0;" />
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button class="cancelClose" @click="initial.dialogFormVisible = false; ">关闭</el-button>
            <el-button class="success" :disabled="isokDisable" @click="initialData()">确认</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { GetDataByName, GetDataByNames, checkButtons, calculativeWidth, ExecDataByConfig, failproccess } from '@/api/common'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { json2excel, parseTime } from '@/utils/index.js'
// import { getToken } from '@/utils/auth'
import xlsx from 'xlsx'
import { upload } from '@/utils/index.js'
export default {
  name: 'Warehousing',
  components: { Pagination },
  data() {
    return {
      feedNameList: [], // 饲料名称
      feedNameAddList: [], // 饲料名称新增
      supplierList: [], // 供应商
      contractNoList: [], // 合同编号
      islaidList: [{ id: 0, name: '是' }, { id: 1, name: '否' }], // 是否入库
      send_select_list: [
        { name: 'getFeedListEnable', offset: 0, pagecount: 0, parammaps: { pastureid: Cookies.get('pastureid') } },
        { name: 'getProviderListEnable', offset: 0, pagecount: 0, parammaps: { pastureid: Cookies.get('pastureid') } }
      ],
      table: {
        getdataListParm: {
          name: 'getFeedlaidList',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            inputDatetime: '',
            startTime: '',
            stopTime: '',
            feedid: '',
            islaid: '',
            providerid: ''
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true
      },
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() > Date.now()// 当天之前的时间可选
          }
        },
        createTemp: {
          laiddate: '', feedid: '', feedname: '', operateweight: '', providerid: '', providername: '', startweight: '', priceold: '', contractcode: '', pricenew: '', sumprice: '', grossweight: '', tareweight: '', licence: '', pcpde: '', createemp: '', createdate: '', remark: '', 'wagonnumber': ''
        },
        rules: {
          laiddate: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          feedname: [{ type: 'string', required: true, message: '必填', trigger: 'change' }],
          pricenew: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
        },
        getdataListParm: {
          name: 'getBigContractListEnable',
          offset: 0,
          pagecount: '',
          parammaps: { pastureid: Cookies.get('pastureid') }
        },
        getfeedNameParm: {
          name: 'getFeedListEnableV2',
          offset: 0,
          pagecount: '',
          parammaps: { pastureid: Cookies.get('pastureid') }
        }
      },
      initial: {
        dialogFormVisible: false,
        dialogStatus: '',
        rules: {},
        getdataListParm: {
          name: 'getinitFeed',
          page: 1,
          offset: 1,
          pagecount: 6,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid')
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        character: {
          fname: {
            text: '饲料名称',
            type: String
          },
          stockweight: {
            text: '库存重量',
            type: String
          }
        }
      },
      textMap: {
        create: '新增入库单',
        update: '编辑入库单',
        see: '查看入库单',
        initial: '初始化库存'
      },
      requestParam: {},
      isokDisable: false,
      isRoleEdit: [],
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },

  created() {
    this.get_auto_buttons()
    this.get_select_list()
    this.get_table_data()
  },

  methods: {
    get_auto_buttons() {
      const Edit = 'Warehousing'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    get_select_list() {
      GetDataByNames(this.send_select_list).then(response => {
        this.feedNameList = response.data.getFeedListEnable.list
        this.supplierList = response.data.getProviderListEnable.list
      })
    },
    handleBefore() {
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        var start = new Date(this.table.getdataListParm.parammaps.inputDatetime[0].setDate(this.table.getdataListParm.parammaps.inputDatetime[0].getDate() - 1))
        var stop = new Date(this.table.getdataListParm.parammaps.inputDatetime[1].setDate(this.table.getdataListParm.parammaps.inputDatetime[1].getDate() - 1))
        this.table.getdataListParm.parammaps.inputDatetime.length = 0
        this.table.getdataListParm.parammaps.inputDatetime.push(start, stop)
        this.$forceUpdate()
      }
    },
    handleNext() {
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        var start = new Date(this.table.getdataListParm.parammaps.inputDatetime[0].setDate(this.table.getdataListParm.parammaps.inputDatetime[0].getDate() + 1))
        var stop = new Date(this.table.getdataListParm.parammaps.inputDatetime[1].setDate(this.table.getdataListParm.parammaps.inputDatetime[1].getDate() + 1))
        this.table.getdataListParm.parammaps.inputDatetime.length = 0
        this.table.getdataListParm.parammaps.inputDatetime.push(start, stop)
        this.$forceUpdate()
      }
    },
    get_table_data() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      // console.log('点击了查询')
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        this.table.getdataListParm.parammaps.startTime = parseTime(this.table.getdataListParm.parammaps.inputDatetime[0], '{y}-{m}-{d}')
        this.table.getdataListParm.parammaps.stopTime = parseTime(this.table.getdataListParm.parammaps.inputDatetime[1], '{y}-{m}-{d}')
      } else {
        this.table.getdataListParm.parammaps.inputDatetime = ''
        this.table.getdataListParm.parammaps.startTime = ''
        this.table.getdataListParm.parammaps.stopTime = ''
      }
      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      console.log('点击了重置')
      this.table.getdataListParm.parammaps.inputDatetime = ''
      this.table.getdataListParm.parammaps.startTime = ''
      this.table.getdataListParm.parammaps.stopTime = ''
      this.table.getdataListParm.parammaps.feedid = ''
      this.table.getdataListParm.parammaps.islaid = ''
      this.table.getdataListParm.parammaps.providerid = ''
      this.table.getdataListParm.offset = 1
    },

    resetCreateTemp() {
      this.create.createTemp = {
        pastureid: Cookies.get('pastureid'), laiddate: parseTime(new Date(), '{y}-{m}-{d}'), feedid: '', feedname: '', operateweight: '', providerid: '', providername: '', startweight: '', priceold: '', contractcode: '', pricenew: '', sumprice: '', grossweight: '', tareweight: '', licence: '', pcpde: '', createemp: Cookies.get('employename'), createdate: parseTime(new Date(), '{y}-{m}-{d}'), remark: '', 'wagonnumber': ''
      }
      this.contractNoList = []
    },
    // 供应商
    changeSupplier(item) {
      console.log(item)
      if (item !== '') {
        this.create.createTemp.providername = this.supplierList.find(obj => obj.id == item).providerName
      } else {
        this.create.createTemp.providername = ''
        this.contractNoList = []
      }
      if (this.create.createTemp.feedid !== '' && this.create.createTemp.providerid !== '') {
        this.getContractNoList()
      }
    },
    // 合同编号
    changeContractNo(item) {
      if (item !== '') {
        this.create.createTemp.pricenew = this.contractNoList.find(obj => obj.contractcode == item).price
      } else {
        this.create.createTemp.pricenew = ''
      }
      if (this.create.createTemp.operateweight !== '' && this.create.createTemp.pricenew !== '') {
        this.create.createTemp.sumprice = parseFloat(this.create.createTemp.operateweight) * parseFloat(this.create.createTemp.pricenew)
        this.create.createTemp.sumprice = this.create.createTemp.sumprice.toFixed(2)
      }
    },
    getContractNoList() {
      this.create.getdataListParm.parammaps.feedid = this.create.createTemp.feedid
      this.create.getdataListParm.parammaps.providerid = this.create.createTemp.providerid
      GetDataByName(this.create.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.contractNoList = response.data.list
          this.create.createTemp.contractcode = ''
          this.create.createTemp.pricenew = ''
          this.create.createTemp.sumprice = ''
        } else {
          this.contractNoList = []
          this.create.createTemp.contractcode = ''
          this.create.createTemp.pricenew = ''
          this.create.createTemp.sumprice = ''
        }
      })
    },
    feedNameSearch(queryString, cb) {
      this.create.getfeedNameParm.parammaps['fname'] = queryString
      GetDataByName(this.create.getfeedNameParm).then(response => {
        console.log('模糊查询搜索data', response.data.list)
        if (response.data.list == null) {
          cb([])
        } else {
          cb(response.data.list)
        }
      })
    },
    handleSelectFeedName(item) {
      console.log('模糊查询选中值', item)
      this.create.createTemp.feedname = item.fname
      this.create.createTemp.feedid = item.id
      this.create.createTemp.startweight = item.stockweight
      this.create.createTemp.priceold = item.price
      this.create.createTemp.providerid = ''
      this.create.createTemp.providername = ''
      this.create.createTemp.contractcode = ''
      this.create.createTemp.pricenew = ''
      this.create.createTemp.sumprice = ''
      if (this.create.createTemp.feedid !== '' && this.create.createTemp.providerid !== '') {
        this.getContractNoList()
      }
    },
    blurFeedName() {
      this.create.createTemp.feedname = ''
      this.create.createTemp.feedid = ''
      this.create.createTemp.startweight = ''
      this.create.createTemp.priceold = ''
      this.create.createTemp.providerid = ''
      this.create.createTemp.providername = ''
      this.create.createTemp.contractcode = ''
      this.create.createTemp.pricenew = ''
      this.create.createTemp.sumprice = ''
    },
    // 入库重量
    blurOperateweight() {
      // 毛重grossweight皮重tareweight入库重量operateweight
      if (this.create.createTemp.grossweight !== '' && this.create.createTemp.operateweight !== '') {
        this.create.createTemp.tareweight = parseFloat(this.create.createTemp.grossweight) - parseFloat(this.create.createTemp.operateweight)
      }
      if (this.create.createTemp.grossweight !== '' && this.create.createTemp.operateweight !== '') {
        if (parseFloat(this.create.createTemp.operateweight) > parseFloat(this.create.createTemp.grossweight)) {
          this.create.createTemp.grossweight = this.create.createTemp.operateweight
          this.create.createTemp.tareweight = parseFloat(this.create.createTemp.operateweight) - parseFloat(this.create.createTemp.operateweight)
        }
      }
      if (this.create.createTemp.tareweight !== '' && this.create.createTemp.grossweight !== '') {
        if (this.create.createTemp.operateweight == '') {
          this.create.createTemp.operateweight = (parseFloat(this.create.createTemp.grossweight) - parseFloat(this.create.createTemp.tareweight))
        }
        if (parseFloat(this.create.createTemp.tareweight) > parseFloat(this.create.createTemp.grossweight)) {
          this.create.createTemp.tareweight = this.create.createTemp.grossweight
          this.create.createTemp.operateweight = (parseFloat(this.create.createTemp.grossweight) - parseFloat(this.create.createTemp.tareweight))
        }
      }
      if (this.create.createTemp.operateweight !== '' && this.create.createTemp.pricenew !== '') {
        this.create.createTemp.sumprice = parseFloat(this.create.createTemp.operateweight) * parseFloat(this.create.createTemp.pricenew)
        this.create.createTemp.sumprice = this.create.createTemp.sumprice.toFixed(2)
      } else {
        this.create.createTemp.sumprice = ''
      }
    },
    // 毛重
    blurGrossweight() {
      // 毛重grossweight皮重tareweight入库重量operateweight
      if (this.create.createTemp.grossweight !== '' && this.create.createTemp.operateweight !== '') {
        this.create.createTemp.tareweight = parseFloat(this.create.createTemp.grossweight) - parseFloat(this.create.createTemp.operateweight)
      }

      if (this.create.createTemp.grossweight !== '' && this.create.createTemp.operateweight !== '') {
        if (parseFloat(this.create.createTemp.operateweight) > parseFloat(this.create.createTemp.grossweight)) {
          this.create.createTemp.grossweight = this.create.createTemp.operateweight
          this.create.createTemp.tareweight = parseFloat(this.create.createTemp.operateweight) - parseFloat(this.create.createTemp.operateweight)
        }
      }
    },
    // 皮重
    blurTareweight() {
      // 毛重grossweight皮重tareweight入库重量operateweight
      if (this.create.createTemp.operateweight !== '' && this.create.createTemp.tareweight !== '') {
        this.create.createTemp.grossweight = parseFloat(this.create.createTemp.tareweight) + parseFloat(this.create.createTemp.operateweight)
      }
      if (this.create.createTemp.grossweight !== '' && this.create.createTemp.operateweight !== '') {
        if (parseFloat(this.create.createTemp.operateweight) > parseFloat(this.create.createTemp.grossweight)) {
          this.create.createTemp.grossweight = this.create.createTemp.operateweight
          this.create.createTemp.tareweight = parseFloat(this.create.createTemp.operateweight) - parseFloat(this.create.createTemp.operateweight)
        }
      }
      if (this.create.createTemp.tareweight !== '' && this.create.createTemp.grossweight !== '') {
        if (parseFloat(this.create.createTemp.tareweight) > parseFloat(this.create.createTemp.grossweight)) {
          this.create.createTemp.tareweight = this.create.createTemp.grossweight
          this.create.createTemp.operateweight = (parseFloat(this.create.createTemp.grossweight) - parseFloat(this.create.createTemp.tareweight))
        }
      }
    },
    // 单价
    blurPricenew() {
      if (this.create.createTemp.operateweight !== '' && this.create.createTemp.pricenew !== '') {
        this.create.createTemp.sumprice = parseFloat(this.create.createTemp.operateweight) * parseFloat(this.create.createTemp.pricenew)
        this.create.createTemp.sumprice = this.create.createTemp.sumprice.toFixed(2)
      } else {
        this.create.createTemp.sumprice = ''
      }
    },
    // 总价
    blurSumprice() {
      if (this.create.createTemp.sumprice !== '' && this.create.createTemp.pricenew !== '') {
        this.create.createTemp.operateweight = parseFloat(this.create.createTemp.sumprice) / parseFloat(this.create.createTemp.pricenew)
        this.create.createTemp.operateweight = this.create.createTemp.operateweight.toFixed(2)
      } else {
        this.create.createTemp.operateweight = ''
      }
    },
    form_add() {
      console.log('点击了新增入库单')
      this.resetCreateTemp()
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.createTemp.resetFields()
      })
    },
    add_dialog_save() {
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          if (this.create.createTemp.operateweight == '' && this.create.createTemp.grossweight == '') {
            this.$message({ type: 'error', message: '请输入入库重量或毛重', duration: 2000 })
            return false
          }
          if (this.create.createTemp.sumprice.length > 15) {
            this.$message({ type: 'error', message: '数值过大请重新输入', duration: 2000 })
          }
          const keepTwoNum = /^\d+(\.\d{1,2})?$/
          // 入库重量
          if (this.create.createTemp.operateweight !== '') {
            if (this.create.createTemp.operateweight == 0) {
              this.$message({ type: 'error', message: '入库重量请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.operateweight))) {
                this.$message({ type: 'error', message: '入库重量请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          // 单价
          if (this.create.createTemp.pricenew == 0) {
            this.$message({ type: 'error', message: '单价请输入自然数并保留两位小数', duration: 2000 })
            return false
          } else {
            if (!keepTwoNum.test(parseFloat(this.create.createTemp.pricenew))) {
              this.$message({ type: 'error', message: '单价请输入自然数并保留两位小数', duration: 2000 })
              return false
            }
          }
          // 总价
          if (this.create.createTemp.pricenew !== '' && this.create.createTemp.operateweight !== '') {
            if (this.create.createTemp.sumprice == 0) {
              this.$message({ type: 'error', message: '总价请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.sumprice))) {
                this.$message({ type: 'error', message: '总价请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          // 毛重
          if (this.create.createTemp.grossweight !== '') {
            if (this.create.createTemp.grossweight == 0) {
              this.$message({ type: 'error', message: '毛重请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.grossweight))) {
                this.$message({ type: 'error', message: '毛重请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          // 皮重
          if (this.create.createTemp.tareweight !== '') {
            if (this.create.createTemp.tareweight == 0) {
              this.$message({ type: 'error', message: '皮重请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.tareweight))) {
                this.$message({ type: 'error', message: '皮重请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }

          MessageBox.confirm('是否确认保存当前内容', {            confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
          }).then(() => {
            this.isokDisable = true
            setTimeout(() => {
              this.isokDisable = false
            }, 1000)
            this.requestParam.common = { 'returnmap': '0' }
            this.requestParam.data = []
            this.requestParam.data[0] = {              'name': 'insertFeedlaid', 'type': 'e', 'parammaps': {
                'pastureid': this.create.createTemp.pastureid,
                'laiddate': this.create.createTemp.laiddate,
                'feedid': this.create.createTemp.feedid,
                'feedname': this.create.createTemp.feedname,
                'providerid': this.create.createTemp.providerid,
                'providername': this.create.createTemp.providername,
                'contractcode': this.create.createTemp.contractcode,
                'operateweight': this.create.createTemp.operateweight,
                'grossweight': this.create.createTemp.grossweight,
                'tareweight': this.create.createTemp.tareweight,
                'sumprice': this.create.createTemp.sumprice,
                'licence': this.create.createTemp.licence,
                'pcpde': this.create.createTemp.pcpde,
                'remark': this.create.createTemp.remark,
                'createdate': this.create.createTemp.createdate,
                'createemp': this.create.createTemp.createemp,
                'startweight': this.create.createTemp.startweight,
                'priceold': this.create.createTemp.priceold,
                'pricenew': this.create.createTemp.pricenew,
                'wagonnumber': this.create.createTemp.wagonnumber
              }            }
            if (this.create.createTemp.operateweight !== '' && parseFloat(this.create.createTemp.operateweight) > 0) {
              this.requestParam.data[1] = {                'name': 'insertFeedstorageLaid', 'type': 'e', 'parammaps': {
                  'operateweight': this.create.createTemp.operateweight,
                  'pastureid': this.create.createTemp.pastureid,
                  'feedid': this.create.createTemp.feedid,
                  'fname': this.create.createTemp.fname,
                  'pcpde': this.create.createTemp.pcpde,
                  'stockweight': this.create.createTemp.startweight,
                  'price': this.create.createTemp.pricenew
                }              }
            }
            console.log('点击了新增入库单保存', this.requestParam)
            ExecDataByConfig(this.requestParam).then(response => {
              if (response.msg === 'fail') {
                failproccess(response, this.$notify)
              } else {
                this.$notify({ title: '', message: '成功', type: 'success', duration: 2000 })
                this.create.dialogFormVisible = false
                this.get_table_data()
              }
            })
          })
        }
      })
    },
    form_edit(row) {
      console.log('点击了编辑')
      this.$nextTick(() => {
        this.$refs.createTemp.resetFields()
      })
      this.create.dialogStatus = 'update'
      this.create.dialogFormVisible = true
      row.feedid = String(row.feedid)
      this.create.createTemp = Object.assign({}, row)
    },
    form_edit_save() {
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          if (this.create.createTemp.operateweight == '' && this.create.createTemp.grossweight == '') {
            this.$message({ type: 'error', message: '请输入入库重量或毛重', duration: 2000 })
            return false
          }
          if (this.create.createTemp.sumprice.length > 15) {
            this.$message({ type: 'error', message: '数值过大请重新输入', duration: 2000 })
          }
          const keepTwoNum = /^\d+(\.\d{1,2})?$/
          // 入库重量
          if (this.create.createTemp.operateweight !== '') {
            if (this.create.createTemp.operateweight == 0) {
              this.$message({ type: 'error', message: '入库重量请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.operateweight))) {
                this.$message({ type: 'error', message: '入库重量请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          // 单价
          if (this.create.createTemp.pricenew == 0) {
            this.$message({ type: 'error', message: '单价请输入自然数并保留两位小数', duration: 2000 })
            return false
          } else {
            if (!keepTwoNum.test(parseFloat(this.create.createTemp.pricenew))) {
              this.$message({ type: 'error', message: '单价请输入自然数并保留两位小数', duration: 2000 })
              return false
            }
          }
          // 总价
          if (this.create.createTemp.pricenew !== '' && this.create.createTemp.operateweight !== '') {
            if (this.create.createTemp.sumprice == 0) {
              this.$message({ type: 'error', message: '总价请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.sumprice))) {
                this.$message({ type: 'error', message: '总价请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          // 毛重
          if (this.create.createTemp.grossweight !== '') {
            if (this.create.createTemp.grossweight == 0) {
              this.$message({ type: 'error', message: '毛重请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.grossweight))) {
                this.$message({ type: 'error', message: '毛重请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          // 皮重
          if (this.create.createTemp.tareweight !== '') {
            if (this.create.createTemp.tareweight == 0) {
              this.$message({ type: 'error', message: '皮重请输入自然数并保留两位小数', duration: 2000 })
              return false
            } else {
              if (!keepTwoNum.test(parseFloat(this.create.createTemp.tareweight))) {
                this.$message({ type: 'error', message: '皮重请输入自然数并保留两位小数', duration: 2000 })
                return false
              }
            }
          }
          MessageBox.confirm('是否确认保存当前内容', {            confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
          }).then(() => {
            this.isokDisable = true
            setTimeout(() => {
              this.isokDisable = false
            }, 1000)
            this.requestParam.common = { 'returnmap': '0' }
            this.requestParam.data = []
            this.requestParam.data[0] = {              'name': 'updateFeedlaid', 'type': 'e', 'parammaps': {
                'pastureid': this.create.createTemp.pastureid,
                'id': this.create.createTemp.id,
                'laiddate': this.create.createTemp.laiddate,
                'feedid': this.create.createTemp.feedid,
                'feedname': this.create.createTemp.feedname,
                'providerid': this.create.createTemp.providerid,
                'providername': this.create.createTemp.providername,
                'contractcode': this.create.createTemp.contractcode,
                'operateweight': this.create.createTemp.operateweight,
                'grossweight': this.create.createTemp.grossweight,
                'tareweight': this.create.createTemp.tareweight,
                'sumprice': this.create.createTemp.sumprice,
                'licence': this.create.createTemp.licence,
                'pcpde': this.create.createTemp.pcpde,
                'remark': this.create.createTemp.remark,
                'createdate': this.create.createTemp.createdate,
                'createemp': this.create.createTemp.createemp,
                'startweight': this.create.createTemp.startweight,
                'priceold': this.create.createTemp.priceold,
                'pricenew': this.create.createTemp.pricenew,
                'wagonnumber': this.create.createTemp.wagonnumber
              }            }
            if (this.create.createTemp.operateweight !== '' && parseFloat(this.create.createTemp.operateweight) > 0) {
              this.requestParam.data[1] = {                'name': 'insertFeedstorageLaid', 'type': 'e', 'parammaps': {
                  'operateweight': this.create.createTemp.operateweight,
                  'pastureid': this.create.createTemp.pastureid,
                  'feedid': this.create.createTemp.feedid,
                  'fname': this.create.createTemp.fname,
                  'pcpde': this.create.createTemp.pcpde,
                  'stockweight': this.create.createTemp.startweight,
                  'price': this.create.createTemp.pricenew
                }              }
            }
            console.log('点击了新增入库单保存', this.requestParam)
            ExecDataByConfig(this.requestParam).then(response => {
              if (response.msg === 'fail') {
                failproccess(response, this.$notify)
              } else {
                this.$notify({ title: '', message: '成功', type: 'success', duration: 2000 })
                this.create.dialogFormVisible = false
                this.get_table_data()
              }
            })
          })
        }
      })
    },
    form_see(row) {
      console.log('点击了查看')
      this.$nextTick(() => {
        this.$refs.createTemp.resetFields()
      })
      this.create.dialogStatus = 'see'
      this.create.dialogFormVisible = true
      this.create.createTemp = Object.assign({}, row)
    },

    handleInitial() {
      console.log('点击了初始化库存')
      this.initial.dialogStatus = 'initial'
      this.initial.dialogFormVisible = true

      this.getInitialList()
    },
    getInitialList() {
      this.initial.listLoading = true
      GetDataByName(this.initial.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.initial.list = response.data.list
          this.initial.pageNum = response.data.pageNum
          this.initial.pageSize = response.data.pageSize
          this.initial.total = response.data.total
        } else {
          this.initial.list = []
        }
        setTimeout(() => {
          this.initial.listLoading = false
        }, 100)
      })
    },
    handleInitialExport() {
      console.log('点击了初始化库存导出')

      const ExcelDatas = [
        {
          tHeader: ['饲料名称', '库存重量'],
          filterVal: ['fname', 'stockweight'],
          tableDatas: this.initial.list,
          sheetName: '初始化库存'
        }
      ]
      json2excel(ExcelDatas, '初始化库存', true, 'xlsx')
    },
    async handleInitialImport(eve) {
      const file = eve.raw
      if (!file) return
      let reader = await upload(file)
      const worker = xlsx.read(reader, { type: 'binary' })
      // 将返回的数据转换为json对象的数据
      reader = xlsx.utils.sheet_to_json(worker.Sheets[worker.SheetNames[0]])
      console.log(reader)
      const arr = []
      reader.forEach(item => {
        const obj = {}
        for (const key in this.initial.character) {
          if (!this.initial.character.hasOwnProperty(key)) break
          let v = this.initial.character[key]
          const text = v.text
          const type = v.type
          v = item[text] || ''
          type === 'string' ? (v = String(v)) : null
          type === 'number' ? (v = Number(v)) : null
          obj[key] = v
        }
        arr.push(obj)
      })
      console.log('导入处理后数据', arr)
      var sum = 0
      for (let i = 0; i < this.initial.list.length; i++) {
        for (let j = 0; j < arr.length; j++) {
          if (this.initial.list[i].fname == arr[j].fname) {
            this.initial.list[i].stockweight = arr[j].stockweight
            sum++
            arr.splice(j, 1)
          }
        }
      }
      console.log(arr)
      for (let i = 0; i < arr.length; i++) {
        this.$set(arr[i], 'msg', '饲料名称与系统不匹配')
      }
      console.log(sum)
      this.$message({ title: '成功', message: '导入成功:' + sum + '条!', type: 'success', duration: 2000 })
      this.$notify({ title: '失败', message: '导入失败:' + arr.length + '条!', type: 'danger', duration: 2000 })
      if (arr.length > 0) {
        const ExcelDatas1 = [
          {
            tHeader: ['饲料名称', '库存重量', '报错信息'],
            filterVal: ['fname', 'stockweight', 'msg'],
            tableDatas: arr,
            sheetName: 'ExcelDatas1'
          }
        ]
        json2excel(ExcelDatas1, '初始化库存报错信息', true, 'xlsx')
      }
    },
    initialData() {
      console.log('点击了初始化库存保存')
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      var rulesStockweight = /^\d+(\.\d{1,2})?$/
      for (let i = 0; i < this.initial.list.length; i++) {
        if (!rulesStockweight.test(parseFloat(this.initial.list[i].stockweight))) {
          this.$message({ type: 'warning', message: '库存重量不可小于0，且保留俩位小数', duration: 2000 })
          return false
        }
      }
      this.requestParam.common = { 'returnmap': '0' }
      this.requestParam.data = []
      this.requestParam.data[0] = {        'name': 'clearFS', 'type': 'e', 'parammaps': {
          'pastureid': Cookies.get('pastureid')
        }      }
      this.requestParam.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.initial.list } }
      this.requestParam.data[1].children = []
      this.requestParam.data[1].children[0] = {        'name': 'insertFeedstorage', 'type': 'e', 'parammaps': {
          pastureid: '@insertSpotList.pastureid',
          feedid: '@insertSpotList.feedid',
          fname: '@insertSpotList.fname',
          pcpde: '@insertSpotList.pcpde',
          stockweight: '@insertSpotList.stockweight',
          price: '@insertSpotList.price'
        }      }
      ExecDataByConfig(this.requestParam).then(response => {
        if (response.msg === 'fail') {
          failproccess(response, this.$notify)
        } else {
          this.$notify({ title: '', message: '成功', type: 'success', duration: 2000 })
          this.create.dialogFormVisible = false
          this.get_table_data()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.search {
  margin-top: 10px;
}
.table {
  margin-top: 10px;
}
</style>
