<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.pastureArr"
        style="width: 220px"
        placeholder="牧场"
        multiple
        collapse-tags
        filterable collapse-tags-tooltip
        class="filter-item"
      >
           <div class="select_up">
                <el-button type="text" @click="selectAll">
                    <i class="jw jw-quanxuan " />
                    全选</el-button>
                <el-button type="text" @click="removeTag">
                    <i class="jw jw-qingkong " />
                    清空</el-button>
                <el-button type="text" @click="selectReverse">
                    <i class="jw jw-fanxuan " />
                    反选</el-button>
            </div>
            <div class="select_list">
        <el-option
          v-for="item in findAllPasture"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
        </div>
      </el-select>
         <el-input
            v-model="getdataListParm.parammaps.eqName"
            placeholder="设备名称"
            clearable
            style="width: 120px"
            class="filter-item"
          />
            <el-input
            v-model="getdataListParm.parammaps.eqCode"
            placeholder="设备内部编号"
            clearable
            style="width: 150px"
            class="filter-item"
          />
           <el-input
            v-model="getdataListParm.parammaps.financeCode"
            placeholder="财务编号"
            clearable
            style="width: 120px"
            class="filter-item"
          />
      <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-select
            v-model="getdataListParm.parammaps.status"
            clearable
            placeholder="状态"
            class="filter-item"
            style="width: 120px"
          >
            <el-option
              v-for="item in getDictByName"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
           <el-input
            v-model="getdataListParm.parammaps.cardCode"
            placeholder="油卡编号"
            clearable
            style="width: 120px"
            class="filter-item"
          />
      <!-- <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-date-picker
                  v-model="getdataListParm.parammaps.inputDatetime"
                  type="month"
                  placeholder="选择月">
                </el-date-picker>
      <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"
        ref="table"
      >
        <!-- <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="eqClassName" />
       <el-table-column label="设备名称" align="center" prop="eqName" />
        <el-table-column label="设备内部编号" align="center" prop="eqCode" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="置换日期"   align="center" prop="purchaseDate" />
        <el-table-column label="财务编号" align="center" prop="financeCode" />
        <el-table-column label="部门" align="center" prop="departmentName" />
        <el-table-column label="责任人" sortable align="center" prop="employeName" />
        <el-table-column label="物联网编码" sortable align="center" prop="license" />
        <el-table-column label="标准工作时长" sortable align="center" prop="duration" />
        <el-table-column label="油卡号" sortable align="center" prop="cardCode" />
        <el-table-column label="油卡类型" sortable align="center" prop="cardType" />
        <el-table-column label="油卡状态" sortable align="center" prop="enable" >
          </el-table-column>
        <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>
          </template>
        </el-table-column>
     </el-table>
      <pagination v-show="total>=0" :total="total" :page.sync="getdataListParm.parammaps.offset" :limit.sync="getdataListParm.parammaps.pagecount" @pagination="get_table_data" />
      <el-dialog title="查看详情" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="80%">
        <div class="app-change">
          <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="first">
                <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="8">
                <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="8">
                <el-form-item label="部门:" prop="departmentName">
                 <el-input ref="departmentName" v-model="see.temp.departmentName" placeholder="部门" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备类别:" prop="eqClassName">
                 <el-input ref="departmentName" v-model="see.temp.eqClassName" placeholder="设备类别" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="设备内部编号:" prop="eqCode">
                 <el-input ref="assetCode" v-model="see.temp.eqCode" placeholder="设备内部编号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <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="8">
                <el-form-item label="品牌:" prop="brandName">
                  <el-input ref="eqCode" v-model="see.temp.brandName" placeholder="品牌" disabled />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="8">

                <el-form-item label="用途:" prop="purpose">
                  <el-input ref="unit" v-model="see.temp.purpose" placeholder="用途" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="购置日期:" prop="purchaseDate">
                 <el-input ref="purchaseDate" v-model="see.temp.purchaseDate" placeholder="购置日期" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="财务编号:" prop="financeCode">
                 <el-input ref="financeCode" v-model="see.temp.financeCode" placeholder="财务编号" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="残值:" prop="salvage">
                  <el-input ref="salvage" v-model="see.temp.salvage" placeholder="残值" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="保养级别:" prop="upkeepgrade">
                 <el-input ref="upkeepgrade" v-model="see.temp.upkeepgrade" placeholder="保养级别" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="保养费用:" prop="yearUpkeepCost">
                 <el-input ref="yearUpkeepCost" v-model="see.temp.yearUpkeepCost" placeholder="保养费用" disabled />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="责任人:" prop="employeName">
                  <el-input ref="employeName" v-model="see.temp.employeName" placeholder="责任人" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物联网编码:" prop="license">
                 <el-input ref="license" v-model="see.temp.license" placeholder="物联网编码" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标准工作时长:" prop="duration">
                 <el-input ref="duration" v-model="see.temp.duration" placeholder="标准工作时长" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="油卡号:" prop="cardCode">
                  <el-input ref="cardCode" v-model="see.temp.cardCode" placeholder="油卡号" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="油卡类型:" prop="cardType">
                 <el-input ref="cardType" v-model="see.temp.cardType" placeholder="油卡类型" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="油卡状态:" prop="enable">
                 <el-input ref="enable" v-model="see.temp.enable" placeholder="油卡状态" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          </el-tab-pane>

          <el-tab-pane label="记录" name="second">
            <div style="margin-bottom: 60px;">
          <!-- <el-date-picker
            ref="inputDatetime2"
            v-model="getdataListParm.parammaps.inputDatetime"
            class="inputDatetime"
            type="month"
            style="width: 250px; top: -3px"
            format="yyyy-MM"
            value-format="yyyy-MM"
            range-separator="至"
            start-placeholder="购置日期"
            end-placeholder="购置日期"
            @change="getDateByList"
          /> -->
          <el-date-picker
            v-model="getdataListParm.parammaps.inputDatetime"
            type="month"
            @change="getDateByList"
            placeholder="选择月">
          </el-date-picker>

             <el-table
              key="tableRef"
              v-loading="listLoading"
              element-loading-text="给我一点时间"
              :data="recodeList"
              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 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="date" />
            <el-table-column label="工作时长/h" align="center" prop="hour" />
            <el-table-column label="加油量/L" align="center" prop="oilAmount" />
             </el-table>

            </div>

          </el-tab-pane>
        </el-tabs>


          <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 ,getBigData,getBigDataRecode, getDownLoadData} 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 {
      recodeList:[],
      mountDate:'',
      tableKey: 0,
      list: [],
      statusMap: [
            { id: 17, label: "正常", value: "正常" },
            { id: 18, label: "闲置", value: "闲置" },
            { id: 19, label: "报废", value: "报废" },
            { id: 20, label: "封存", value: "封存" }
        ],
      activeName: 'first',
      getDictByName:[],
      total: 0,
      listLoading: true,
      getdataListParm: {
        parammaps: { offset: 1, pagecount: 50, pastureId:'',  cardCode: '', status: '', departmentName: '', departmentId: '',eqCode:"",eqName:"",financeCode:"" ,inputDatetime:this.getCurrentMonthStart() , startTime: '', endTime: '',} // [this.getCurrentMonthStart(), this.getCurrentMonthEnd()]
      },
      isAssetinventorySee: [], isBasicsCard: [], isBasicsUpdate: [], isBasicsDel: [], isBasicsDel2: [], isBasic: [], isBasicSH: [], isBasicExamine: [],
      requestParams: [
          {
          name: 'getDictByName',
          offset: 0,
          pagecount: 0,
          params: ['资产状态']
        },
        { 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_select_list()

  },
  methods: {
    getDateByList(val) {
      console.log(val,'yue')
      this.handlegetBigDataRecode()
   },
    async handlegetBigDataRecode() {
       const obj = {
        startTime: '',
        endTime:"",
      }
      if (this.getdataListParm.parammaps.inputDatetime == '' || this.getdataListParm.parammaps.inputDatetime == null) {
        this.getdataListParm.parammaps.inputDatetime = ''
        obj.startTime = ''
        obj.endTime = ''
      } else {
        obj.startTime = parseTime(this.getdataListParm.parammaps.inputDatetime,'{y}-{m}')+'-01'
        obj.endTime = parseTime(this.getdataListParm.parammaps.inputDatetime,'{y}-{m}')+ '-31'
      }
      const { data } = await getBigDataRecode(obj)
      console.log(data, '记录')
      this.recodeList = data.list;

    },
     // 获取当前月份的开始日期
    getCurrentMonthStart() {
        const date = new Date();
        return new Date(date.getFullYear(), date.getMonth());
        // return new Date(date.getFullYear(), date.getMonth(), 1);
    },
    // 获取当前月份的结束日期
    getCurrentMonthEnd() {
        const date = new Date();
        return new Date(date.getFullYear(), date.getMonth() + 1, 0);
    },
    handleClick(){
      // this.get_table_data()
      this.activeName = 'second';
      if ( this.activeName == 'second') {
       this. handlegetBigDataRecode()
      }
    },
        // 删除
    removeTag() {
      this.getdataListParm.parammaps.pastureArr = []
    },
    // 全选
    selectAll(val) {
      val = []
      this.findAllPasture.map(item => {
          val.push(item.name)
      })
      this.getdataListParm.parammaps.pastureArr = val
    },
    // 反选
    selectReverse(val) {
        val = []
        this.findAllPasture.map(item => {
            let index = this.getdataListParm.parammaps.pastureArr.indexOf(item.name);
            if (index != -1) {
                //orgData.splice(index, 1)
            } else {
                val.push(item.name)
            }
        })
        this.getdataListParm.parammaps.pastureArr = val
    },
    // 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.getDictByName = response.data.getDictByName.list
          this.getdataListParm.parammaps.pastureArr = [Cookies.get('pasturename')]
          this.getDepartDownList()
           this.get_table_data()

        }
      })
    },
    getDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.findAllDepart = response.data.list
      })
    },
    get_table_data() {
      this.listLoading = true
      if (this.getdataListParm.parammaps.inputDatetime == '' || this.getdataListParm.parammaps.inputDatetime == null) {
        this.getdataListParm.parammaps.inputDatetime = ''
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.endTime = ''
      } else {
        this.getdataListParm.parammaps.startTime = parseTime(this.getdataListParm.parammaps.inputDatetime,'{y}-{m}')+'-01'
        this.getdataListParm.parammaps.endTime = parseTime(this.getdataListParm.parammaps.inputDatetime,'{y}-{m}')+ '-31'
      }
    if (this.getdataListParm.parammaps.departmentId == undefined) { this.getdataListParm.parammaps.departmentId = '' }

        // 对于多选的牧场,根据数组的名称来转换 pastureArr =》 pastureId TODO:
      if (this.getdataListParm.parammaps.pastureArr && this.getdataListParm.parammaps.pastureArr.length > 0) {
        const arr = this.findAllPasture.filter((item) => {
          if (this.getdataListParm.parammaps.pastureArr.includes(item.name)) {
            return item
          }
        })
        const ids = arr.map((child) => { return child.id })
        this.getdataListParm.parammaps.pastureId = ids.toString();
      }
      const obj = JSON.parse(JSON.stringify(this.getdataListParm.parammaps));

      delete obj.pastureArr
      delete obj.endTime
      delete obj.startTime
      getBigData(obj).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.list = response.data.list.map((child) => {
            const status = this.statusMap.find(item => item.id == child.status);
            child.status = status.value || '暂无状态'
            child.enable = child.enable == true ? '禁用' : '启用'
            return child;
          })
          this.pageNum = 1
          this.pageSize = response.data.pagecount
        } else {
          this.list = []
        }
        this.total = response.data.count
        this.listLoading = false;
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 100)

      })
    },
    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.endTime = ''
      } else {
        this.getdataListParm.parammaps.startTime = this.getdataListParm.parammaps.inputDatetime[0]
        this.getdataListParm.parammaps.endTime = 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
      this.activeName = 'first'
    },
    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 })
          }
        })
      })
    },

// 处理每一行数据，生成与表头对应的字段
 processData(downLoadList, filterVal, tHeader) {
   return downLoadList.map(item => {
     let row = {};
     // 遍历 filterVal，根据顺序提取相应字段的值
     filterVal.forEach((key, index) => {
       // 如果是 1 到 31 天的数据，处理工作时长和加油量
       if (key.includes('工作时长') || key.includes('加油量')) {
        // 对应工作时长
         item.day.forEach((child,indexl) => {
            if (tHeader[index].includes('工作时长')) {
              row[tHeader[index]] = item.hours[indexl];
            }
             // 对应加油量
            if (tHeader[index].includes('加油量')) {
              row[tHeader[index]] = item.diesel[indexl];
            }
          })
      } else {
        // 其他字段直接赋值
        row[filterVal[index]] = item[key];
      }
    });
    return row;
  });
},


    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 == '' || this.getdataListParm.parammaps.inputDatetime == null) {
        this.getdataListParm.parammaps.inputDatetime = ''
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.endTime = ''
      } else {
        this.getdataListParm.parammaps.startTime = parseTime(this.getdataListParm.parammaps.inputDatetime,'{y}-{m}')+'-01'
        this.getdataListParm.parammaps.endTime = parseTime(this.getdataListParm.parammaps.inputDatetime,'{y}-{m}')+ '-31'
      }
      if( this.getdataListParm.parammaps.departmentId == undefined){ this.getdataListParm.parammaps.departmentId = ''}

      const obj = JSON.parse(JSON.stringify(this.getdataListParm.parammaps));
      obj.pastureId = Cookies.get('pastureid');
      delete obj.pastureArr
      getDownLoadData(obj).then(response => {
        var downLoadList = response.data.list.map((child) => {
          const status = this.statusMap.find(item => item.id == child.status);
          child.status = status && status.value;
          child.enable = child.enable == true ? '禁用' : '启用'
          return child
        })


        const days = downLoadList[0].day;
        const currentData = downLoadList[0];
        let filterVal = []
        const filterVal0 = ['pastureName', 'eqClassName', 'eqName', 'eqCode', 'status', 'purchaseDate', 'financeCode', 'departmentName', 'employeName', 'license', 'duration', 'cardCode', 'cardType', 'enable'];
        filterVal = [...filterVal0];

        // 添加每一天的 hours 和 diesel 数据
        currentData.day.forEach(day => {
          filterVal.push(`${day}天(工作时长)`); // 添加对应的 hours
        });
        currentData.day.forEach(day => {
          filterVal.push(`${day}天(加油量)`); // 添加对应的 diesel
        });

        if (response.data.list !== '') {
          this.percentage = 99;
          setTimeout(() => {
            this.isPercentage = false;
          }, 2000);
        }

        const table = this.$refs.table;
        const labels = table.columns.map((column) => column.label !== '序号' && column.label !== '操作' ? column.label : null).filter(label => label !== null);
        const tHeader = [...labels, ...currentData.day.map(d => `${d}天(工作时长)`), ...currentData.day.map(d => `${d}天(加油量)`)];

        const processedData = this.processData(downLoadList, filterVal, tHeader);
        const elecExcelDatas = [
          {
            tHeader: tHeader,
            filterVal: filterVal,
            tableDatas: processedData,
            sheetName: '设备大数据',
            autowidth: true
          }
        ];
        console.log(elecExcelDatas, 'elecExcelDatas')
        json2excel(elecExcelDatas, '设备大数据', true, 'xlsx')
     })
    },

    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;
  }

  .select_up {
    padding: 0 12px;
    font-size: 14px;
    position: absolute;
    z-index: 99999;
    background-color: white;
    top: 0px;
    width: 100%;
    border-radius: 5px 5px 0 0;

    ::v-deep .el-button {
        color: #bcbcbc;
        font-size: 14px;

        i {
            font-size: 14px;
        }
    }

    ::v-deep .el-button:hover {
        color: #409EFF;
    }

        .el-button+.el-button {
            margin-left: 6px;
        }
    }

    .select_list {
        margin-top: 25px;
    }
</style>
