<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.pastureName" placeholder="牧场" class="filter-item">
        <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-input v-model="getdataListParm.parammaps.oddCode" placeholder="盘点编号" style="width: 150px;" class="filter-item" />

      <el-select v-model="getdataListParm.parammaps.statue" placeholder="盘点状态" class="filter-item" clearable>
        <el-option v-for="item in findAllStatus" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>

      <el-date-picker
        ref="inputDatetime"
        v-model="getdataListParm.parammaps.inputDatetime"
        class="inputDatetime"
        type="datetimerange"
        style="width: 260px;top:-3px;"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <div>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      </div>
    </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"
    >
      <!-- table表格 -->
      <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.oddCode }}</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="盘盈金额" sortable prop="moreSum" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.moreSum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘亏金额" sortable prop="lessSum" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lessSum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盈亏净额" sortable prop="sums" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sums }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点原因" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.note }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点状态" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.statue == 0 ? '盘点中' : '已完成' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点日期" sortable prop="checkDate" min-width="110px" align="center" />

      <el-table-column label="操作" align="center" width="240px" 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 v-if="row.statue == 0" type="success" size="mini" @click="form_edit(row)">盘点</el-button>
          <el-button v-if="row.statue == 0" 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="getList"
    />
    <!-- 弹出层新增or查看 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="temp" :rules="rules" :model="temp" label-position="right" label-width="140px" style="width: 800px; margin-left:50px;">

        <el-row>

          <el-col :span="8">
            <el-form-item label="盘点单号：">
              <!-- <span>{{ temp.pastureName }}</span> -->
              <el-input v-model="temp.oddCode" disabled style="width:170px;" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="牧场：" prop="pastureName">
              <el-select v-model="temp.pastureId" placeholder="牧场" class="filter-item" style="width:170px;" :disabled="dialogStatus==='see'">
                <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="盘点人：" prop="employeId">
              <el-select
                v-model="temp.employeId"
                placeholder="盘点人"
                class="filter-item"
                style="width:170px;"
                :disabled="dialogStatus==='see'"
              >
                <el-option
                  v-for="item in findAllEmploye"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="盘点日期：" prop="checkDate">
              <el-date-picker
                v-model="temp.checkDate"
                type="date"
                placeholder="日期"
                :disabled="dialogStatus==='see'"
                style="width:170px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点原因：">
              <!-- <span>{{ temp.pastureName }}</span> -->
              <el-input v-model="temp.note" :disabled="dialogStatus==='see'" style="width:170px;" />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div v-if="temp.statue !== 0 && dialogStatus=='see' " style="position:relative;">
        <el-button class="filter-item" type="success" icon="el-icon-upload2" style="position:absolute ;right:10px;top:-50px;" @click="handleDownloadSee">导出</el-button>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="tempSolr"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-bottom:50px"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
      >
        <!-- table表格 -->

        <el-table-column v-if="isAdd" label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (pageNum21-1) * pageSize21 + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isLook" label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (pageNum22-1) * pageSize22 + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备件编号" width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.partCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备件名称" width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.partName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="备件规格" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.specification }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.brand }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.providerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库位" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.location }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当前库存" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.repertory }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="dialogStatus==='see' && temp.statue ===1" label="盘点库存" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.checkAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="dialogStatus==='see' && temp.statue ===1" label="差值" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ (parseFloat(scope.row.checkAmount) -parseFloat(scope.row.repertory)).toFixed(2) }}</span>
          </template>
        </el-table-column>

      </el-table>
      <pagination

        v-show="tempSolrtotal>0 && isAdd"
        :total="tempSolrtotal"
        :page.sync="gettempSolr.offset"
        :limit.sync="gettempSolr.pagecount"
        @pagination="gettempSolrList"
      />
      <pagination

        v-show="tempSolrtotal2>0 && isLook"
        :total="tempSolrtotal2"
        :page.sync="gettempSolr2.offset"
        :limit.sync="gettempSolr2.pagecount"
        @pagination="gettempSolrList2"
      />
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus==='create'" type="primary" @click="add_dialog_save()">确认</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="盘点" :visible.sync="dialogFormVisible3" :close-on-click-modal="false" width="90%">
      <el-form ref="temp3" :rules="rules" :model="temp3" label-position="right" label-width="180px" style=" width:90%;margin:0 auto;">

        <el-row>

          <el-input v-model="gettempSolr3.parammaps.partCode" placeholder="备件编号" style="width: 170px;" class="filter-item" />

          <el-input v-model="gettempSolr3.parammaps.partName" placeholder="备件名称" style="width: 170px;" class="filter-item" />

          <el-autocomplete v-model="gettempSolr3.parammaps.providerName" value-key="name" class="inline-input" :fetch-suggestions="providerSearch" placeholder="供应商" style="width:30%;" @select="handleSelect" />

          <tree-select
            class="typeSelect"
            :height="150"
            :width="200"
            size="small"
            clearable
            :data="parentDept"
            :disabled="disabled"
            :placeholder="placeholder"
            style="display:inline-block;top:-3px;"
            :default-props="defaultProps"
            :node-key="nodeKey"
            :checked-keys="defaultCheckedKeys"
            @popoverHide="popoverHide"
          />
          <el-select v-model="gettempSolr3.parammaps.inventoryStatue" placeholder="库存筛选" class="filter-item" clearable>
            <el-option v-for="item in inventoryScreening" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_searchDelivery">搜索</el-button>

          <!-- <el-col :span="8">
            <el-form-item label="盘点人：" prop="employeId">
              <el-select
                v-model="temp3.employeId"
                placeholder="盘点人"
                class="filter-item"
                style="width:170px;"
                :disabled="dialogStatus==='see'"
              >
                <el-option
                  v-for="item in findAllEmploye"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->

        </el-row>

      </el-form>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="tempSolr3"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-bottom:50px"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
      >
        <!-- table表格 -->

        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (pageNum3-1) * pageSize3 + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备件编号" width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.partCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备件名称" width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.partName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="备件规格" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.specification }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.brand }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.providerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库位" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.location }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当前库存" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.repertory }}</span>
          </template>
        </el-table-column>
        <el-table-column label="盘点库存" min-width="130px" align="center" valign="middle">
          <template slot-scope="scope">
            <el-form ref="checkAmount" :model="scope.row" :rules="rules">
              <el-form-item prop="checkAmount">
                <el-input v-model="scope.row.checkAmount" style="margin-top:15px" />
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="差值" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ (parseFloat(scope.row.checkAmount) -parseFloat(scope.row.repertory)).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100px"
        >
          <template slot-scope="{row}">

            <el-button type="primary" size="mini" @click="partSave(row)">保存</el-button>
          </template>
        </el-table-column>
      </el-table>

      </el-table>
      <pagination
        v-show="tempSolrtotal3>0"
        :total="tempSolrtotal3"
        :page.sync="gettempSolr3.offset"
        :limit.sync="gettempSolr3.pagecount"
        @pagination="gettempSolrList3"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="edit_dialog_save()">完成盘点</el-button>
        <el-button @click="dialogFormVisible3 = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import { GetDataByName, GetDataByNames, PostDataByName, checkButtons, transData, 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 { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import TreeSelect from '@/components/TreeSelect'
import Cookies from 'js-cookie'
import { json2excel } from '@/utils/index.js'
export default {
  name: 'Inventory',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      // 新增
      isCustomAdd: [],
      // 导入
      isCustomImport: [],
      // 编辑
      isCustomUpdate: [],
      // 删除
      isCustomDelate: [],

      listType: [],
      placeholder: '请选择备件类别',
      isokDisable: false,
      disabled: false,
      getDeptListParm: { name: 'getpart_classList' },
      parentDept: [],
      defaultProps: {
        children: 'children',
        label: 'partClassNameCode'
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      deptform: {
        id: '',
        tempPtypeCode: '',
        temptypeCode: '',
        typeName: '',
        typeCode: '',
        pid: '',
        sort: '',
        enable: ''
      },
      createTemp: {
        partClass: '',
        partCode: '',
        tempPtypeCode: '',
        temptypeCode: '',
        partName: '',
        specification: '',
        unit: '',
        purpose: '',
        createPerson: this.$store.state.user.employeid,
        createTime: parseTime(new Date(), '{y}-{m}-{d}'),
        note: ''
      },

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'insertAsset',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },

      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getBigcheckpartList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          oddCode: '',
          statue: '',
          startTime: '',
          stopTime: '',
          inputDatetime: '',
          pastureName: Cookies.get('pasturename')
        }
      },
      getdataProvider: {
        name: 'getStockList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        params: []
      },

      isLook: false,
      isAdd: false,

      pageNum: 1,
      pageSize: 10,
      pageNum21: 1,
      pageSize21: 10,
      pageNum22: 1,
      pageSize22: 10,
      pageNum3: 1,
      pageSize3: 10,

      tempSolrtotal: 0,
      gettempSolr: {
        name: 'getPartRepertoryList',
        page: 1,
        offset: 1,
        pagecount: 10,
        total: 0,
        parammaps: {
          pastureId: this.$store.state.user.pastureid
        }
      },
      tempSolrtotal2: 0,
      gettempSolr2: {
        name: 'getcheckpartbyBig',
        page: 1,
        offset: 1,
        pagecount: 10,
        parammaps: {
          id: '',
          partCode: '',
          partName: '',
          providerName: '',
          eqClass: ''
        }
      },
      tempSolrtotal3: 0,
      gettempSolr3: {
        name: 'getcheckpartbyBig',
        page: 1,
        offset: 1,
        pagecount: 10,
        parammaps: {
          id: '',
          partCode: '',
          partName: '',
          providerName: '',
          eqClass: '',
          inventoryStatue: ''
        }
      },
      inventoryScreening: [{ id: 1, name: '全部' }, { id: 2, name: '库存为0' }, { id: 3, name: '库存不为0' }],
      tempSolr3: [],

      // 2-3：下拉框请求后数据加入[]
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllStatus: [{ id: 0, name: '盘点中' }, { id: 1, name: '已完成' }],
      findAllDepart: [],
      findAllEmploye: [],

      getDictByName: [],
      findAllCategory: [],
      // 2-1.请求下拉框接口
      requestParams: [

        { 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: 'findAllProvider', offset: 0, pagecount: 0, params: [] },
        {
          name: 'getDictByName',
          offset: 0,
          pagecount: 0,
          params: ['资产状态']
        },
        { name: 'findAllCategory', offset: 0, pagecount: 0, params: [] }
      ],

      temp: {
        checkDate: parseTime(new Date(), '{y}-{m}-{d}'),
        employeId: this.$store.state.user.employeid,
        pastureId: this.$store.state.user.pastureid
      },
      tempSolr: [],
      dialogFormVisible: false,
      dialogFormVisible3: false,
      temp3: {
        employeId: this.$store.state.user.employeid,
        pastureId: this.$store.state.user.pastureid
      },
      dialogStatus: '',
      textMap: {
        update: '盘点',
        see: '查看',
        create: '新增'
      },
      dialogPvVisible: false,
      // 校验规则
      rules: {
        assetNumber: [
          { required: true, message: '必填', trigger: 'blur' }
          // 引入自定义校验并使用
          // { validator: validateEMail, trigger: 'blur' }
        ],
        equipmentName: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      downLoadParm: {},
      isPercentage: false,
      percentage: 1
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'insertWatersMeasure',
        importParams: '编号,牧场,表名称,表编号,本次值,上次值,单价,录入人,备注,jwt_username',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  created() {
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.get_auto_buttons()
    })
    this.get_select_list()
    this.getList()
    this.getTypeList()
  },

  methods: {
    get_auto_buttons() {
      // 新增
      var CustomAdd = 'customs:custom:add'
      var isCustomAdd = checkButtons(this.$store.state.user.buttons, CustomAdd)
      this.isCustomAdd = isCustomAdd
      // 导入
      var CustomImport = 'customs:custom:import'
      var isCustomImport = checkButtons(this.$store.state.user.buttons, CustomImport)
      this.isCustomImport = isCustomImport
      // 编辑
      var CustomUpdate = 'customs:custom:update'
      var isCustomUpdate = checkButtons(this.$store.state.user.buttons, CustomUpdate)
      this.isCustomUpdate = isCustomUpdate
      // 删除
      var CustomDelate = 'customs:custom:delate'
      var isCustomDelate = checkButtons(this.$store.state.user.buttons, CustomDelate)
      this.isCustomDelate = isCustomDelate
    },
    popoverHide(checkedIds, checkedData) {
      console.log(checkedIds, checkedData)
      if (checkedIds !== null) {
        if (checkedData.childrens == 0) {
          this.deptform.pid = checkedIds
          console.log(checkedData)
          if (checkedIds !== null) {
          // this.deptform.partCode = checkedData.partClassCode
            this.createTemp.partCode = checkedData.partClassCode
            this.createTemp.partClass = checkedData.partClassCode
            this.createTemp.partClassNameCode = checkedData.partClassNameCode
          } else {
            this.createTemp.pid = -1
          }
          this.getMaxCode()
        } else {
          this.defaultCheckedKeys = []
          this.createTemp.tempPtypeCode = ''
          this.createTemp.temptypeCode = ''
          this.$message({
            type: 'warning',
            message: '请选择详细备件类别'
          })
        }
      } else {
        this.defaultCheckedKeys = []
        this.createTemp.partCode = ''
        this.createTemp.partClass = ''
        this.createTemp.partClassNameCode = ''
      }
    },
    getTypeList() {
      // this.listLoading = true
      this.getDeptListParm.parammaps = this.deptform
      GetDataByName(this.getDeptListParm).then(response => {
        this.listType = response.data
        // console.log(this.listType)

        if (response.data.list !== null) {
          this.listType = transData(response.data.list, 'id', 'pid', 'children')
          console.log(this.listType)
        }
        this.parentDept = this.listType
      })
    },
    getMaxCode() {
      this.requestParam.name = 'getPartCode'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.partCode = this.createTemp.partCode
      GetDataByName(this.requestParam).then(response => {
        console.log('备件类别选中data', response.data.list)
        if (response.data.list.length > 0) {
          if (response.data.list[0].preCode === '') {
            this.createTemp.tempPtypeCode = this.deptform.typeCode + '.'
            // console.log(this.createTemp.tempPtypeCode)
          } else {
            this.createTemp.tempPtypeCode = response.data.list[0].preCode
            // console.log(this.createTemp.tempPtypeCode)
          }
          this.createTemp.temptypeCode = response.data.list[0].maxcode
          // console.log(this.createTemp.temptypeCode)
          this.$nextTick(() => {
            this.createTemp.partCode = this.createTemp.tempPtypeCode + this.createTemp.temptypeCode
            console.log(this.createTemp.partCode)
            this.$forceUpdate()
          })

          if (this.requestParam.parammaps.pid === -1) {
            // this.createTemp.typeCode = this.deptform.tempPtypeCode + this.deptform.temptypeCode
            this.createTemp.partCode = this.createTemp.tempPtypeCode + this.createTemp.temptypeCode
          }
        }
      })
    },

    // 供应商模糊查询
    providerSearch(queryString, cb) {
      var returnList = this.findAllProvider
      var results = queryString ? returnList.filter(this.createFilter(queryString)) : returnList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return returnValue => {
        return (
          returnValue.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        )
      }
    },
    handleSelect(item) {
      console.log(item)
      this.temp3.providerId = item.id
      this.temp3.providerName = item.name
    },
    // 1-1: table&搜索
    getList() {
      if (this.$refs['inputDatetime'] !== undefined && this.$refs['inputDatetime'].value !== null) {
        this.getdataListParm.parammaps.startTime = this.$refs['inputDatetime'].value[0]
        this.getdataListParm.parammaps.stopTime = this.$refs['inputDatetime'].value[1]
      } else {
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      }
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    // 2-2：下拉框
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        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.findAllProvider = response.data.findAllProvider.list
        this.getDictByName = response.data.getDictByName.list
        this.findAllCategory = response.data.findAllCategory.list
        // for (var i = 0; i < this.findAllProvider.length; i++) {
        //   this.findAllProvider[i].value = this.findAllProvider[i].name
        // }
      })
    },
    form_search() {
      this.listLoading = true
      if (this.getdataListParm.parammaps.inputDatetime === null) {
        this.getdataListParm.parammaps.inputDatetime = ''
      }
      this.getdataListParm.offset = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },

    add_dialog_save() {
      var send_data1 = {
        'common': {
          'returnmap': '0'
        },
        'data': [
          {
            'name': 'insertBigcheckpart',
            'type': 'e',
            'parammaps': {
              'pastureId': this.$store.state.user.pastureid,
              'oddCode': this.temp.oddCode,
              'checkId': this.temp.employeId,
              'checkDate': this.temp.checkDate,
              'note': this.temp.note
            }
          },
          {
            'name': 'insertCheckparts',
            'type': 'e',
            'parammaps': {
              'id': '@insertBigcheckpart.LastInsertId',
              'pastureId': this.$store.state.user.pastureid
            }
          }
        ]
      }

      ExecDataByConfig(send_data1).then(response => {
        if (response.msg === 'fail') {
          this.$notify({
            title: '保存失败',
            message: response.data,
            type: 'warning',
            duration: 2000
          })
        } else {
          this.getList()
          this.dialogFormVisible = false
          this.createTemp.providerName = ''
          this.$notify({
            title: '',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    form_reset() {
      this.pageNum21 = 1
      this.pageSize21 = 10
      this.pageNum22 = 1
      this.pageSize22 = 10
      this.pageNum3 = 1
      this.pageSize3 = 10

      this.temp = {
        // 格式化日期
        checkDate: parseTime(new Date(), '{y}-{m}-{d}'),
        employeId: this.$store.state.user.employeid,

        pastureId: this.$store.state.user.pastureid
      }
    },

    form_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      GetDataByName({ name: 'autoCreatCode', parammaps: { pastureId: this.$store.state.user.pastureid, codeType: 'PD' }}).then(response => {
        console.log(response.data.list[0].orderCode)
        this.temp.oddCode = response.data.list[0].orderCode
        this.$forceUpdate()
        this.gettempSolrList()
      })
    },

    gettempSolrList() {
      GetDataByName(this.gettempSolr).then(response => {
        this.tempSolr = response.data.list
        if (response.data.total) {
          this.tempSolrtotal = response.data.total
          this.gettempSolr.pageNum = response.data.pageNum
          this.gettempSolr.pageSize = response.data.pageSize
          this.pageNum21 = response.data.pageNum
          this.pageSize21 = response.data.pageSize
        }
        this.isLook = false
        this.isAdd = true
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },

    form_see(row) {
      this.form_reset()
      console.log('row', row)
      this.temp = Object.assign({}, row) // copy obj
      this.temp.employeId = row.checkId
      this.temp.employeName = row.checkName
      this.temp.pastureId = row.pastureId

      this.dialogStatus = 'see'
      this.dialogFormVisible = true
      this.gettempSolr2.parammaps['id'] = row.id

      GetDataByName(this.gettempSolr2).then(response => {
        this.tempSolr = response.data.list
        if (response.data.total) {
          this.tempSolrtotal2 = response.data.total
        }
        this.isLook = true
        this.isAdd = false
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },

    gettempSolrList2() {
      GetDataByName(this.gettempSolr2).then(response => {
        this.tempSolr = response.data.list
        if (response.data.total) {
          this.tempSolrtotal2 = response.data.total
          this.gettempSolr2.pageNum = response.data.pageNum
          this.gettempSolr2.pageSize = response.data.pageSize
          this.pageNum22 = response.data.pageNum
          this.pageSize22 = response.data.pageSize
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },

    form_searchDelivery() {
      this.gettempSolrList3()
      this.gettempSolr3.parammaps.eqClass = this.createTemp.partClass
    },
    gettempSolrList3() {
      GetDataByName(this.gettempSolr3).then(response => {
        this.tempSolr3 = response.data.list
        if (response.data.total) {
          this.tempSolrtotal3 = response.data.total
          this.gettempSolr3.pageNum = response.data.pageNum
          this.gettempSolr3.pageSize = response.data.pageSize
          this.pageNum3 = response.data.pageNum
          this.pageSize3 = response.data.pageSize
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    // 编辑

    form_edit(row) {
      this.temp3 = Object.assign({}, row) // copy obj
      this.dialogFormVisible3 = true

      this.gettempSolr3.parammaps['id'] = row.id

      GetDataByName(this.gettempSolr3).then(response => {
        this.tempSolr3 = response.data.list
        if (response.data.total) {
          this.tempSolrtotal3 = response.data.total
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    edit_dialog_save() {
      this.$refs['temp3'].validate(valid => {
        if (valid) {
          var send_data3 = {
            name: 'completeCheckpart',
            parammaps: {
              id: this.temp3.id
            }
          }

          PostDataByName(send_data3).then(response => {
            console.log(response)
            if (response.msg === 'fail') {
              this.$notify({
                title: '失败',
                message: '保存失败-' + response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.getList()
              this.dialogFormVisible3 = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    form_delete(row) {
      MessageBox.confirm('确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var send_data4 = {
            'common': {
              'returnmap': '0'
            },
            'data': [
              {
                'name': 'deleteBigCheckpart',
                'type': 'e',
                'parammaps': {
                  'id': row.id
                }
              },
              {
                'name': 'deleteCheckpart',
                'type': 'e',
                'parammaps': {
                  'id': row.id
                }
              }
            ]
          }

          ExecDataByConfig(send_data4).then(response => {
            if (response.msg === 'fail') {
              this.$notify({
                title: '删除失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.getList()
              this.dialogFormVisible = false

              this.$notify({
                title: '',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDownload() {
      this.requestParam.name = 'stockDown'
      this.requestParam.parammaps.pastureName = this.getdataListParm.parammaps.pastureName
      this.requestParam.parammaps.stockName = this.getdataListParm.parammaps.stockName
      this.requestParam.parammaps.stockNumber = this.getdataListParm.parammaps.stockNumber

      GetDataByName(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
              '牧场', '物料编号', '名称', '规格', '用途', '备件种类', '供应商', '单位', '单价', '库存', '最低库存', '最高库存'
            ]
            const filterVal = [
              '牧场', '物料编号', '名称', '规格', '用途', '备件种类', '供应商', '单位', '单价', '库存', '最低库存', '最高库存'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '备件信息',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    handleDownloadSee() {
      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.downLoadParm.name = 'getcheckpartbyBig'
      this.downLoadParm.parammaps = this.gettempSolr2.parammaps
      GetAccount(this.downLoadParm).then(response => {
        if (response.data.list !== null) {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
          for (let i = 0; i < response.data.list.length; i++) {
            this.$set(response.data.list[i], 'pastureName', this.temp.pastureName)
            this.$set(response.data.list[i], 'oddCode', this.temp.oddCode)
            this.$set(response.data.list[i], 'employeName', this.temp.employeName)
            this.$set(response.data.list[i], 'checkDate', this.temp.checkDate)
            this.$set(response.data.list[i], 'note', this.temp.note)
          }
        }
        const ExcelDatas = [
          {
            tHeader: ['牧场', '盘点单号', '备件编号', '备件名称', '备件规格', '品牌', '供应商', '库位', '单价', '当前库存', '盘点库存', '差值', '盘点人', '盘点日期', '盘点原因'],
            filterVal: ['pastureName', 'oddCode', 'partCode', 'partName', 'specification', 'brand', 'providerName', 'location', 'price', 'repertory', 'checkAmount', 'checkAmount', 'employeName', 'checkDate', 'note'],
            tableDatas: response.data.list,
            sheetName: '备件盘点'
          }
        ]
        json2excel(ExcelDatas, '备件盘点', true, 'xlsx')
      })
    },
    partSave(row) {
      console.log(row)

      var send_data1 = {
        name: 'updateCheckpart',
        parammaps: {
          id: row.id,
          checkAmount: row.checkAmount
        }
      }
      if (row.checkAmount !== null || row.checkAmount !== '') {
        const rulesCheckAmount = /^\d+(\.\d{1,2})?$/
        if (!rulesCheckAmount.test(parseFloat(row.checkAmount))) {
          this.$message({ type: 'warning', message: '盘点库存请输入非负数并保留2位小数！' })
          return false
        }
        PostDataByName(send_data1).then(response => {
          console.log(response)
          if (response.msg === 'fail') {
            this.$notify({
              title: '失败',
              message: '保存失败-' + response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      } else {
        this.$message({ type: 'warning', message: '请填写盘点库存' })
      }
    },
    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 < 2
      /*  if (!isExcel) {
        this.$message.error(
          '上传文件必须是Xlsx格式!建议先导出，再修改导出文件再导入！'
        )
      }*/
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
    //  if (res.msg === 'ok') {
      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
          })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    }
  }
}
</script>
