<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="getdataListParmImportInfo.parammaps.pastureName"
        placeholder="牧场"
        class="filter-item"
        style="width:110px"
      >
        <el-option
          v-for="item in findAllPasture"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-select
        v-model="getdataListParmImportInfo.parammaps.deptName"
        clearable
        placeholder="部门"
        class="filter-item"
        style="width:110px"
      >
        <el-option
          v-for="item in findAllDepart"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-input
        v-model="getdataListParmImportInfo.parammaps.useForm"
        placeholder="领用单号"
        style="width: 110px;"
        class="filter-item"
      />
      <el-input
        v-model="getdataListParmImportInfo.parammaps.stockNumber"
        placeholder="备件编号"
        style="width: 110px;"
        class="filter-item"
      />
      <el-input
        v-model="getdataListParmImportInfo.parammaps.stockName"
        placeholder="备件名称"
        style="width: 110px;"
        class="filter-item"
      />
      <el-date-picker
        v-model="getdataListParmImportInfo.parammaps.receiveTime"
        type="date"
        placeholder="出库日期"
        style="width:140px;top:-3px;"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      />
      <el-select
        v-model="getdataListParmImportInfo.parammaps.applicatName"
        clearable
        placeholder="领用人"
        class="filter-item"
        style="width:110px"
      >
        <el-option
          v-for="item in findAllEmploye"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="form_search"
      >搜索</el-button>
      <div>
        <el-upload
          style="display: inline-block;"
          :headers="headers"
          :data="uploadData"
          :action="uploadExcelUrl"
          :show-file-list="false"
          :before-upload="beforeImportExcel"
          :on-success="handleImportExcelSuccess"
        >
          <el-button
            v-if="isReceiveImport"
            v-waves
            class="filter-item"
            type="warning"
            icon="el-icon-upload2"
          >导入</el-button>
        </el-upload>
        <el-button
          v-waves
          class="filter-item"
          type="info"
          icon="el-icon-download"
          @click="handleDownloadTemp"
        >模板</el-button>
        <el-button
          style="position: absolute;"
          type="danger"
          @click="form_delete(selection)"
        >批量删除
        </el-button>
      </div>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoadingImportInfo"
      element-loading-text="给我一点时间"
      :data="listImportInfo"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
      @selection-change="handleSelectionChange"
    >
      <!-- 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="牧场" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用单编号" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.useForm }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用部门" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用人" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.applicatName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用时间" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.receiveTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领用类型" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.fClass }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.stockNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品名" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.stockName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.specification }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.brand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计量单位" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实发数量" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.useNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</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.location }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.providerName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.assetName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="牧场设备编号" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.equipmentNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="具体用处" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.purpose }}</span>
        </template>
      </el-table-column>
      <el-table-column label="导入人" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.inputName }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="totalImportInfo"
      :page.sync="getdataListParmImportInfo.offset"
      :limit.sync="getdataListParmImportInfo.pagecount"
      @pagination="getListImportInfo"
    />
    <el-dialog
      :title="textMap[dialogStatusErro]"
      :visible.sync="dialogFormVisibleErro"
      :close-on-click-modal="false"
    >
      <div class="app-erro">
        <el-table
          :key="tableKey"
          v-loading="listLoadingErro"
          element-loading-text="给我一点时间"
          :data="listErro"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
        >
          <!-- table表格 -->
          <el-table-column label="序号" align="center" type="index" min-width="50px">
            <template slot-scope="scope">
              <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="错误信息" min-width="110px" align="center">
            <template slot-scope="scope">
              <span><b>错误行：</b>{{ scope.row.input }}</span><br><span><b>错误信息：</b>{{ scope.row.error_msg }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// / 引入
import { GetDataByName, GetDataByNames, ExecDataByConfig, GetAccount } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils/index.js'
// eslint-disable-next-line no-unused-vars
import { validateEMail } from '@/utils/validate.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Cookies from 'js-cookie'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
export default {
  name: 'OutRecord',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      totalImportInfo: 0,
      listLoadingImportInfo: true,
      listLoadingErro: true,
      listImportInfo: [],
      isReceiveImport: [],
      isReceiveAdd: [],
      display: true,
      tableKey: 0,
      list: [],
      list2: [],
      listErro: [],
      total: 0,
      value: false,
      listLoading: true,
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      requestParamDelete: {},
      requestFilterParams: {
        returntype: 'Map',
        parammaps: {}
      },
      // 1-2:table& 搜索传参
      getdataListParmImportInfo: {
        name: 'getImportStockUseList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          deptName: '',
          useForm: '',
          stockNumber: '',
          stockName: '',
          receiveTime: '',
          fClass: '',
          sClass: '',
          applicatName: ''
        }
      },
      getdataListParmCreate: {
        name: 'createOddNumber',
        page: 0,
        offset: 0,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {}
      },
      // 2-3：下拉框请求后数据加入[]
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      getDictByName: [],
      getDictByName1: [],
      getDictByName2: [],
      getDictByName3: [],
      // 2-1.请求下拉框接口
      requestParams: [
        { name: 'findAllProvider', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllAssetType', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'getDictByName', offset: 0, pagecount: 0, params: ['耗用类别-父'] },
        { name: 'getDictByName1', offset: 0, pagecount: 0, params: ['耗用类别-子'] },
        { name: 'getDictByName2', offset: 0, pagecount: 0, params: ['审核状态'] },
        { name: 'getDictByName3', offset: 0, pagecount: 0, params: ['旧品回收状态'] }
      ],
      stockAAA: {
        stockA: '',
        stockNumber: '',
        stockName: '',
        specification: '',
        amount: '',
        note: ''
      },
      bigAAA: {
        bigId: '',
        listTypeA: ''
      },
      postDataPramas: {

      },
      temp: {
        inputDatetime: parseTime(new Date(), '{y}-{m}-{d}'),
        note: '',
        employeId: this.$store.state.user.employeid,
        departmentId: this.$store.state.user.departmentid,
        pastureId: this.$store.state.user.pastureid
      },
      tempExamine: {},
      searchBtnVisible: true,
      dialogFormVisibleErro: false,
      dialogStatusErro: '',
      textMap: {
        erro: '导入错误信息'
      },
      dialogPvVisible: false,
      // 校验规则
      rules: {},
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      isPercentage: false,
      percentage: 1
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        // eslint-disable-next-line no-undef
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importStockUse',
        importParams: '牧场,领用单编号,领用日期,物料编码,品名,规格型号,品牌,计量单位,实发数量,库位,供应商,单价,总价,名称,牧场设备编号,具体用处,领用类型,领用部门,领用人,jwt_username',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  created() {
    this.get_select_list()
    this.getListImportInfo()
  },

  methods: {
    createFilter(queryString) {
      return returnValue => {
        return (
          returnValue.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleSelect(item) {
      // console.log(item)
      this.temp.providerId = item.id
      this.temp.providerName = item.name
    },
    // 1-1: 导入信息table&搜索
    getListImportInfo() {
      this.listLoadingImportInfo = true
      if (this.getdataListParmImportInfo.parammaps.receiveTime === null) {
        this.getdataListParmImportInfo.parammaps.receiveTime = ''
      }
      GetDataByName(this.getdataListParmImportInfo).then(response => {
        this.listImportInfo = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        // console.log(this.list)
        if (response.data.total) {
          this.totalImportInfo = response.data.total
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoadingImportInfo = false
        }, 100)
      })
    },
    form_search() {
      this.listLoadingImportInfo = true
      this.getdataListParmImportInfo.offset = 1
      this.getListImportInfo()
    },
    // 2-2：下拉框
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllProvider = response.data.findAllProvider.list
        this.findAllAssetType = response.data.findAllAssetType.list
        this.findAllPasture = response.data.findAllPasture.list
        this.findAllDepart = response.data.findAllDepart.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.getDictByName = response.data.getDictByName.list
        this.getDictByName1 = response.data.getDictByName1.list
        this.getDictByName2 = response.data.getDictByName2.list
        this.getDictByName3 = response.data.getDictByName3.list
      })
    },
    form_reset() {
      // this.temp.typeName = ''
      // this.temp.assTypeId = ''
      this.temp.note = ''
      this.temp.inputDatetime = parseTime(new Date(), '{y}-{m}-{d}')
      this.temp.employeId = this.$store.state.user.employeid
      this.temp.departmentId = this.$store.state.user.departmentid
      this.temp.pastureId = this.$store.state.user.pastureid
      this.list2 = null
    },
    // 导出模板
    handleDownloadTemp() {
      this.requestParam.name = 'stockUseDownTemp'
      GetDataByName(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
              '牧场', '领用单编号', '领用日期', '物料编码', '品名', '规格型号', '品牌', '计量单位', '实发数量', '单价', '总价', '库位', '供应商', '名称', '牧场设备编号', '具体用处', '领用类型', '领用部门', '领用人']
            const filterVal = [
              '牧场', '领用单编号', '领用日期', '物料编码', ' 品名', '规格型号', '品牌', '计量单位', '实发数量', '单价', '总价', '库位', '供应商', '名称', '牧场设备编号', '具体用处', '领用类型', '领用部门', '领用人']
            const data1 = this.formatJsonTemp(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '领用模板',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    formatJsonTemp(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },

    // 导出
    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)
      this.requestParam.name = 'bigStockUseDown'
      this.requestParam.parammaps.useForm = this.getdataListParm.parammaps.useForm
      this.requestParam.parammaps.createTime = this.getdataListParm.parammaps.createTime
      this.requestParam.parammaps.createTime = this.getdataListParm.parammaps.useStatus
      GetAccount(this.requestParam).then(response => {
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
              '领用单号', '类型(保养/维修）', '牧场名称', '部门名称', '申请人', '创建时间', '部门主管审核状态', '厂长助理审核状态', '审核状态', '厂长助理审核', '厂长助理审核时间', '审核时间',
              '部门主管审核', '维修单/保养单', '领用状态', '旧品状态', '备件编号', '备件名称', '用途', '规格', '领用数量', '单价', '单件总价', '耗用类别(父)', '耗用类别(子)'
            ]
            const filterVal = [
              '领用单号', '类型(保养/维修）', '牧场名称', '部门名称', '申请人', '创建时间', '部门主管审核状态', '厂长助理审核状态', '审核状态', '厂长助理审核', '厂长助理审核时间', '审核时间',
              '部门主管审核', '维修单/保养单', '领用状态', '旧品状态', '备件编号', '备件名称', '用途', '规格', '领用数量', '单价', '单件总价', '耗用类别(父)', '耗用类别(子)'
            ]
            if (list1 !== null) {
              const data1 = this.formatJson(filterVal, list1)
              excel.export_json_to_excel({
                header: tHeader,
                data: data1,
                filename: '备件领用：' + this.getdataListParm.parammaps.createTime,
                autoWidth: true,
                bookType: 'xlsx'
              })
            } else {
              this.$notify({
                title: '',
                message: '无备件领用完成信息，无法导出!',
                type: 'warning',
                duration: 2000
              })
            }
          })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // 导入
    beforeImportExcel(file) {
      /*   const isExcel =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' */
      const isLt2M = file.size / 1024 / 1024 < 20
      /*  if (!isExcel) {
        this.$message.error(
          '上传文件必须是Xlsx格式!建议先导出，再修改导出文件再导入！'
        )
      }*/
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 20MB!')
      }
      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.dialogFormVisibleErro = true
          this.dialogStatusErro = 'erro'
          this.listErro = res.data.result
          setTimeout(() => {
            this.listLoadingErro = false
          }, 100)
          // console.log(res.data.result)
          this.$notify({
            title: '失败',
            message: '导入失败:' + res.data.err_count + '条!',
            type: 'danger',
            duration: 2000
          })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    // 导入信息
    handleImportInfo() {
      this.dialogStatusImportInfo = 'ImportInfo'
      this.dialogFormVisibleImportInfo = true
      this.getListImportInfo()
    },
    // 选择要删除的数据
    handleSelectionChange(val) {
      // console.log(val)
      this.selection = val
    },
    // 删除
    form_delete(selection) {
      // console.log('selection', selection)
      this.parammapsId = []
      for (var i = 0; i < selection.length; i++) {
        console.log(selection[i])
        this.parammapsId.push(selection[i])
      }
      console.log(this.parammapsId)
      if (selection.length === 0) {
        this.$message({
          type: 'info',
          message: '请选中要删除的数据'
        })
      } else {
        MessageBox.confirm('确认删除？', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(this.parammapsId)
          this.requestParamDelete.common = { 'returnmap': '0' }
          // this.requestParamDelete.data = []
          // this.requestParamDelete.data[0] = { 'name': 'deleteIStockLaid', 'type': 'e', 'parammaps': {}}
          // this.requestParamDelete.data[0].parammaps = this.parammapsId
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'deleteIStockLaidList', 'resultmaps': { 'list': this.parammapsId }}
          this.postDataPramas.data[0].children = []
          this.postDataPramas.data[0].children[0] = { 'name': 'deleteIStockUse', 'type': 'e', 'parammaps': { }}
          this.postDataPramas.data[0].children[0].parammaps.id = '@deleteIStockLaidList.id'
          this.postDataPramas.data[0].children[0].parammaps.pastureId = '@deleteIStockLaidList.pastureId'
          this.postDataPramas.data[0].children[0].parammaps.stockNumber = '@deleteIStockLaidList.stockNumber'
          this.postDataPramas.data[0].children[0].parammaps.providerName = '@deleteIStockLaidList.providerName'
          this.postDataPramas.data[0].children[0].parammaps.location = '@deleteIStockLaidList.location'
          this.postDataPramas.data[0].children[0].parammaps.useNumber = '@deleteIStockLaidList.useNumber'
          ExecDataByConfig(this.postDataPramas).then(response => {
            if (response.msg === 'fail') {
              this.$notify({
                title: '删除失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.getListImportInfo()
              this.dialogFormVisible = false
              this.$notify({
                title: '',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
}

</script>

<style lang="scss" scoped>
  .el-table .cell {
    text-align: left !important;
  }
  h5{
    text-align:left;font-size: 14px;line-height:23px;margin:0;padding:0;
  }
  .pagination-container{
    display: block !important;
  }
  .el-date-editor--daterange{
    width: 250px;
    top:-3px;
  }
</style>
