<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-input v-model="getdataListParm.parammaps.providerName" placeholder="供应商名" style="width: 140px;" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <el-button v-if="isProductAdd" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      <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"
      @sort-change="tableSort"
    >
      <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.providerName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="供应商简称" align="center" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.providerIntro }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商编码" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.providerNumber }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="联系人" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.linkman }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.telphone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资产数" sortable prop="eqs" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.eqs }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件数" sortable prop="bcs" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.bcs }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同数" sortable prop="pps" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pps }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备类型数" sortable prop="eps" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.eps }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isProductUpdate" label="启用" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEnableChange(scope.$index, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column v-if="isProductUpdate" label="是否线上采购" min-width="80px" header-align="center" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.flexPrice" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleFlexPriceChange(scope.$index, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="success" size="mini" @click="handleeqMenu(row)">设备</el-button>
          <el-button type="success" size="mini" @click="handlePartMenu(row)">备件</el-button>
          <el-button type="success" size="mini" @click="handlewarehouseMenu(row)">库位</el-button>
          <el-button v-if="isProductUpdate" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button v-if="isProductDelete && row.bcs === 0 && row.eqs === 0 && row.pps === 0 && row.eps === 0" size="mini" type="danger" @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" width="80%">
      <div class="content-add">
        <el-form
          ref="temp"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="100px"
          style="width: 90%; margin-left:50px;"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商简称" prop="providerName">
                <el-input ref="providerName" v-model="temp.providerName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商名" prop="providerIntro">
                <el-input ref="providerIntro" v-model="temp.providerIntro" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商编号" prop="providerNumber">
                <el-input ref="providerNumber" v-model="temp.providerNumber" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="营业执照" prop="businessLicense">
                <el-input ref="businessLicense" v-model="temp.businessLicense" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="组织机构代码" prop="organizationCode">
                <el-input ref="organizationCode" v-model="temp.organizationCode" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="税务登记证" prop="IRSregister">
                <el-input ref="IRSregister" v-model="temp.IRSregister" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户许可证" prop="openLicence">
                <el-input ref="openLicence" v-model="temp.openLicence" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="linkman">
                <el-input ref="linkman" v-model="temp.linkman" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="telphone">
                <el-input ref="telphone" v-model="temp.telphone" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input ref="email" v-model="temp.email" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()">确认</el-button>
          <el-button @click="dialogFormVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :title="textMap['stock']" :visible.sync="dialogstockVisible" :close-on-click-modal="false">
      <el-form :rules="rules" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-form-item label="可提供的备件类别" prop="stockname">
          <tree-select
            :disabled="disabled"
            :height="280"
            :width="400"
            size="small"
            multiple
            :data="sparePartparentstock"
            :default-props="sparePartdefaultProps"
            collapse-tags
            :node-key="nodeKey"
            :checked-keys="sparePartDefaultCheckedKeys"
            @popoverHide="sparePartpopoverHide"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatestock()"> 确认 </el-button>
        <el-button @click="dialogstockVisible = false"> 关闭 </el-button>
      </div>
    </el-dialog>
    <!-- 库位 -->
    <el-dialog :title="textMap['location']" :visible.sync="dialogwarehouseVisible" :close-on-click-modal="false">
      <div class="content-warehoseCode">
        <el-form :rules="rules" label-position="right" label-width="100px" style="width: 800px; margin-left:50px;">
          <!-- <el-form-item label="可提供的库位" prop="stockname">
          <tree-select
            :disabled="disabled"
            :height="280"
            :width="400"
            size="small"
            multiple
            :data="parentstock"
            :default-props="defaultProps"
            collapse-tags
            :node-key="nodeKey"
            :checked-keys="defaultCheckedKeys"
            @popoverHide="popoverHide"
          />
        </el-form-item> -->
          <el-row>
            <el-col :span="16">
              <el-form-item label="库位：" prop="warehoseCode">
                <el-autocomplete v-model="warehoseTemp.warehoseCode" value-key="name" class="inline-input" :fetch-suggestions="querySearchWarehoseCode" placeholder="请输入库位" style="width:100%" @select="handleSelectWarehoseCode">
                  <template slot-scope="{ item }">
                    <b>库位编号：</b><span class="name">{{ item.warehoseCode }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="7" style="margin-left:20px">
              <el-button style="display: inline-block;" class="filter-item" type="info" icon="el-icon-tickets" @click="handleDownloadTemp"> 模板 </el-button>
              <el-upload style="display: inline-block;" :headers="headers" :data="uploadData" :action="uploadExcelUrl" :show-file-list="false" :before-upload="beforeImportExcel" :on-success="handleImportExcelSuccess">
                <el-button class="filter-item" type="warning" icon="el-icon-download">导入</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          :data="listAdd"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-bottom:30px"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
        >
          <!-- table表格 -->
          <el-table-column type="index" label="序号" align="center" width="50px" />
          <el-table-column label="库位编号" min-width="90px" prop="warehoseCode" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.warehoseCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span><br>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <a class="del" @click="handleWarehoseDelete(row)">删除</a>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="totalWarehouprovider>0" :total="totalWarehouprovider" :page.sync="getWarehouListParm.offset" :limit.sync="getWarehouListParm.pagecount" @pagination="getWarehouproviderlist" />
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="updatewarehouse()"> 确认111 </el-button> -->
        <el-button @click="dialogwarehouseVisible = false"> 关闭 </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap['eq']" :visible.sync="dialogeqVisible" :close-on-click-modal="false">
      <el-form :rules="rules" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-form-item label="可提供的设备类别" prop="eqname">
          <tree-select
            :disabled="disabled"
            :height="280"
            :width="400"
            size="small"
            multiple
            :data="parenteq"
            :default-props="eq_defaultProps"
            collapse-tags
            :node-key="eq_nodeKey"
            :checked-keys="eq_defaultCheckedKeys"
            @popoverHide="eq_popoverHide"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateeq()"> 确认 </el-button>
        <el-button @click="dialogeqVisible = false"> 关闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
import TreeSelect from '@/components/TreeSelect'
import { GetDataByName, GetDataByNames, PostDataByName, ExecDataByConfig, checkButtons, UpdateDataRelation, transData, failproccess, formatJson, GetAccount } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime, sortChange } 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: 'Product',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      disabled: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'createRole',
        offset: 0,
        pagecount: 0,
        parammaps: {}
      },
      // 1-2:table&搜索传参
      getdataListParm: {
        name: 'getProviderList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          providerName: ''
        }
      },
      // 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, params: [] }
      //  { name: 'findAllDepart', offset: 0, pagecount: 0, params: [] },
      //  { name: 'findAllEmploye', offset: 0, pagecount: 0, params: [] },
      //  { name: 'getDictByName', offset: 0, pagecount: 0, params: ['资产状态'] }
      ],

      temp: {},
      // 备件
      sparePartparentstock: [],
      getParmSparePart: {
        name: 'getpart_classList'
      },
      sparePartdefaultProps: {
        children: 'children',
        label: 'partClassName'
      },
      sparePartDefaultCheckedKeys: [],

      sparePartDataform: {
        id: '',
        name: '',
        selectSparePart: [],
        sort: '',
        enable: ''
      },
      sparePartUpdateDataRelationParam: {
        name: '',
        dataname: '',
        datavalue: '',
        valuename: '',
        values: ''
      },
      // 备件
      // 库位选择开始
      getStockParm: {
        name: 'getWarehousimple',
        page: 1,
        offset: 1,
        pagecount: 10,
        parammaps: {
          pastureId: Cookies.get('pastureid')
        }
      },
      warehoseTemp: {},
      listAdd: [],
      selectWarehose: [],
      postWarehosePramas: {},
      getWarehouListParm: {
        name: 'getWarehouproviderlist',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      totalWarehouprovider: 0,
      parentstock: [],
      nodeKey: 'id',
      defaultCheckedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'warehoseCode'
      },
      dialogstockVisible: false,
      dialogwarehouseVisible: false,
      selectedstock: '',
      dataform: {
        id: '',
        name: '',
        selectedstock: [],
        sort: '',
        enable: ''
      },
      UpdateDataRelationParam: {
        name: '',
        dataname: '',
        datavalue: '',
        valuename: '',
        values: ''
      },
      // 库位选择结束
      // 设备选择开始
      getEQParm: { name: 'geteqclasslist' },
      parenteq: [],
      eq_nodeKey: 'id',
      eq_defaultCheckedKeys: [],
      eq_defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      dialogeqVisible: false,
      selectedeq: '',
      eq_dataform: {
        id: '',
        name: '',
        selectedeq: [],
        sort: '',
        enable: ''
      },

      // 设备选择结束
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        stock: '绑定备件',
        location: '绑定库位',
        eq: '授权设备'
      },
      dialogPvVisible: false,
      // 校验规则
      rules: {
        assetNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        equipmentName: [{ required: true, message: '必填', trigger: 'blur' }],
        providerName: [{ required: true, message: '必填', trigger: 'blur' }],
        providerNumber: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      buttons: [],
      isProductDelete: [],
      isProductUpdate: [],
      isProductAdd: [],
      isPercentage: false,
      percentage: 1
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        // eslint-disable-next-line no-undef
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'insertwarehouseprovider',
        importParams: '牧场,库位,供应商',
        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.getButtons()
    })
    // this.getDownList()
    this.getList()
    this.getStockList()
    this.geteqList()
    this.getTypeList()
  },

  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    getButtons() {
      // 新增
      const ProductAdd = 'basic:product:add'
      const isProductAdd = checkButtons(this.$store.state.user.buttons, ProductAdd)
      this.isProductAdd = isProductAdd

      // 删除
      const ProductDelete = 'basic:product:delete'
      const isProductDelete = checkButtons(this.$store.state.user.buttons, ProductDelete)
      this.isProductDelete = isProductDelete
      // 编辑
      const ProductUpdate = 'basic:product:update'
      const isProductUpdate = checkButtons(this.$store.state.user.buttons, ProductUpdate)
      this.isProductUpdate = isProductUpdate
    },
    getTypeList() {
      GetDataByName(this.getParmSparePart).then(response => {
        if (response.data.list !== null) {
          this.sparePartparentstock = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    sparePartpopoverHide(checkedIds, checkedData) {
      console.log('选中值', checkedIds, checkedData)
      this.sparePartDataform.selectSparePart = checkedIds
      this.sparePartUpdateDataRelationParam.values = checkedIds
      // eslint-disable-next-line no-unreachable
    },
    // 供应商模糊查询
    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)
    },
    // 1-1: table&搜索
    getList() {
      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：下拉框
    getDownList() {
      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.getdataListParm.offset = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    form_reset() {
      this.temp = {
        // 格式化日期
        inputDatetime: parseTime(new Date(), '{y}-{m}-{d}')
      }
    },
    form_add() {
      this.form_reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // this.temp.pastureId = this.$store.state.user.pastureid
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    add_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'insertProvider'
          if (this.temp.pastureId === undefined || this.temp.pastureId === '') {
            this.temp.pastureId = '-1'
          }
          this.requestParam.parammaps = this.temp
          // console.log('牧场主键:'+this.temp.pastureId)
          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    // 设备开始
    eq_popoverHide(checkedIds, checkedData) {
      this.eq_dataform.selectedeq = checkedIds
      this.selectedeq = checkedIds
      this.UpdateDataRelationParam.values = checkedIds
    },
    geteqList() {
      GetDataByName(this.getEQParm).then(response => {
        if (response.data.list !== null) {
          this.parenteq = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    handleeqMenu(row) {
      this.dialogeqVisible = true
      this.requestParam.name = 'getEQByProvider'
      this.requestParam.parammaps = { providerId: row.id }
      this.requestParam.pagecount = 0
      this.requestParam.returntype = 'list'
      this.dialogMenuVisible = true
      GetDataByName(this.requestParam).then(response => {
        this.selectedeq = response.data.lists.eqClassId
        this.eq_defaultCheckedKeys = this.selectedeq
        this.UpdateDataRelationParam.values = this.eq_defaultCheckedKeys
      })
    },
    updateeq() {
      this.UpdateDataRelationParam.name = 'eqclass_provider'
      this.UpdateDataRelationParam.dataname = 'providerId'
      this.UpdateDataRelationParam.datavalue = this.requestParam.parammaps.providerId
      this.UpdateDataRelationParam.valuename = 'eqClassId'
      this.UpdateDataRelationParam.values = this.selectedeq

      UpdateDataRelation(this.UpdateDataRelationParam).then(response => {
        if (response.msg !== 'fail') {
          this.getList()
          this.dialogeqVisible = false
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    // 设备选择结束
    // 库位开始

    popoverHide(checkedIds, checkedData) {
      this.dataform.selectedstock = checkedIds
      this.selectedstock = checkedIds
      this.UpdateDataRelationParam.values = checkedIds
    },
    getStockList() {
      GetDataByName(this.getStockParm).then(response => {
        if (response.data.list !== null) {
          this.parentstock = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    handlePartMenu(row) {
      this.requestParam.name = 'getPartByProvider'
      this.requestParam.parammaps = { providerId: row.id }
      this.requestParam.pagecount = 0
      this.requestParam.returntype = 'list'
      GetDataByName(this.requestParam).then(response => {
        this.selectedstock = response.data.lists.partClassId
        this.defaultCheckedKeys = this.selectedstock
        this.UpdateDataRelationParam.values = this.defaultCheckedKeys
      })
      this.dialogstockVisible = true
      this.dialogMenuVisible = true
    },

    handlewarehouseMenu(row) {
      // this.requestParam.name = 'getPartByProvider'
      // this.requestParam.parammaps = { providerId: row.id }
      // this.requestParam.pagecount = 0
      // this.requestParam.returntype = 'list'
      // GetDataByName(this.requestParam).then(response => {
      //   this.selectedstock = response.data.lists.partClassId
      //   this.defaultCheckedKeys = this.selectedstock
      //   this.UpdateDataRelationParam.values = this.defaultCheckedKeys
      // })
      this.warehoseTemp = Object.assign({}, row)
      this.dialogwarehouseVisible = true
      this.dialogMenuVisible = true
      this.selectWarehose = []
      this.getWarehouproviderlist()
    },
    getWarehouproviderlist() {
      this.getWarehouListParm.parammaps.id = this.warehoseTemp.id
      this.getWarehouListParm.parammaps.pastureId = this.$store.state.user.pastureid
      GetDataByName(this.getWarehouListParm).then(response => {
        this.listAdd = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.totalWarehouprovider = response.data.total
        }
      })
    },
    querySearchWarehoseCode(queryString, cb) {
      console.log('库位模糊查询输入值', queryString)
      this.getStockParm.parammaps['warehoseCode'] = queryString
      GetDataByName(this.getStockParm).then(response => {
        console.log('备件名称模糊查询搜索data', response.data.list)
        cb(response.data.list)
      })
    },
    handleSelectWarehoseCode(item) {
      console.log('库位模糊查询选中值', item)
      if (this.listAdd != null) {
        // eslint-disable-next-line no-redeclare
        if (this.listAdd.find(obj => obj.warehouseId === item.warehouseId)) {
          this.$message({
            type: 'warning',
            message: '此库位已存在，请重新选择库位'
          })
        } else {
          this.UpdateDataRelationParam.name = 'insertWarehouprovider'
          this.UpdateDataRelationParam.parammaps = {}
          this.UpdateDataRelationParam.parammaps.id = this.warehoseTemp.id
          this.UpdateDataRelationParam.parammaps.warehouseId = item.warehouseId
          GetDataByName(this.UpdateDataRelationParam).then(response => {
            if (response.msg !== 'fail') {
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.listAdd.unshift(item)
              this.getWarehouproviderlist()
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      } else {
        this.listAdd = []

        this.UpdateDataRelationParam.name = 'insertWarehouprovider'
        this.UpdateDataRelationParam.parammaps = {}
        this.UpdateDataRelationParam.parammaps.id = this.warehoseTemp.id
        this.UpdateDataRelationParam.parammaps.warehouseId = item.warehouseId
        GetDataByName(this.UpdateDataRelationParam).then(response => {
          if (response.msg !== 'fail') {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.listAdd.unshift(item)
            this.getWarehouproviderlist()
          } else {
            failproccess(response, this.$notify)
          }
        })
      }
      this.$forceUpdate()
    },
    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 = [
               '牧场', '供应商', '库位', 'error_msg'
             ]
             const filterVal = [
               '牧场', '供应商', '库位', 'error_msg'
             ]
             const data1 = this.formatJson(filterVal, list1)
             excel.export_json_to_excel({
               header: tHeader,
               data: data1,
               filename: '供应商库位报错信息',
               autoWidth: true,
               bookType: 'xlsx'
             })
           })
        }
        this.getWarehouproviderlist()
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    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.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '供应商库位模板',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    handleWarehoseDelete(row) {
      console.log(row)
      console.log(this.listMaintenance)
      MessageBox.confirm('确认是否删除当前信息？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.postWarehosePramas.name = 'deleteWarehouprovider'
        this.postWarehosePramas.parammaps = {}
        this.postWarehosePramas.parammaps.id = row.id
        PostDataByName(this.postWarehosePramas).then(response => {
          console.log('保存发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            this.$notify({
              title: '保存失败',
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.getWarehouproviderlist()
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      })
    },
    updatestock() {
      this.UpdateDataRelationParam.name = 'partClass_provider'
      this.UpdateDataRelationParam.dataname = 'providerId'
      this.UpdateDataRelationParam.datavalue = this.requestParam.parammaps.providerId
      this.UpdateDataRelationParam.valuename = 'partClassId'
      this.UpdateDataRelationParam.values = this.selectedstock

      UpdateDataRelation(this.UpdateDataRelationParam).then(response => {
        if (response.msg !== 'fail') {
          this.getList()
          this.dialogstockVisible = false

          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    // updatewarehouse() {
    //   console.log(this.selectWarehose)
    //   for (var i = 0; i < this.listAdd.length; i++) {
    //     this.selectWarehose.push(this.listAdd[i].warehouseId)
    //   }
    //   this.UpdateDataRelationParam.name = 'warehouse_provider'
    //   this.UpdateDataRelationParam.dataname = 'providerId'
    //   this.UpdateDataRelationParam.datavalue = this.warehoseTemp.id
    //   this.UpdateDataRelationParam.valuename = 'warehouseId'
    //   this.UpdateDataRelationParam.values = this.selectWarehose

    //   UpdateDataRelation(this.UpdateDataRelationParam).then(response => {
    //     if (response.msg !== 'fail') {
    //       this.$notify({
    //         title: '成功',
    //         message: '修改成功',
    //         type: 'success',
    //         duration: 2000
    //       })
    //       this.dialogwarehouseVisible = false
    //       this.getList()
    //     } else {
    //       failproccess(response, this.$notify)
    //     }
    //   })
    // },
    // 备件选择结束
    form_edit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['temp'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateProvider'
          this.requestParam.parammaps = this.temp
          PostDataByName(this.requestParam).then(response => {
            console.log(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
              })
            }
          })
        }
      })
    },

    // 导出
    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 = 'getProviderList'
      GetAccount(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            if (response.data.list !== '') {
              this.percentage = 99
              setTimeout(() => {
                this.isPercentage = false
              }, 2000)
            }
            const tHeader = [
              '供应商名称', '供应商编码', '供应商简称', '联系人', '联系方式',
              '营业执照', '组织机构代码', '税务登记证', '开户许可证', '邮箱'
            ]

            const filterVal = [
              'providerName', 'providerNumber', 'providerIntro', 'linkman', 'telphone',
              'businessLicense', 'organizationCode', 'IRSregister', 'openLicence', 'email'
            ]
            const data1 = formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '供应商',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    form_delete(row) {
      MessageBox.confirm('设备名称：' + row.providerName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.requestParam.name = 'deleteProvider'
          this.requestParam.parammaps = {}
          this.requestParam.parammaps['id'] = row.id
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleEnableChange(index, row) { // 启用按钮更新状态
      this.requestParam.name = 'updateProviderEnable' // 接口名称
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.enable = row.enable // 传递参数
      this.requestParam.parammaps.id = row.id
      PostDataByName(this.requestParam).then(response => { // 响应信息处理
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
          this.getList()
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    handleFlexPriceChange(index, row) { // 是否线上采购
      this.requestParam = {}
      this.requestParam.common = { 'returnmap': '0' }
      this.requestParam.data = []
      this.requestParam.data[0] = { 'name': 'updateProviderflexPrice', 'type': 'e', 'parammaps': {
        flexPrice: row.flexPrice,
        id: row.id
      }}
      this.requestParam.data[1] = { 'name': 'insertBrandV2', 'type': 'e', 'parammaps': {
        brandName: row.providerName
      }}
      ExecDataByConfig(this.requestParam).then(response => {
        if (response.msg == 'fail') {
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        } else {
          this.getList()
          this.$notify({ title: '', message: '保存成功', type: 'success', duration: 2000 })
        }
      })
    }
  }
}
</script>
