<template>
  <div class="app-container">
    <div v-if="isPercentage" class="percentage" style="width: 210px;height: 90px;background: #fff;position: fixed;bottom: 0;left: 0;z-index: 9999999999999;">
      <h4 style="padding-left: 10px;line-height: 0;">导出进度:</h4>
      <el-progress style="padding-left: 10px;" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    </div>
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureId" placeholder="牧场" class="filter-item" style="width: 120px;" @change="changePastureName">
        <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="getdataListParm.parammaps.departmentId" clearable placeholder="部门" class="filter-item" style="width: 120px;">
        <el-option v-for="item in findAllDepart" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-date-picker ref="inputDatetime" v-model="getdataListParm.parammaps.inputDatetime" class="inputDatetime" type="monthrange" style="width: 250px;top:-3px;" format="yyyy-MM" value-format="yyyy-MM" range-separator="至" start-placeholder="盘点日期" end-placeholder="盘点日期" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <el-button class="filter-item" type="info" icon="el-icon-tickets" style="" @click="handleDownloadTemp">模板</el-button>
      <el-upload style="display: inline-block;" :headers="headers" :data="uploadData" :action="uploadExcelUrl" :show-file-list="false" :before-upload="beforeImportExcel" :on-success="handleImportExcelSuccess">
        <el-button class="filter-item" type="warning" icon="el-icon-upload2">导入</el-button>
      </el-upload>

      <el-button class="filter-item" type="success" icon="el-icon-download" style="" @click="handleDownload">导出</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleDelete">批量删除</el-button>
    </div>
    <el-table
        :key="tableKey"
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
        @selection-change="handleSelectionChange"
        :max-height="myHeight"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="牧场" align="center" prop="pastureName" />
        <el-table-column label="部门" align="center" prop="departmentName" />
        <el-table-column label="资产编号" align="center" prop="assetCode" />
       <el-table-column label="资产名称" align="center" prop="eqName" />
        <el-table-column label="设备内部编号" align="center" prop="eqCode" />
        <el-table-column label="实物入账日期" align="center" prop="rzdate" />
        <el-table-column label="计量单位"   align="center" prop="unit" />
        <el-table-column label="规格" align="center" prop="specification" />
        <el-table-column label="资产数量" align="center" prop="quantity" />
        <el-table-column label="资产原值" sortable align="center" prop="yuanzhi" />
        <el-table-column label="实际盘点数" sortable align="center" prop="count" />
        <el-table-column label="盈亏量" sortable align="center" prop="profit" />
        <el-table-column label="有无标签" sortable align="center" prop="tag" />
        <el-table-column label="导入日期" sortable align="center" prop="importdate" />
        <el-table-column label="盘点时间" sortable align="center" prop="inventorydate" />
        <el-table-column label="盘点人" sortable align="center" prop="checkTakerName" />
        <el-table-column label="备注" sortable align="center" prop="remark" />
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="form_see(row)">查看</el-button>
            <el-button type="danger" size="mini" @click="form_delete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>=0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="get_table_data" />
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="80%">
        <div class="app-change">
          <el-form ref="seeTemp" :model="see.temp" label-position="right" label-width="115px" style="width: 90%;margin:0 auto 30px" @click.native.prevent @submit.native.prevent>
            <el-row>
              <el-col :span="6">
                <el-form-item label="牧场:" prop="pastureName">
                  <el-input ref="pastureName" v-model="see.temp.pastureName" placeholder="牧场" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门:" prop="departmentName">
                 <el-input ref="departmentName" v-model="see.temp.departmentName" placeholder="部门" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="资产编号:" prop="eqCode">
                  <el-input ref="eqCode" v-model="see.temp.eqCode" placeholder="资产编号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="资产名称:" prop="eqName">
                 <el-input ref="eqName" v-model="see.temp.eqName" placeholder="资产名称" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设备内部编号:" prop="assetCode">
                 <el-input ref="assetCode" v-model="see.temp.assetCode" placeholder="设备内部编号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="实物入账日期:" prop="rzdate">
                 <el-input ref="rzdate" v-model="see.temp.rzdate" placeholder="实物入账日期" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="计量单位:" prop="unit">
                  <el-input ref="unit" v-model="see.temp.unit" placeholder="计量单位" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="规格:" prop="specification">
                 <el-input ref="specification" v-model="see.temp.specification" placeholder="规格" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="资产数量:" prop="quantity">
                 <el-input ref="quantity" v-model="see.temp.quantity" placeholder="资产数量" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="资产原值:" prop="yuanzhi">
                 <el-input ref="yuanzhi" v-model="see.temp.yuanzhi" placeholder="资产原值" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="实际盘点数:" prop="count">
                  <el-input ref="count" v-model="see.temp.count" placeholder="实际盘点数" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="盈亏量:" prop="profit">
                 <el-input ref="profit" v-model="see.temp.profit" placeholder="盈亏量" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="有无标签:" prop="tag">
                 <el-input ref="tag" v-model="see.temp.tag" placeholder="有无标签" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="导入日期:" prop="importdate">
                 <el-input ref="importdate" v-model="see.temp.importdate" placeholder="导入日期" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="盘点时间:" prop="inventorydate">
                  <el-input ref="inventorydate" v-model="see.temp.inventorydate" placeholder="盘点时间" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="盘点人:" prop="checkTakerName">
                 <el-input ref="checkTakerName" v-model="see.temp.checkTakerName" placeholder="盘点人" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="备注:" prop="remark">
                 <el-input ref="remark" v-model="see.temp.remark" placeholder="备注" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:10px">
            <el-button @click="dialogFormVisible = false;">关闭</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { GetDataByName, GetDataByNames,checkButtons,postJson,getJson } from '@/api/common'
import { parseTime, json2excel } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
export default {
  inject: ['reload'],
  name: 'Assetinventory',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      getdataListParm: {
        name: 'getAssetList', page: 1, offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: { pastureId: parseInt(Cookies.get('pastureid')),  inputDatetime: '', startTime: '', stopTime: '', departmentId: '' }
      },
      isAssetinventorySee: [], isBasicsCard: [], isBasicsUpdate: [], isBasicsDel: [], isBasicsDel2: [], isBasic: [], isBasicSH: [], isBasicExamine: [],
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': "18" }}
      ],
      getDepartParam: { name: 'findAllDepart1', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid'), 'eId': Cookies.get('employeid') }},
      findAllPasture: [], findAllDepart: [],
      selectionList:[],
      textMap: { see: '查看设备信息' },
      dialogFormVisible: false,
      dialogStatus: '',
      see:{
        temp:{}
      },
      isPercentage:false,
      uploadImageUrl: process.env.VUE_APP_BASE_API + 'authdata/uploaderimage',
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      myHeight:document.documentElement.clientHeight - 85- 150
    }
  },
  computed: {
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        // importParams: '牧场,部门, 资产编号, 资产名称, 设备内部编号, 实物入账日期, 计量单位, 规格, 资产数量, 资产原值, 实际盘点数, 盈亏量, 有无标签, 备注',
        // sheetname: 'SheetJS'
      }
    },

    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/stock/import'
    }
  },



  created() {
    // this.get_buttons()
    this.get_table_data()

  },
  methods: {
    // get_buttons() {
    //   // 新增
    //   const AssetinventorySee = 'asset:assetinventory:see'
    //   const isAssetinventorySee = checkButtons(this.$store.state.user.buttons, AssetinventorySee)
    //   this.isAssetinventorySee = isAssetinventorySee
    // },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        if (response.data.list !== null) {
          this.findAllPasture = response.data.findAllPasture.list
          this.getDepartDownList()
        }
      })
    },
    getDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.findAllDepart = response.data.list
      })
    },
    get_table_data() {
      this.listLoading = true
      if (this.getdataListParm.parammaps.inputDatetime == null || this.getdataListParm.parammaps.inputDatetime == []) {
        this.getdataListParm.parammaps.inputDatetime = ''
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      } else {
        this.getdataListParm.parammaps.startTime = parseTime(this.getdataListParm.parammaps.inputDatetime[0],'{y}-{m}')+'-01'
        this.getdataListParm.parammaps.stopTime = parseTime(this.getdataListParm.parammaps.inputDatetime[1],'{y}-{m}')+ '-31'
      }
      // if( this.getdataListParm.parammaps.startTime == undefined){ this.getdataListParm.parammaps.startTime = ''}
      // if( this.getdataListParm.parammaps.stopTime == undefined){ this.getdataListParm.parammaps.stopTime = ''}
      if( this.getdataListParm.parammaps.departmentId == undefined){ this.getdataListParm.parammaps.departmentId = ''}
      let url ='/authdata/stock/list?'
      let data = 'offset=' + this.getdataListParm.offset
                + '&pagecount=' + this.getdataListParm.pagecount
                + '&pastureId=' + this.getdataListParm.parammaps.pastureId
                + '&departmentId=' + this.getdataListParm.parammaps.departmentId
                + '&startdate=' + this.getdataListParm.parammaps.startTime
                + '&enddate=' + this.getdataListParm.parammaps.stopTime
      getJson(url,data).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.list = response.data.list
          this.pageNum = 1
          this.pageSize = response.data.pagecount
        } else {
          this.list = []
        }
        this.total = response.data.count
        setTimeout(() => {
          this.listLoading = false
        }, 100)
        this.get_select_list()
      })
    },
    changePastureName(item) {
      this.getDepartParam.parammaps.pastureId = this.getdataListParm.parammaps.pastureId
      this.getdataListParm.parammaps.departmentId = ''
      this.getDepartDownList()
    },
    handleSelectionChange(item) {
      this.selectionList = item
    },
    form_search() {
      if (this.getdataListParm.parammaps.inputDatetime == null) {
        this.getdataListParm.parammaps.inputDatetime = ''
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      } else {
        this.getdataListParm.parammaps.startTime = this.getdataListParm.parammaps.inputDatetime[0]
        this.getdataListParm.parammaps.stopTime = this.getdataListParm.parammaps.inputDatetime[1]
      }
      this.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_see(row){
      this.see.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'see'
      this.dialogFormVisible = true
    },
    form_delete(row){
      MessageBox.confirm('确认删除此信息?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'authdata/stock/del'
        let data = {
          id:[row.id]
        }
        postJson(url,data).then(response => {
          if (response.msg !== 'fail') {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.get_table_data()
          } else {
            this.$notify({ title: '失败', message: response.data, type: 'warning', duration: 2000 })
          }
        })
      })
    },
    handleDelete(){
      if(this.selectionList.length == 0){
        this.$message({ type: 'error', message: '请选择要删除的信息！', duration: 2000 })
        return false
      }
      let array = []
      this.selectionList.forEach((item)=>{
        array.push(item.id)
      })
      let str = '确认删除选择的'+ array.length+ '条信息?'
      MessageBox.confirm(str, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'authdata/stock/del'
        let data = {
          id:array
        }
        postJson(url,data).then(response => {
          if (response.msg !== 'fail') {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.get_table_data()
          } else {
            this.$notify({ title: '失败', message: response.data, type: 'warning', duration: 2000 })
          }
        })
      })
    },
    handleDownloadTemp(){
      const elecExcelDatas = [
        {
          tHeader: ['序号','牧场','部门', '资产编号', '资产名称', '设备内部编号', '实物入账日期', '计量单位', '规格', '资产数量', '资产原值', '实际盘点数', '盈亏量', '有无标签', '备注'  ],
          filterVal: ['','','', '', '', '', '', '', '', '', '', '', '', '', ''],
          tableDatas: [],
          sheetName: '资产盘点模板'
        }
      ]
      json2excel(elecExcelDatas, '资产盘点模板', true, 'xlsx')
    },
    handleDownload() {
      this.$alert('设备基础信息正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      this.isPercentage = true
      this.percentage = 1
      var timer = setInterval(() => {
        this.percentage += 5
        if (this.percentage > 95) {
          this.percentage = 99
          clearInterval(timer)
        }
        this.percentage = this.percentage
      }, 1000)
      if (this.getdataListParm.parammaps.inputDatetime == null || this.getdataListParm.parammaps.inputDatetime == []) {
        this.getdataListParm.parammaps.inputDatetime = ''
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      } else {
        this.getdataListParm.parammaps.startTime = parseTime(this.getdataListParm.parammaps.inputDatetime[0],'{y}-{m}')+'-01'
        this.getdataListParm.parammaps.stopTime = parseTime(this.getdataListParm.parammaps.inputDatetime[1],'{y}-{m}')+ '-31'
      }
      if( this.getdataListParm.parammaps.departmentId == undefined){ this.getdataListParm.parammaps.departmentId = ''}
      let url ='/authdata/stock/list?'
      let data = 'offset=' + this.getdataListParm.offset
                + '&pagecount='+9999999
                + '&pastureId=' + this.getdataListParm.parammaps.pastureId
                + '&departmentId=' + this.getdataListParm.parammaps.departmentId
                + '&startdate=' + this.getdataListParm.parammaps.startTime
                + '&enddate=' + this.getdataListParm.parammaps.stopTime
      getJson(url,data).then(response => {
        var downLoadList = response.data.list
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        const elecExcelDatas = [
          {
            tHeader: ['牧场','部门', '资产编号', '资产名称', '设备内部编号', '实物入账日期', '计量单位', '规格', '资产数量', '资产原值', '实际盘点数', '盈亏量', '有无标签','导入日期','盘点日期','盘点人', '备注'],
            filterVal: ['pastureName','departmentName', 'eqCode', 'eqName', 'assetCode', 'rzdate', 'unit', 'specification', 'quantity', 'yuanzhi', 'count', 'profit', 'tag', 'importdate', 'inventorydate', 'checkTakerName', 'remark'],
            tableDatas: downLoadList,
            sheetName: '资产盘点'
          }
        ]
        json2excel(elecExcelDatas, '资产盘点', true, 'xlsx')
      })
    },
    // 导入
     beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
      if (res.msg === 'ok') {
        this.$message({ title: '成功', message: '导入成功:' + res.data.success + '条!', type: 'success', duration: 2000 })
        if (res.data.err_count > 0) {
          this.$notify({ title: '失败', message: '导入失败:' + res.data.err_count + '条!', type: 'danger', duration: 2000 })
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = res.data.result
            const tHeader = [
              '牧场','部门', '资产编号', '资产名称', '设备内部编号', '实物入账日期', '计量单位', '规格', '资产数量', '资产原值', '实际盘点数', '盈亏量', '有无标签', '备注','报错信息'
            ]
            const filterVal = [
              '牧场','部门', '资产编号', '资产名称', '设备内部编号', '实物入账日期', '计量单位', '规格', '资产数量', '资产原值', '实际盘点数', '盈亏量', '有无标签', '备注','error_msg'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '资产盘点模板报错信息',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        }
      } else {
        this.$notify({ title: '失败', message: '上传失败', type: 'danger', duration: 2000 })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    formatJsonTemp(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') { return parseTime(v[j])  } else { return v[j] } })
      )
    },
  }
}
</script>
<style lang="scss" scoped>
  .el-autocomplete-suggestion li{
    padding:0 3px!important;
  }
  .el-table .warning-row {
      background: oldlace;
  }
  .el-table .success-row {
      background: #f0f9eb;
  }
</style>
