<template>
  <div class="app-container">
    <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-input
        v-model="getdataListParmImportInfo.parammaps.storageNumber"
        placeholder="入库单号"
        style="width: 110px;"
        class="filter-item"
      />
      <el-input
        v-model="getdataListParmImportInfo.parammaps.stockNumber"
        placeholder="备件编码"
        style="width: 110px;"
        class="filter-item"
      />
      <el-autocomplete
        v-model="temp.providerName"
        value-key="name"
        class="inline-input"
        :fetch-suggestions="providerSearch"
        placeholder="供应商"
        style="width:110px;top:-3px;"
        @select="handleSelect"
      />
      <el-date-picker
        v-model="getdataListParmImportInfo.parammaps.storageTime"
        type="date"
        placeholder="入库日期"
        style="width:140px;top:-3px;"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="form_search"
      >搜索</el-button>
      <div>
        <el-button
          v-if="isRetreatMuban"
          v-waves
          class="filter-item"
          type="info"
          icon="el-icon-download"
          @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
            v-if="isReceiveImport"
            v-waves
            class="filter-item"
            type="warning"
            icon="el-icon-upload2"
          >导入</el-button>
        </el-upload>
        <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.storageNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.storageTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" min-width="130px" 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.trade }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计量单位" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总价" min-width="90px" 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.inputName }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>=0"
      :total="totalImportInfo"
      :page.sync="getdataListParmImportInfo.offset"
      :limit.sync="getdataListParmImportInfo.pagecount"
      @pagination="get_table_dataImportInfo"
    />
    <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 } 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 { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
export default {
  name: 'Storage',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      totalImportInfo: 0,
      listLoadingImportInfo: true,
      listImportInfo: [],
      isReceiveImport: [],
      isRetreatMuban: [],
      isStorageAdd: [],
      isStorageExport: [],
      isStorageSee: [],
      isStorageUpdate: [],
      isStorageDelate: [],
      tableKey: 0,
      listLoadingErro: true,
      listErro: [],
      list: [],
      list2: [],
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      postDataPramas: {

      },
      // 1-2:table&搜索传参
      getdataListParmImportInfo: {
        name: 'getImportStockLaidList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          deptName: '',
          useForm: '',
          stockNumber: '',
          stockName: '',
          receiveTime: '',
          providerName: '',
          storageName: '',
          storageTime: ''
        }
      },
      getdataListParmUpdate: {
        name: 'getStockLaidList',
        page: 0,
        offset: 0,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {
          bigId: ''
        }
      },
      getParmCreateLaidNumber: {
        name: 'createLaidNumber',
        page: 0,
        offset: 0,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {
          pastureNumber: Cookies.get('pasturenumber')
        }
      },
      orderAAA: {
        orderNumber: '',
        pastureId: '',
        pastureName: '',
        providerId: '',
        provoderName: '',
        orderA: '',
        stockId: '',
        stockNumber: '',
        stockName: '',
        specification: '',
        amount: '',
        unit: '',
        puropse: '',
        TAG: ''
      },
      // 2-3：下拉框请求后数据加入[]
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      getDictByName: [],
      // 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: ['资产状态'] }
      ],
      requestParamDelete: {

      },

      requestFilterParams: {

      },
      temp: {
      },
      storage: {
        inputDatetime: parseTime(new Date(), '{y}-{m}-{d}'),
        typeName: '',
        assTypeId: '',
        employeId: this.$store.state.user.employeid,
        departmentId: this.$store.state.user.departmentid,
        pastureId: this.$store.state.user.pastureid,
        laidNumber: ''
      },
      dialogFormVisibleErro: false,
      dialogStatusErro: '',
      textMap: {
        erro: '导入错误信息'
      },
      dialogPvVisible: false,
      // 校验规则
      rules: {},
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      selection: []
    }
  },

  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        // eslint-disable-next-line no-undef
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importStockLaid',
        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.get_table_dataImportInfo()
  },

  methods: {
    // 供应商模糊查询
    providerSearch(queryString, cb) {
      var returnList = this.findAllProvider
      var results = queryString ? returnList.filter(this.createFilter(queryString)) : returnList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      console.log(queryString)
      return returnValue => {
        return (
          returnValue.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleSelect(item) {
      this.temp.providerId = item.id
      this.temp.providerName = item.name
    },
    // 模糊查询  --查询申购单信息
    purchaseSearch(queryString, cb) {
      this.requestFilterParams.name = 'findPurchaseSolr'
      this.requestFilterParams.parammaps = {}
      this.requestFilterParams.parammaps['orderA'] = queryString
      this.requestFilterParams.parammaps['pastureId'] = this.$store.state.user.pastureid
      GetDataByName(this.requestFilterParams).then(response => {
        // console.log(response.data.list)
        cb(response.data.list)
      })
    },
    // 导出模板
    handleDownloadTemp() {
      this.requestParam.name = 'stockLaidDownTemp'
      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]
          }
        })
      )
    },
    // 导入
    beforeImportExcel(file) {
      /*   const isExcel =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' */
      const isLt2M = file.size / 1024 / 1024 < 10
      /*  if (!isExcel) {
        this.$message.error(
          '上传文件必须是Xlsx格式!建议先导出，再修改导出文件再导入！'
        )
      }*/
      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.dialogFormVisibleErro = true
          this.dialogStatusErro = 'erro'
          this.listErro = res.data.result
          setTimeout(() => {
            this.listLoadingErro = false
          }, 100)
          this.$notify({
            title: '失败',
            message: '导入失败:' + res.data.err_count + '条!',
            type: 'danger',
            duration: 2000
          })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    // 1-1: 导入信息table&搜索
    get_table_dataImportInfo() {
      this.listLoadingImportInfo = true
      if (this.getdataListParmImportInfo.parammaps.storageTime === null) {
        this.getdataListParmImportInfo.parammaps.storageTime = ''
      }
      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_searchImportInfo() {
      this.listLoadingImportInfo = true
      this.get_table_dataImportInfo()
    },
    // 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
      })
    },
    form_search() {
      this.listLoading = true
      this.getdataListParmImportInfo.offset = 1
      this.get_table_dataImportInfo()
      // this.get_table_data()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    form_reset() {
      this.list2 = []
      this.storage.inputDatetime = parseTime(new Date(), '{y}-{m}-{d}')
      this.storage.typeName = ''
      this.storage.assTypeId = ''
      this.storage.employeId = this.$store.state.user.employeid
      this.storage.departmentId = this.$store.state.user.departmentid
      this.storage.pastureId = this.$store.state.user.pastureid
    },
    // 选择要删除的数据
    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(() => {
          this.requestParamDelete.common = { 'returnmap': '0' }
          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': 'deleteIStockLaid', '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.amount = '@deleteIStockLaidList.amount'
          ExecDataByConfig(this.postDataPramas).then(response => {
            if (response.msg === 'fail') {
              this.$notify({
                title: '删除失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.get_table_dataImportInfo()
              this.dialogFormVisible = false
              this.$notify({
                title: '',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
}
</script>
