<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" class="filter-item" style="width: 120px;">
        <el-option
          v-for="item in findAllPasture"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
      <el-input v-model="getdataListParm.parammaps.partCode" placeholder="备件编号" style="width: 160px;" class="filter-item" />
      <el-input v-model="getdataListParm.parammaps.partName" placeholder="备件名称" style="width: 160px;" class="filter-item" />
      <tree-select
        class="typeSelect"
        :height="150"
        :width="250"
        size="small"
        clearable
        :data="parentDept"
        :disabled="disabled"
        :placeholder="placeholder"
        style="display:inline-block;"
        :default-props="defaultProps"
        :node-key="nodeKey"
        :checked-keys="defaultCheckedKeys"
        @popoverHide="popoverHide"
      />
      <el-autocomplete v-model="getdataListParm.parammaps.providerName" clearable value-key="providerName" class="inline-input" :fetch-suggestions="providerSearch" placeholder="供应商" style="width:150px;top:-3px;" @select="handleSelectProvider" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
    </div>
    <div class="app-btn" style="height:50px">
      <el-button class="filter-item" type="primary" @click="form_add">库存预警设置</el-button>
      <!-- <el-button 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-waves class="filter-item" type="warning" icon="el-icon-upload2">导入</el-button>
      </el-upload>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleDownload">导出</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"
      @sort-change="tableSort"
    >
      <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="140px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.partCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件名称" min-width="140px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.partName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件规格" min-width="140px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.specification }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件类别" min-width="140px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.providerName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高库存" sortable prop="maxRepertory" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.maxRepertory }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最低库存" sortable prop="minRepertory" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.minRepertory }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="getdataListParm.offset"
      :limit.sync="getdataListParm.pagecount"
      @pagination="getList"
    />
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <div class="app-add">
        <b>当前设置条数：{{ number }}条</b>
        <el-form
          ref="createTemp"
          :rules="rules"
          :model="createTemp"
          label-position="right"
          label-width="100px"
          style="width: 90%;margin:10px auto 0"
        >
          <el-row>
            <el-col :span="20">
              <el-form-item label="最高库存：" prop="maxRepertory">
                <el-input ref="maxRepertory" v-model="createTemp.maxRepertory" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="最低库存：" prop="minRepertory">
                <el-input ref="minRepertory" v-model="createTemp.minRepertory" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="isokDisable" @click="dialogStatus==='create'?add_dialog_save():add_dialog_save()">保存并关闭</el-button>
          <el-button @click="dialogFormVisible = false;">取消并关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { GetDataByName, GetDataByNames, transData, ExecDataByConfig } from '@/api/common'
import TreeSelect from '@/components/TreeSelect'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
import { parseTime, sortChange } from '@/utils/index.js'
export default {
  name: 'SafetyStock',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      rules: {
        maxRepertory: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('不能为空'))
          }
          setTimeout(() => {
            const re = /^[0-9]*[1-9][0-9]*$/ // /^[0-9]*[1-9][0-9]*$/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入正整数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }],
        minRepertory: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('不能为空'))
          }
          setTimeout(() => {
            const re = /^[0-9]*[1-9][0-9]*$/ // /^[0-9]*[1-9][0-9]*$/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入正整数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }]
      },
      isokDisable: false,
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      findAllPasture: [],
      requestParams: [{ name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }}],
      parentDept: [],
      defaultProps: {
        children: 'children',
        label: 'partClassNameCode'
      },
      disabled: false,
      placeholder: '请选择备件类别',
      nodeKey: 'id',
      defaultCheckedKeys: [],
      listType: [],
      tableKey: 0,
      getDeptListParm: { name: 'getpart_classList' },
      list: [],
      total: 0,
      listLoading: true,
      getdataListParm: {
        name: 'getPRlist',
        page: 1,
        offset: 1,
        pagecount: 50,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          partCode: '',
          partName: '',
          classCode: ''
        }
      },
      textMap: {
        create: '库存预警设置'
      },
      dialogStatus: '',
      dialogFormVisible: false,
      selectionList: [],
      number: 0,
      createTemp: {
        maxRepertory: '',
        minRepertory: ''
      },
      postDataPramas: {},
      requestProvider: {
        name: 'getProviderList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      }
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        // eslint-disable-next-line no-undef
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'importStockUse',
        importParams: '牧场,领用单编号,领用日期,物料编码,品名,规格型号,品牌,计量单位,实发数量,单价,总价,库位,供应商,名称,牧场设备编号,具体用处,领用类型,领用部门,领用人,SignColumn',
        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.getList()
    this.getTypeList()
  },

  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    providerSearch(queryString, cb) {
      console.log('供应商模糊查询输入值', queryString)
      this.requestProvider.parammaps['providerName'] = queryString
      GetDataByName(this.requestProvider).then(response => {
        console.log('供应商模糊查询搜索data', response.data.list)
        if (response.data.list !== null) {
          cb(response.data.list)
        } else {
          cb([])
        }
      })
    },
    handleSelectProvider(item) {
      console.log('供应商模糊查询选中值', item)
    },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
      })
    },
    getTypeList() {
      GetDataByName(this.getDeptListParm).then(response => {
        this.listType = response.data
        if (response.data.list !== null) {
          this.listType = transData(response.data.list, 'id', 'pid', 'children')
          console.log(this.listType)
        }
        this.parentDept = this.listType
      })
    },
    popoverHide(checkedIds, checkedData) {
      if (checkedIds !== null) {
        console.log(checkedData)
        console.log(checkedData.childrens)
        if (checkedData.childrens == 0) {
          if (checkedIds !== null) {
            this.getdataListParm.parammaps.classCode = checkedData.partClassCode
          }
        } else {
          this.defaultCheckedKeys = []
          this.getdataListParm.parammaps.classCode = ''
          this.$message({
            type: 'warning',
            message: '请选择详细备件类别'
          })
        }
      } else {
        this.defaultCheckedKeys = []
        this.getdataListParm.parammaps.classCode = ''
      }
    },
    getList() {
      GetDataByName(this.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.getList()
    },
    handleSelectionChange(val) {
      console.log('选中值', val)
      this.selectionList = val
    },
    resetCreateTemp() {
      this.createTemp.maxRepertory = ''
      this.createTemp.minRepertory = ''
    },
    form_add() {
      if (this.selectionList.length > 0) {
        this.resetCreateTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.number = this.selectionList.length
      } else {
        this.$message({
          type: 'warning',
          message: '请选择备件'
        })
      }
    },
    add_dialog_save() {
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.common = { 'returnmap': '0' }
          this.postDataPramas.data = []
          this.postDataPramas.data[0] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.selectionList }}
          this.postDataPramas.data[0].children = []
          this.postDataPramas.data[0].children[0] = { 'name': 'updatePRMaxMin', 'type': 'e', 'parammaps': {
            id: '@insertSpotList.id',
            maxRepertory: this.createTemp.maxRepertory,
            minRepertory: this.createTemp.minRepertory
          }}
          ExecDataByConfig(this.postDataPramas).then(response => {
            console.log('新增保存发送参数', this.postDataPramas)
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDownloadTemp() {
      console.log('点击了模板')
    },
    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 = [
               '牧场', '领用单编号', '领用日期', '物料编码', '品名', '规格型号', '品牌', '计量单位', '实发数量', '单价', '总价', '库位', '供应商', '名称', '牧场设备编号', '具体用处', '领用类型', '领用部门', '领用人', 'SignColumn', '报错信息'
             ]
             const filterVal = [
               '牧场', '领用单编号', '领用日期', '物料编码', '品名', '规格型号', '品牌', '计量单位', '实发数量', '单价', '总价', '库位', '供应商', '名称', '牧场设备编号', '具体用处', '领用类型', '领用部门', '领用人', 'SignColumn', 'error_msg'
             ]
             const data1 = this.formatJson(filterVal, list1)
             excel.export_json_to_excel({
               header: tHeader,
               data: data1,
               filename: this.requestParam.parammaps.formType,
               autoWidth: true,
               bookType: 'xlsx'
             })
           })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    formatJsonTemp(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    handleDownload() {
      console.log('点击了导出')
    }
  }
}
</script>
