<template>
  <div class="app-container">
    <div class="search" ref="search">
      <el-input v-model="table.parammaps.name" placeholder="饲料名称" style="width: 130px;" class="filter-item" clearable />
      <el-select v-model="table.parammaps.category_id" filterable placeholder="饲料类别" class="filter-item" style="width: 150px;" clearable>
        <el-option v-for="item in feedTypeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="table.parammaps.forage_source_id" filterable placeholder="饲料来源" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in feedSourcesList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="table.parammaps.is_show" filterable placeholder="是否启用" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in enableList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <div ref="selectInput" class="filter-item selectInput">
        <el-input type="text" name="" value="" placeholder="请点击选择搜索条件" class="Input" />
        <i v-if="arrowDown" icon="el-icon-arrow-down" class="el-icon-arrow-down" />
        <i v-if="arrowUp" icon="el-icon-arrow-up" class="el-icon-arrow-up" />
        <ul v-if="arrowUp" class="selectUl">
          <li><a>允许误差数</a><el-input v-model="table.parammaps.allow_error"type="text" style="width: 245px;" /></li>
          <li><a>跳转重量域</a><el-input v-model="table.parammaps.jump_weight" type="text" style="width: 245px;" /></li>
          <li>
            <a>跳转延时</a>
            <el-select v-model="table.parammaps.jump_delay" filterable placeholder="跳转延时" class="filter-item" style="width: 245px;" clearable>
              <el-option v-for="item in jumpDelayList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </li>
          <li>
            <div style="float: right;">
              <el-button class="downminCancel" @click="arrowUp=false;arrowDown=true;">取消</el-button>
              <el-button class="miniPrimary" @click="handleSearch">搜索</el-button>
            </div>
          </li>
        </ul>
      </div>
      <el-button class="successBorder" @click="handleSearch">查询</el-button>
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
    </div>
    <div class="operation" ref="operation">
      <el-button v-if="isAdd" class="success" icon="el-icon-plus" @click="handleCreate">新增</el-button>
      <!-- <el-button class="success" icon="el-icon-plus" @click="handleGetSapCode">获取SAP编码</el-button> -->
      <el-button v-if="isDelete" class="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>
      <!-- <el-button class="success" icon="el-icon-receiving" @click="handleFeedBank">饲料库</el-button> -->
     <el-button v-if="isOrder && isSort" icon="el-icon-sort" class="success" @click="handleChangeOrder">更改顺序</el-button>
       <div v-else style="display: inline-block;">
        <el-button v-if="isSort" icon="el-icon-folder-checked" class="success" @click="saveChangeOrder">保存</el-button>
        <el-button v-if="isSort" icon="el-icon-close" class="sortCancel" @click="cancelChangeOrder">取消</el-button>
      </div>
      <el-upload style="float: right;" action="#" :http-request="httpRequest" :show-file-list="false" :on-change="handleChange" :before-upload="beforeAvatarUpload" multiple accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
        <el-button v-if="isImport" class="import" icon="el-icon-download" style="float: right;">导入</el-button>
      </el-upload>
      <el-dropdown style="float: right;margin-right: 10px;">
        <el-button v-if="isExport" class="export" icon="el-icon-upload2">导出</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="handleExport(1)">导出模板</el-dropdown-item>
          <el-dropdown-item @click.native="handleExport(2)">导出数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <div class="table">
      <u-table
        id="table"
        ref="table"
        :key="table.tableKey"
        v-loading="table.listLoading"
        element-loading-text="给我一点时间"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable table-fixed"
        row-key="id"
        @selection-change="handleSelectionChange"
        :max-height="myHeight"
        use-virtual
        :row-height="rowHeight"
      >
        <u-table-column type="selection" align="center" width="50" fixed="left" />
        <u-table-column label="序号" align="center" width="50" fixed="left" prop="id" />
        <u-table-column label="饲料名称" min-width="80px" align="center" prop="name" fixed="left"/>
        <u-table-column label="饲料分类" min-width="80px" align="center" prop="category_name" fixed="left"/>
        <u-table-column label="物料类型" min-width="90px" align="center" prop="material_type_name" />
        <u-table-column label="唯一编码" min-width="80px" align="center" prop="unique_encode" />
        <u-table-column label="饲料来源" min-width="80px" align="center" prop="forage_source_name" />
        <u-table-column label="来源归属" min-width="80px" align="center" prop="data_source" />
        <u-table-column label="计划类型" min-width="80px" align="center" prop="plan_type_name" />
        <u-table-column v-if="isInforvalue" label="小料秤" min-width="90px" align="center" prop="small_material_scale" />
        <u-table-column label="允许误差数(kg)" min-width="80px" align="center" prop="allow_error" />
        <u-table-column label="包装单位重量(kg)" min-width="80px" align="center" prop="package_weight" />
        <u-table-column label="单价" min-width="80px" align="center" prop="price" />
        <u-table-column label="跳转重量域(kg)" min-width="80px" align="center" prop="jump_weight" />
        <u-table-column label="跳转延时" min-width="80px" align="center" prop="jump_delay">
          <template slot-scope="scope">
            <span v-if="scope.row.jump_delay == 0">禁用</span>
            <span v-else-if="scope.row.jump_delay == 1">3秒</span>
            <span v-else>6秒</span>
          </template>
        </u-table-column>
        <u-table-column label="确认开始" min-width="80px" align="center" prop="confirm_start">
          <template slot-scope="scope">
            <span v-if="scope.row.confirm_start == 1">启用</span>
            <span v-else>禁用</span>
          </template>
        </u-table-column>
        <u-table-column label="继电器位置" min-width="80px" align="center" prop="relay_locations" />
        <u-table-column label="无上域" min-width="60px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.jmp == 0">否</span>
            <span v-else>是</span>
          </template>
        </u-table-column>
        <u-table-column label="备用字段01" min-width="90px" align="center" prop="backup1" />
        <u-table-column label="备用字段02" min-width="90px" align="center" prop="backup2" />
        <u-table-column label="备用字段03" min-width="90px" align="center" prop="backup3" />
        <u-table-column label="是否启用" min-width="80px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_show" :disabled="!isEnable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="2"  @change="handleEnableChange(scope.$index, scope.row)"  />
          </template>
        </u-table-column>
        <u-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- <a class="correcting" @click="handleNutritive (row)">营养价值</a>
            <span class="centerSpan">|</span>
            <a class="correcting" @click="handleRelation(row)">关联</a>
            <span class="centerSpan">|</span> -->
            <el-button v-if="isEdit" icon="el-icon-edit-outline" class="miniSuccess" @click="handleUpdate(row)" />
            <span v-if="isEdit && isDelete" class="centerSpan">|</span>
            <el-button v-if="isDelete" icon="el-icon-delete" class="miniDanger" @click="handleRowDelete(row)" />
          </template>
        </u-table-column>
      </u-table>
      <span v-if="table.listLoading == false" style="margin-right: 30px;margin-top: 10px;font-size: 14px;">共{{ table.total }}条</span>
    </div>

    <!-- 新增/编辑 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[create.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-add">
        <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="155px" style="width: 100%;margin:0 auto 50px">
          <el-row>
            <el-col :span="24">
              <h3 style="width: 160px;text-align: right;">基础信息</h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="饲料名称：" prop="name">
                <el-input ref="name" v-model="create.temp.name" class="filter-item" placeholder="请输入饲料名称" type="textarea" :autosize="{ minRows:1}" maxlength="32" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="饲料类别：" prop="category_id">
                <el-select v-model="create.temp.category_id" filterable placeholder="饲料类别" class="filter-item" style="width: 100%;" @change="changeFeedList">
                  <el-option v-for="item in feedTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              </el-col>
            <el-col :span="6">
              <el-form-item label="唯一编码：" prop="unique_encode">
                <el-input ref="unique_encode" v-model="create.temp.unique_encode" class="filter-item" placeholder="请输入唯一编码" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="饲料来源：" prop="forage_source_id">
                <el-select v-model="create.temp.forage_source_id" filterable placeholder="饲料来源" class="filter-item" style="width: 100%;" @change="changeFeedSource">
                  <el-option v-for="item in feedSourcesList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="计划类型：" prop="plan_type_id">
                <el-select v-model="create.temp.plan_type_id" filterable placeholder="计划类型" class="filter-item" style="width: 100%;" @change="changePlantype">
                  <el-option v-for="item in planTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="包装单位重量（kg）：" prop="package_weight">
                <el-input ref="package_weight" v-model="create.temp.package_weight" class="filter-item" placeholder="正整数" type="number" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单价：" prop="price">
                <el-input ref="price" v-model="create.temp.price"  class="filter-item" placeholder="最多俩位小数" type="number" step="0.01" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="物料类型：" prop="material_type_key">
                <el-select v-model="create.temp.material_type_key" filterable placeholder="物料类型" class="filter-item" style="width: 100%;" @change="changeMaterialType">
                  <el-option v-for="item in materialtypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="SAP货位：" prop="goods">
                <el-select v-model="create.temp.goods" filterable placeholder="SAP货位" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in sapGoodsList" :key="item.id" :label="item.mixname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="SAP编码：" prop="sapcode">
                <el-select v-model="create.temp.sapcode" filterable placeholder="SAP编码" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in sapCodeList" :key="item.id" :label="item.mixname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3 style="width: 160px;text-align: right;">搅拌参数</h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="允许误差数（kg）：" prop="allow_error">
                <el-input ref="allow_error" v-model="create.temp.allow_error" class="filter-item" placeholder="正整数" type="number" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="跳转重量域（kg）：" prop="jump_weight">
                <el-input ref="jump_weight" v-model="create.temp.jump_weight" :disabled="create.temp.jump_delay==0" class="filter-item" placeholder="0-50之间的整数" type="number" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="跳转延时：" prop="jump_delay">
                <el-select v-model="create.temp.jump_delay" filterable placeholder="跳转延时" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in jumpDelayList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="确认开始：" prop="confirm_start">
                <el-select v-model="create.temp.confirm_start" filterabler placeholde="确认开始" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in confirmStartList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="是否启用：" prop="is_show">
                <el-select v-model="create.temp.is_show" filterable placeholder="是否启用" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in enableList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="继电器位置：" prop="relay_locations">
                <el-input ref="relay_locations" v-model="create.temp.relay_locations" class="filter-item" placeholder="继电器位置" type="number" />
              </el-form-item>
            </el-col>
            <el-col v-if="isInforvalue" :span="6">
              <el-form-item label="小料秤：" prop="smtmrid">
                <el-select v-model="create.temp.smtmrid" filterable placeholder="小料秤" clearable class="filter-item" style="width: 100%;">
                  <el-option v-for="item in smallMaterialList" :key="item.id" :label="item.tname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="无上域：" prop="jmp">
                <el-select v-model="create.temp.jmp" placeholder="无上域" class="filter-item" style="width: 100%;">
                  <el-option v-for="item in jmpList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <h3 style="width: 160px;text-align: right;">备用字段</h3>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="备用字段01：" prop="backup1">
                <el-input ref="backup1" v-model="create.temp.backup1" class="filter-item" placeholder="备用字段01" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备用字段02：" prop="backup2">
                <el-input ref="backup2" v-model="create.temp.backup2" class="filter-item" placeholder="备用字段02" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备用字段03：" prop="backup3">
                <el-input ref="backup3" v-model="create.temp.backup3" class="filter-item" placeholder="备用字段03" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;getList()">关闭</el-button>
          <el-button v-if="create.dialogStatus==='create' || create.dialogStatus==='update'" class="save" :disabled="isokDisable" @click="create.dialogStatus==='create'?createData():updateData()">确认</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 饲料库 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="feedBank.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[feedBank.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-add">
        <div class="search">
          <el-input v-model="feedBank.getdataListParm.parammaps.fname" placeholder="饲料名称" style="width: 130px;" class="filter-item" clearable />
          <el-select v-model="feedBank.getdataListParm.parammaps.statue" filterabler placeholder="关联状态" class="filter-item" style="width: 120px;" clearable>
            <el-option v-for="item in associationStatusList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button class="successBorder" @click="handleFeedBankSearch">查询</el-button>
          <el-button class="successBorder" @click="handleFeedBankRefresh">重置</el-button>
        </div>
        <div class="table">
          <el-table
            :key="feedBank.tableKey"
            v-loading="feedBank.listLoading"
            element-loading-text="给我一点时间"
            :data="feedBank.list"
            border
            fit
            highlight-current-row
            style="width: 100%;margin: 0 auto 50px;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
          >
            <el-table-column label="序号" align="center" type="index" width="50px" />
            <el-table-column label="来源" min-width="50" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.sources }}</span>
              </template>
            </el-table-column>
            <el-table-column label="中国饲料号" min-width="70px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.feedcode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="饲料名称" min-width="80px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="价格" min-width="50px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column label="样品说明" min-width="50px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column label="干物质(DM%)" min-width="65px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.dry }}</span>
              </template>
            </el-table-column>
            <el-table-column label="淀粉(%DM)" min-width="59px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.starch }}</span>
              </template>
            </el-table-column>
            <el-table-column label="粗蛋白(CP%DM)" min-width="70px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.cp }}</span>
              </template>
            </el-table-column>
            <el-table-column label="钙(Ca%DM)" min-width="85px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ca }}</span>
              </template>
            </el-table-column>
            <el-table-column label="磷(P%DM)" min-width="85px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.p }}</span>
              </template>
            </el-table-column>
            <el-table-column label="产奶净能(%DM)" min-width="75px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.n }}</span>
              </template>
            </el-table-column>
            <el-table-column label="脂肪(%DM)" min-width="59px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fat }}</span>
              </template>
            </el-table-column>
            <el-table-column label="ADF(%DM)" min-width="60px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.adf }}</span>
              </template>
            </el-table-column>
            <el-table-column label="NDF(%DM)" min-width="60px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ndf }}</span>
              </template>
            </el-table-column>
            <el-table-column label="NDIP%" min-width="70px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ndip }}</span>
              </template>
            </el-table-column>
            <el-table-column label="粗灰分(Ash%)" min-width="65px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ash }}</span>
              </template>
            </el-table-column>
            <el-table-column label="粗料" min-width="50px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.iscu }}</span>
              </template>
            </el-table-column>
            <el-table-column label="关联状态" min-width="50px" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.statue==0">否</span>
                <span v-if="scope.row.statue==1">是</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose cancelClose1" @click="feedBank.dialogFormVisible = false; ">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 关联 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="relation.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[relation.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-add">
        <div class="search">
          <el-input v-model="relation.getdataListParm.parammaps.fname" placeholder="饲料名称" style="width: 130px;" class="filter-item" clearable />
          <el-button class="successBorder" @click="handleRelationSearch">查询</el-button>
        </div>
        <div class="table">
          <el-table
            :key="relation.tableKey"
            v-loading="relation.listLoading"
            element-loading-text="给我一点时间"
            :data="relation.list"
            border
            fit
            highlight-current-row
            style="width: 100%;margin: 0 auto 50px;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
          >
            <el-table-column label="序号" align="center" type="index" width="50px" />
            <el-table-column label="来源" min-width="50" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.sources }}</span>
              </template>
            </el-table-column>
            <el-table-column label="中国饲料号" min-width="80px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.feedcode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="饲料名称" min-width="80px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="价格" min-width="50px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column label="样品说明" min-width="50px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column label="干物质(DM%)" min-width="65px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.dry }}</span>
              </template>
            </el-table-column>
            <el-table-column label="淀粉(%DM)" min-width="59px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.starch }}</span>
              </template>
            </el-table-column>
            <el-table-column label="粗蛋白(CP%DM)" min-width="75px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.cp }}</span>
              </template>
            </el-table-column>
            <el-table-column label="钙(Ca%DM)" min-width="83px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ca }}</span>
              </template>
            </el-table-column>
            <el-table-column label="磷(P%DM)" min-width="80px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.p }}</span>
              </template>
            </el-table-column>
            <el-table-column label="产奶净能(%DM)" min-width="75px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.n }}</span>
              </template>
            </el-table-column>
            <el-table-column label="脂肪(%DM)" min-width="59px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.fat }}</span>
              </template>
            </el-table-column>
            <el-table-column label="ADF(%DM)" min-width="60px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.adf }}</span>
              </template>
            </el-table-column>
            <el-table-column label="NDF(%DM)" min-width="60px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ndf }}</span>
              </template>
            </el-table-column>
            <el-table-column label="NDIP%" min-width="70px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ndip }}</span>
              </template>
            </el-table-column>
            <el-table-column label="粗灰分(Ash%)" min-width="65px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.ash }}</span>
              </template>
            </el-table-column>
            <el-table-column label="粗料" min-width="50px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.iscu }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="50px" align="center" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <a v-if="row.statueRelation == '1'" class="correcting" :disabled="isokDisable" @click="disassociateData(row)">取消关联</a>
                <a v-if="row.statueRelation == '0'" class="correcting" :disabled="isokDisable" @click="relationData(row)">关联</a>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose cancelClose1" @click="relation.dialogFormVisible = false;getList() ">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 营养价值 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="nutritive.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[nutritive.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-add">
        <el-form ref="temp" :rules="nutritive.rules" :model="nutritive.temp" label-position="right" label-width="160px" style="width: 100%;margin:0 auto 50px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="干物质（DM%）：" prop="dry">
                <el-input ref="dry" v-model="nutritive.temp.dry"  :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入干物质" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="淀粉（%DM）：" prop="starch">
                <el-input ref="starch" v-model="nutritive.temp.starch" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入淀粉" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="粗蛋白（CP%DM)：" prop="cp">
                <el-input ref="cp" v-model="nutritive.temp.cp" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入粗蛋白" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="钙（Ca%DM）：" prop="ca">
                <el-input ref="ca" v-model="nutritive.temp.ca" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入钙" type="number" step="0.01" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="磷（P%DM）：" prop="p">
                <el-input ref="p" v-model="nutritive.temp.p" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入磷" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产奶净能（%DM）：" prop="n">
                <el-input ref="n" v-model="nutritive.temp.n" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入产奶净能" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="脂肪（%DM）：" prop="fat">
                <el-input ref="fat" v-model="nutritive.temp.fat" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入脂肪" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="ADF（%DM）：" prop="adf">
                <el-input ref="adf" v-model="nutritive.temp.adf" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入ADF" type="number" step="0.01" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="NDF（%DM）：" prop="ndf">
                <el-input ref="ndf" v-model="nutritive.temp.ndf" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入NDF" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="NDIP(%)：" prop="ndip">
                <el-input ref="ndip" v-model="nutritive.temp.ndip" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入NDIP" type="number" step="0.01" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="粗灰分（Ash%）：" prop="ash">
                <el-input ref="ash" v-model="nutritive.temp.ash" v-limit :disabled="isRoleEdit==false" class="filter-item" placeholder="请输入粗灰分" type="number" min="0.00" step="0.01" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="nutritive.dialogFormVisible = false;getList()">关闭</el-button>
          <el-button v-if="nutritive.dialogStatus==='nutritive' && isRoleEdit" class="save" :disabled="isokDisable" @click="nutritiveData()">确认</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 获取SAP编码 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="sapCode.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[sapCode.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="app-add">
        <div class="search" ref="search">
          <el-input v-model="sapCode.table.getdataListParm.parammaps.MAKTX" placeholder="原料名称" style="width: 130px;" class="filter-item" clearable />
          <el-button class="successBorder" @click="handleSapCodeSearch">查询</el-button>
        </div>
        <div class="table">
          <u-table
            id="saptable"
            ref="saptable"
            :key="sapCode.table.tableKey"
            v-loading="sapCode.table.listLoading"
            element-loading-text="给我一点时间"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
            row-key="id"
            @selection-change="handleSapCodeSelectionChange"
            :max-height="myHeight"
            use-virtual
            :row-height="rowHeight"
          >
            <u-table-column type="selection" align="center" width="50"/>
            <u-table-column label="物料号" min-width="80px" align="center" prop="MATNR"/>
            <u-table-column label="物料类型" min-width="90px" align="center" prop="MTART" />
            <u-table-column label="物料组" min-width="80px" align="center" prop="MATKL"/>
            <u-table-column label="物料描述" min-width="90px" align="center" prop="MAKTX" />
            <u-table-column label="最后修改日期" min-width="80px" align="center" prop="LAEDA" />
          </u-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="sapCode.dialogFormVisible = false;getList()">关闭</el-button>
          <el-button v-if="sapCode.dialogStatus==='sapCode' && isRoleEdit" class="save" :disabled="isokDisable" @click="sapCodeData()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { postJson,delJson,exportFile,importFile,checkButtons } from '@/api/common'
import Cookies from 'js-cookie'
import Sortable from 'sortablejs'
import Pagination from '@/components/Pagination'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { parseTime, json2excel, handleTableSpan, handleObjectSpanMethod } from '@/utils/index.js'
import { MessageBox } from 'element-ui'
import localDownloadUtil from "@/utils/localDownloadUtil.js";
export default {
  name: 'FeedTable',
  components: { Pagination },
  directives: {
    limit: {
      // 指令的定义
      update: function(el) {
        el.onkeypress = function(e) {
          var code = e.charCode
          if (code != 0) {
            if (!String.fromCharCode(code).match(/[0-9\.]/)) {
              return false
            }
          }
        }
        el.addEventListener('textInput', function(e) {
          e.target.value = e.target.value.replace(/[^0-9\.]/g, '')
        })
        el.onkeyup = function(e) {
          e.target.value = e.target.value.replace(/[^0-9\.]/g, '')
        }
      }
    }
  },
  data() {
    return {
      isRoleEdit:[],


      // 饲料库
      feedBank: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {},
        rules: {},
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        getdataListParm: {
          name: 'getFeednurList',
          page: 1,
          offset: 1,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            fname: '',
            statue: ''
          }
        }
      },
      // 关联
      relation: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {},
        rules: {},
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        getdataListParm: {
          name: 'getFeednurRelation',
          page: 1,
          offset: 1,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            fname: ''
          }
        }
      },

      // 营养价值
      nutritive: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {},
        rules: {}
      },

      sapCode:{
        dialogFormVisible: false,
        dialogStatus: '',
        selectList:[],
        table: {
          tableKey: 0,
          list: [],
          total: 0,
          listLoading: false,
          getdataListParm: {
            name: 'getFeedSap',
            page: 1,
            offset: 1,
            pagecount: '',
            returntype: 'Map',
            parammaps: {
              MAKTX:''
            }
          }
        }
      },
      // ===============
      table: {
        page: 1,
        page_size: parseInt(Cookies.get('pageCount')),
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        parammaps: {
         name:'',category_id:'',forage_source_id:'',is_show:'',allow_error:'',jump_weight:'',jump_delay_id:''
        }
      },
      // 多项搜索显示隐藏
      arrowDown: true,
      arrowUp: false,
      enableList: JSON.parse(sessionStorage.downlist).is_show, // 是否启用
      feedSourcesList: JSON.parse(sessionStorage.downlist).forage_source, // 饲料来源
      confirmStartList: JSON.parse(sessionStorage.downlist).confirm_start, // 确认开始
      associationStatusList: JSON.parse(sessionStorage.downlist).is_show, // 关联状态
      jumpDelayList: JSON.parse(sessionStorage.downlist).jump_dela_type, // 跳转延时
      feedTypeList: JSON.parse(sessionStorage.downlist).forage_parent_category, // 饲料类别
      planTypeList: JSON.parse(sessionStorage.downlist).forage_plan_type, // 计划类型
      jmpList:  JSON.parse(sessionStorage.downlist).is_show, // 无上域
      materialtypeList:JSON.parse(sessionStorage.downlist).formula_type,//物料类型
      smallMaterialList: [], // 小料秤todo
      sapGoodsList:[],//sap货位todo
      sapCodeList:[],//sap编码todo
      isInforvalue: false,
      rowHeight: 30,
      dialogFull: false,
      textMap: {
        create: '新增',
        update: '编辑',
        feedBank: '饲料库',
        relation: '关联',
        nutritive: '营养价值',
        sapCode: '获取SAP编码'
      },
      // 新增/编辑
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          name: '',
          category_id: '',category_name: '',
          material_type_key:'',
          unique_encode: '',
          forage_source_id: 2,forage_source_name:'用户自定义',
          plan_type_id: 0,plan_type_name:'无',
          small_material_scale:'',
          package_weight: '',
          price:'',
          materialtype:'',
          allow_error:'',
          jump_weight:'',
          jump_delay: 0,
          confirm_start: 2,
          is_show: 1,
          relay_locations:'',
          jmp:2,
          backup1: '',
          backup2: '',
          backup3: '',
          material_type_name:''
        },
        rules: {
          name :[{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          category_id: [{ required: true, message: '必填', trigger: 'blur' }],
          material_type_key: [{ required: true, message: '必填', trigger: 'blur' }],
          unique_encode: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          forage_source_id: [{ required: true, message: '必填', trigger: 'blur' }],
          plan_type_id: [{ required: true, message: '必填', trigger: 'blur' }],
          jump_delay: [{ required: true, message: '必填', trigger: 'blur' }],
          confirm_start: [{ required: true, message: '必填', trigger: 'blur' }],
          jmp: [{ required: true, message: '必填', trigger: 'blur' }]
        }
      },

      isokDisable: false,
      selectList: [],
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      dropState: false,
      isOrder: true,
      myHeight:document.documentElement.clientHeight - 85- 150,
      dataForm:{
        name: "",
        file: null,
      },
      isAdd:'',isEdit:'',isResetpassword:'',isDelete:'',isEnable:'',isImport:'',isExport:'',isSort:''
    }
  },


  mounted() {
    document.addEventListener('click', (e) => {
      if (this.$refs.selectInput !== undefined) {
        if (!this.$refs.selectInput.contains(e.target)) {
          this.arrowDown = true
          this.arrowUp = false
        } else {
          this.arrowDown = false
          this.arrowUp = true
        }
      }
    })
  },
  created() {
    this.getButton()
    this.getList()
    // this.getInforvalueList()
  },

  methods: {
    getButton(){
      const add = 'rangeManagement:feedTable:add'
      this.isAdd = checkButtons(add)
      const edit = 'rangeManagement:feedTable:edit'
      this.isEdit = checkButtons(edit)
      const del = 'rangeManagement:feedTable:delete'
      this.isDelete = checkButtons(del)
      const enable = 'rangeManagement:feedTable:enable'
      this.isEnable = checkButtons(enable)
      const _import = 'rangeManagement:feedTable:import'
      this.isImport = checkButtons(_import)
      const _export = 'rangeManagement:feedTable:export'
      this.isExport = checkButtons(_export)
      const _sort = 'rangeManagement:feedTable:sort'
      this.isSort = checkButtons(_sort)
    },
    getList() {
      this.table.listLoading = true
      let page = this.table.page
      let page_size = this.table.page_size
      let url = 'api/v1/ops/forage/list' + '?page=' + page + '&page_size=' + page_size
      let data = {
        "name":this.table.parammaps.name
      }
      if(this.table.parammaps.is_show !== ''){
        data.is_show = this.table.parammaps.is_show
      }
      if(this.table.parammaps.category_id !== ''){
        data.category_id = this.table.parammaps.category_id
      }
      if(this.table.parammaps.forage_source_id !== ''){
        data.forage_source_id = this.table.parammaps.forage_source_id
      }
      if(this.table.parammaps.jump_delay_id !== ''){
        data.jump_delay_id = this.table.parammaps.jump_delay_id
      }
      if(this.table.parammaps.allow_error !== ''){
        data.allow_error = this.table.parammaps.allow_error
      }
      if(this.table.parammaps.jump_weight !== ''){
        data.jump_weight = this.table.parammaps.jump_weight
      }
      postJson(url, data).then(response => {
        if (response.code == 200) {
          this.table.list = response.data.list
          this.table.total = response.data.total
        } else {
          this.table.list = []
        }
         this.$refs.table.reloadData(this.table.list)
        setTimeout(() => {
          this.table.listLoading = false
        }, 1000)
      })
    },
    getInforvalueList() {
      let url = 'api/v1/ops/forage/small_material'
      console.log(JSON.parse(sessionStorage.pastureList))
      let pastureList = JSON.parse(sessionStorage.pastureList)
      let idList = []
      pastureList.forEach(item=>{
        idList.push(item.id)
      })
      console.log(idList,'idList')
      let data = {
        "api_name": "getSysoptEnable",
        "pasture_id": idList,
        "info_name": "isSmallMaterial"
      }
      postJson(url,data).then(response => {
        if (response.data !== null) {
          if (response.data.list[0].inforvalue == 0) {
            this.isInforvalue = false
          } else {
            this.isInforvalue = true
          }
        } else {
          this.isInforvalue = false
        }
      })
    },
    handleExport(item) {
      if (item == 1) {
        console.log('导出模板')
        let url = 'api/v1/ops/forage/excel_template'
        let data = {name:''}
        exportFile(url, data).then(response => {
          let xlxsname = '饲料表模板' + parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}') + '.xlsx'
          localDownloadUtil.blobDownloads(response,xlxsname)
        })
      } else {
        console.log('导出数据')
        let url = 'api/v1/ops/forage/excel_export'
        let data = {name:''}
        exportFile(url, data).then(response => {
          let xlxsname = '饲料表' + parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}') + '.xlsx'
          localDownloadUtil.blobDownloads(response,xlxsname)
        })
      }
    },
    handleImport(){
      let url = 'api/v1/ops/forage/excel_import'
      let data = {name:''}
      importFile(url, data).then(response => {

      })
    },
    //验证文件类型
    beforeAvatarUpload(file) {
      console.log(file);
      const isXls = file.type === "application/vnd.ms-excel" ? true : file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ? true : false;
      if (!isXls) {
        alert("上传的文件只能是xls以及xlsx格式!");
      }
      return isXls;
    },
    // 判断文件个数
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
      console.log(this.dataForm.file);
    },
    // 导入
    httpRequest(param) {
      let formData = new FormData();
      formData.append('file', this.dataForm.file.raw);
      let url = 'api/v1/ops/forage/excel_import';
      let data = formData
      console.log(param.file);
      axios({
        method: 'POST',
        url: process.env.VUE_APP_BASE_API + url,
        data: data,
        headers: {
          'Authorization': 'Bearer ' + getToken(),
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if(res.code == 200){
          this.$notify({ title: '成功', message:'操作成功', type: 'success', duration: 2000 })
          this.getList()
        }
      }).catch((e) => {
        console.log(e);
      });
    },
    handleSearch() {
      this.table.page = 1
      this.getList()
      this.arrowDown = true
      this.arrowUp = false
    },
    handleRefresh() {
      console.log('点击了重置')
      this.table.parammaps.name = ''
      this.table.parammaps.category_id = ''
      this.table.parammaps.forage_source_id = ''
      this.table.parammaps.is_show = ''
      this.table.parammaps.allow_error = ''
      this.table.parammaps.jump_weight = ''
      this.table.parammaps.jump_delay_id = ''
      this.table.page = 1
      this.getList()
    },
    // 新增
    handleCreate() {
      console.log('点击了新增')
      this.resetTemp()
      this.dialogFull = false
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
    },
    resetTemp() {
      this.create.temp = {
        name: '',
        category_name:'',
        category_id: '',
        material_type_key:'',
        unique_encode:'',
        forage_source_id:2,forage_source_name:'用户自定义',
        plan_type_id: 0,plan_type_name:'无',
        small_material_scale:'',
        package_weight:'',
        price:'',
        materialtype:'',
        allow_error:'',
        jump_weight:'',
        jump_delay:0,
        confirm_start:2,
        is_show:1,
        relay_locations:'',
        jmp:2,
        backup1:'',
        backup2:'',
        backup3:''
      }
    },
    // 饲料来源
    changeFeedSource(item){
      this.create.temp.forage_source_name = this.feedSourcesList.find(obj => obj.value === item).label
    },
    // 计划类型
    changePlantype(item) {
      this.create.temp.plan_type_name = this.planTypeList.find(obj => obj.value === item).label
    },
    // 饲料类型
    changeFeedList(item) {
      this.create.temp.category_name = this.feedTypeList.find(obj => obj.value === item).label
    },
    changeMaterialType(item) {
      this.create.temp.material_type_name = this.materialtypeList.find(obj => obj.value === item).label
    },
    createData() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          const package_weight = /^[1-9]\d*$/
          if (this.create.temp.package_weight !== '') {
            if (!package_weight.test(parseFloat(this.create.temp.package_weight))) {
              this.$message({ type: 'error', message: '包装单位重量请输入正整数', duration: 2000 })
              return false
            }
          }
           const price =  /^(\d+|\d+\.\d{1,2})$/
          if (this.create.temp.price !== '') {
            if (!price.test(parseFloat(this.create.temp.price))) {
              this.$message({ type: 'error', message: '单价请保留两位小数', duration: 2000 })
              return false
            }
          }
          if (this.create.temp.jump_weight !== '') {
            const jump_weight = /^([0-9]|(1[0-9]|2[0-9]|3[0-9]|4[0-9]|(50)))$/
            if (!jump_weight.test(parseFloat(this.create.temp.jump_weight))) {
              this.$message({ type: 'error', message: '跳转重量域请输入大于等于0小于等于50的整数', duration: 2000 })
              return false
            }
          }
          if (this.create.temp.relay_locations.length > 8) {
            this.$message({ type: 'error', message: '继电器位置请输入1-8位数字', duration: 2000 })
            return false
          }
          const allow_error = /^[0-9]\d*$/
          if (this.create.temp.allow_error !== '') {
            if (!allow_error.test(parseFloat(this.create.temp.allow_error))) {
              this.$message({ type: 'error', message: '允许误差数请输入大于等于0的整数', duration: 2000 })
              return false
            }
          }
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          let url = 'api/v1/ops/forage/add'
          let data = {
            "name": this.create.temp.name,
            "category_id": this.create.temp.category_id,
            "category_name": this.create.temp.category_name,
            "material_type_key": this.create.temp.material_type_key,
            "material_type_name": this.create.temp.material_type_name,
            "unique_encode": this.create.temp.unique_encode,
            "forage_source_id": this.create.temp.forage_source_id,
            "forage_source_name": this.create.temp.forage_source_name,
            "plan_type_id": this.create.temp.plan_type_id,
            "plan_type_name": this.create.temp.plan_type_name,
            "jump_delay": this.create.temp.jump_delay,
            "confirm_start": this.create.temp.confirm_start,
            "jmp": this.create.temp.jmp,
            "backup1": this.create.temp.backup1,
            "backup2": this.create.temp.backup2,
            "backup3": this.create.temp.backup3,
            "is_show": this.create.temp.is_show
          }
          if(this.create.temp.small_material_scale){ data.small_material_scale = this.create.temp.small_material_scale }
          if(this.create.temp.allow_error){ data.allow_error = parseFloat(this.create.temp.allow_error) }
          if(this.create.temp.package_weight){ data.package_weight = parseFloat(this.create.temp.package_weight) }
          if(this.create.temp.price){ data.price = parseFloat(this.create.temp.price) }
          if(this.create.temp.jump_weight){ data.jump_weight = parseFloat(this.create.temp.jump_weight) }
          if(this.create.temp.relay_locations){ data.relay_locations = parseFloat(this.create.temp.relay_locations) }
          if(this.create.temp.backup1){ data.backup1 = this.create.temp.backup1 }
          if(this.create.temp.backup2){ data.backup2 = this.create.temp.backup2 }
          if(this.create.temp.backup3){ data.backup3 = this.create.temp.backup3 }

          postJson(url, data).then(response => {
            if(response.code == 200){
              this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },

    // 编辑
    handleUpdate(row) {
      console.log('点击了编辑', row)
      this.create.dialogStatus = 'update'
      this.dialogFull = false
      this.create.dialogFormVisible = true
      this.create.temp = Object.assign({}, row)
      if(this.create.temp.package_weight == 0){
        this.create.temp.package_weight = ''
      }
      this.create.temp.plan_type_name = this.planTypeList.find(obj => obj.value === row.plan_type_id).label
      this.create.temp.forage_source_name = this.feedSourcesList.find(obj => obj.value === row.forage_source_id).label
      this.create.temp.category_name = this.feedTypeList.find(obj => obj.value === row.category_id).label
    },
    updateData() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['temp'].validate(valid => {
        if (valid) {
          const package_weight = /^[1-9]\d*$/
          if (this.create.temp.package_weight !== '') {
            if (!package_weight.test(parseFloat(this.create.temp.package_weight))) {
              this.$message({ type: 'error', message: '包装单位重量请输入正整数', duration: 2000 })
              return false
            }
          }
           const price =  /^(\d+|\d+\.\d{1,2})$/
          if (this.create.temp.price !== '') {
            if (!price.test(parseFloat(this.create.temp.price))) {
              this.$message({ type: 'error', message: '单价请保留两位小数', duration: 2000 })
              return false
            }
          }
          if (this.create.temp.jump_weight !== '') {
            const jump_weight = /^([0-9]|(1[0-9]|2[0-9]|3[0-9]|4[0-9]|(50)))$/
            if (!jump_weight.test(parseFloat(this.create.temp.jump_weight))) {
              this.$message({ type: 'error', message: '跳转重量域请输入大于等于0小于等于50的整数', duration: 2000 })
              return false
            }
          }
          if (this.create.temp.relay_locations.length > 8) {
            this.$message({ type: 'error', message: '继电器位置请输入1-8位数字', duration: 2000 })
            return false
          }
          const allow_error = /^[0-9]\d*$/
          if (this.create.temp.allow_error !== '') {
            if (!allow_error.test(parseFloat(this.create.temp.allow_error))) {
              this.$message({ type: 'error', message: '允许误差数请输入大于等于0的整数', duration: 2000 })
              return false
            }
          }
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          let url = 'api/v1/ops/forage/edit'
          let data = {
            "id":this.create.temp.id,
            "name": this.create.temp.name,
            "category_id": this.create.temp.category_id,
            "category_name": this.create.temp.category_name,
            "material_type_key": this.create.temp.material_type_key,
            "material_type_name": this.create.temp.material_type_name,
            "unique_encode": this.create.temp.unique_encode,
            "forage_source_id": this.create.temp.forage_source_id,
            "forage_source_name": this.create.temp.forage_source_name,
            "plan_type_id": this.create.temp.plan_type_id,
            "plan_type_name": this.create.temp.plan_type_name,
            "jump_delay": this.create.temp.jump_delay,
            "confirm_start": this.create.temp.confirm_start,
            "jmp": this.create.temp.jmp,
            "backup1": this.create.temp.backup1,
            "backup2": this.create.temp.backup2,
            "backup3": this.create.temp.backup3,
            "is_show": this.create.temp.is_show
          }
          if(this.create.temp.small_material_scale){ data.small_material_scale = this.create.temp.small_material_scale }
          if(this.create.temp.allow_error){ data.allow_error = parseFloat(this.create.temp.allow_error) }
          if(this.create.temp.package_weight){ data.package_weight = parseFloat(this.create.temp.package_weight) }
          if(this.create.temp.price){ data.price = parseFloat(this.create.temp.price) }
          if(this.create.temp.jump_weight){ data.jump_weight = parseFloat(this.create.temp.jump_weight) }
          if(this.create.temp.relay_locations){ data.relay_locations = parseFloat(this.create.temp.relay_locations) }
          if(this.create.temp.backup1){ data.backup1 = this.create.temp.backup1 }
          if(this.create.temp.backup2){ data.backup2 = this.create.temp.backup2 }
          if(this.create.temp.backup3){ data.backup3 = this.create.temp.backup3 }

          postJson(url, data).then(response => {
            if(response.code == 200){
              this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    // 行内删除
    handleRowDelete(row) {
      console.log('点击了行内删除')
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.selectList = []
        let url = 'api/v1/ops/forage/delete'
          let data = [row.id]
          postJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
      })
    },
    handleSelectionChange(val) {
      this.selectList = []
      val.forEach((item,index)=>{
        this.selectList.push(item.id)
      })
    },
    // 多项删除
    handleDelete() {
      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择饲料表信息', duration: 2000 })
      } else {
        MessageBox.confirm('当前选中' + this.selectList.length + '条信息，是否删除?', {
          confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
        }).then(() => {
          let url = 'api/v1/ops/forage/delete'
          let data = this.selectList
          postJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        })
      }
    },
    handleEnableChange(index, row) {
      let url = 'api/v1/ops/forage/is_show'
      let data = {
        "forage_id":row.id,
        "is_show":row.is_show
      }
      postJson(url,data).then(response => {
        if(response.code == 200){
          this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
          this.getList()
        }
      })
    },

    // 待对

    // 饲料库
    handleFeedBank() {
      console.log('点击了饲料库')
      this.dialogFull = false
      this.feedBank.dialogStatus = 'feedBank'
      this.feedBank.dialogFormVisible = true
      this.getFeedBankList()
    },
    getFeedBankList() {
      this.feedBank.listLoading = true
      GetDataByName(this.feedBank.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.feedBank.list = response.data.list
          this.feedBank.pageNum = response.data.pageNum
          this.feedBank.pageSize = response.data.pageSize
          this.feedBank.total = response.data.total
        } else {
          this.feedBank.list = []
        }
        setTimeout(() => {
          this.feedBank.listLoading = false
        }, 100)
      })
    },
    handleFeedBankSearch() {
      console.log('点击了饲料库搜索')
      this.getFeedBankList()
      this.feedBank.getdataListParm.offset = 1
    },
    handleFeedBankRefresh() {
      console.log('点击了饲料库重置')
      this.feedBank.getdataListParm.parammaps.fname = ''
      this.feedBank.getdataListParm.parammaps.statue = ''
      this.getFeedBankList()
    },

    // 关联
    handleRelation(row) {
      console.log('点击了关联')
      this.dialogFull = false
      this.relation.dialogStatus = 'relation'
      this.relation.dialogFormVisible = true
      this.relation.temp = Object.assign({}, row)
      this.relation.getdataListParm.parammaps.fid = this.relation.temp.id
      this.getRelationList()
    },
    getRelationList() {
      this.relation.listLoading = true
      GetDataByName(this.relation.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.relation.list = response.data.list
          this.relation.pageNum = response.data.pageNum
          this.relation.pageSize = response.data.pageSize
          this.relation.total = response.data.total
        } else {
          this.relation.list = []
        }
        setTimeout(() => {
          this.relation.listLoading = false
        }, 100)
      })
    },
    handleRelationSearch() {
      console.log('点击了关联搜索')
      this.relation.getdataListParm.offset = 1
      this.getRelationList()
    },
    disassociateData(row) {
      console.log('点击了取消关联')
      MessageBox.confirm('是否确认取消关联?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.isokDisable = true
        setTimeout(() => {
          this.isokDisable = false
        }, 1000)
        this.requestParam.name = 'updateFeedrelation'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.pastureid = this.relation.temp.pastureid
        this.requestParam.parammaps.fid = this.relation.temp.id
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          console.log('取消关联保存发送参数', this.requestParam)
          if (response.msg !== 'fail') {
            this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
            this.getRelationList()
            this.getList()
          } else {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消' })
      })
    },
    relationData(row) {
      console.log('点击了关联保存')
      MessageBox.confirm('是否确认关联?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.isokDisable = true
        setTimeout(() => {
          this.isokDisable = false
        }, 1000)
        this.requestParam.name = 'insertFeednur'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.pastureid = this.relation.temp.pastureid
        this.requestParam.parammaps.fid = this.relation.temp.id
        this.requestParam.parammaps.fname = this.relation.temp.fname
        this.requestParam.parammaps.feedcode = this.relation.temp.feedcode
        this.requestParam.parammaps.price = row.price
        this.requestParam.parammaps.remark = row.remark
        this.requestParam.parammaps.dry = row.dry
        this.requestParam.parammaps.starch = row.starch
        this.requestParam.parammaps.cp = row.cp
        this.requestParam.parammaps.ca = row.ca
        this.requestParam.parammaps.p = row.p
        this.requestParam.parammaps.n = row.n
        this.requestParam.parammaps.fat = row.fat
        this.requestParam.parammaps.adf = row.adf
        this.requestParam.parammaps.ndf = row.ndf
        this.requestParam.parammaps.ndip = row.ndip
        this.requestParam.parammaps.ash = row.ash
        this.requestParam.parammaps.fpercent = row.fpercent
        this.requestParam.parammaps.iscu = row.iscu
        this.requestParam.parammaps.feednurid = row.id
        PostDataByName(this.requestParam).then(response => {
          console.log('关联保存发送参数', this.requestParam)
          if (response.msg !== 'fail') {
            this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
            this.getRelationList()
            this.getList()
          } else {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消' })
      })
    },
    // 营养价值
    handleNutritive(row) {
      console.log('点击了营养价值', row)
      this.dialogFull = false
      this.nutritive.dialogStatus = 'nutritive'
      this.nutritive.dialogFormVisible = true
      this.nutritive.temp = Object.assign({}, row)
    },
    nutritiveData() {
      console.log('点击了营养价值保存')
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      if (this.nutritive.temp.dry == undefined) { this.$set(this.nutritive.temp, 'dry', '') }
      if (this.nutritive.temp.starch == undefined) { this.$set(this.nutritive.temp, 'starch', '') }
      if (this.nutritive.temp.cp == undefined) { this.$set(this.nutritive.temp, 'cp', '') }
      if (this.nutritive.temp.ca == undefined) { this.$set(this.nutritive.temp, 'ca', '') }
      if (this.nutritive.temp.p == undefined) { this.$set(this.nutritive.temp, 'p', '') }
      if (this.nutritive.temp.n == undefined) { this.$set(this.nutritive.temp, 'n', '') }
      if (this.nutritive.temp.fat == undefined) { this.$set(this.nutritive.temp, 'fat', '') }
      if (this.nutritive.temp.adf == undefined) { this.$set(this.nutritive.temp, 'adf', '') }
      if (this.nutritive.temp.ndf == undefined) { this.$set(this.nutritive.temp, 'ndf', '') }
      if (this.nutritive.temp.ndip == undefined) { this.$set(this.nutritive.temp, 'ndip', '') }
      if (this.nutritive.temp.ash == undefined) { this.$set(this.nutritive.temp, 'ash', '') }
      var positiveNumber = /^\d+(\.\d{1,2})?$/
      if (this.nutritive.temp.dry !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.dry))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }
      console.log(this.nutritive.temp.starch)
      if (this.nutritive.temp.starch !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.starch))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.cp !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.cp))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.ca !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.ca))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.p !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.p))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.n !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.n))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.fat !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.fat))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.adf !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.adf))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.ndf !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.ndf))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.ndip !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.ndip))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }

      if (this.nutritive.temp.ash !== '') {
        if (!positiveNumber.test(parseFloat(this.nutritive.temp.ash))) {
          this.$message({ type: 'error', message: '请输入自然数，最多保留俩位小数', duration: 2000 })
          return false
        }
      }
      this.requestParam.name = 'insertFeednur'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.pastureid = this.nutritive.temp.pastureid
      this.requestParam.parammaps.fid = this.nutritive.temp.id
      this.requestParam.parammaps.fname = this.nutritive.temp.fname
      this.requestParam.parammaps.feedcode = this.nutritive.temp.feedcode
      this.requestParam.parammaps.price = this.nutritive.temp.uprice
      this.requestParam.parammaps.remark = this.nutritive.temp.remark
      this.requestParam.parammaps.dry = this.nutritive.temp.dry
      this.requestParam.parammaps.starch = this.nutritive.temp.starch
      this.requestParam.parammaps.cp = this.nutritive.temp.cp
      this.requestParam.parammaps.ca = this.nutritive.temp.ca
      this.requestParam.parammaps.p = this.nutritive.temp.p
      this.requestParam.parammaps.n = this.nutritive.temp.n
      this.requestParam.parammaps.fat = this.nutritive.temp.fat
      this.requestParam.parammaps.adf = this.nutritive.temp.adf
      this.requestParam.parammaps.ndf = this.nutritive.temp.ndf
      this.requestParam.parammaps.ndip = this.nutritive.temp.ndip
      this.requestParam.parammaps.ash = this.nutritive.temp.ash
      this.requestParam.parammaps.fpercent = this.nutritive.temp.fpercent
      this.requestParam.parammaps.iscu = this.nutritive.temp.iscu
      this.requestParam.parammaps.feednurid = '-1'
      PostDataByName(this.requestParam).then(response => {
        console.log('关联保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getList()
          this.nutritive.dialogFormVisible = false
        } else {
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        }
      })
    },



    handleChangeOrder() {
      this.isOrder = false
      this.rowDrop()
    },

    saveChangeOrder() {
      // 保存顺序
      var sortArr = []
      for (let i = 0; i < this.table.list.length; i++) {
        var obj = {}
        obj.sort = i + 1
        obj.id = this.table.list[i].id
        sortArr.push(obj)
      }
      let url = 'api/v1/ops/forage/sort'
      let data = {
        list:sortArr
      }
      postJson(url,data).then(response => {
        if(response.code == 200){
          this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
          this.getList()
        }
      })
    },
    cancelChangeOrder() {
      // 取消顺序
      this.getList()
      this.isOrder = true
    },

     // 行拖拽
    rowDrop() {
      console.log(document.querySelector('#table .el-table__body-wrapper tbody'))
      const tbody = document.querySelector('#table .el-table__body-wrapper tbody')
      const that = this
      var sortable = Sortable.create(tbody, {
        disabled: that.dropState,
        onChoose({ newIndex, oldIndex }) {
          if (that.dropState == true) {
            sortable.destroy()
          }
        },
        onEnd({ newIndex, oldIndex }) {
          const currRow = that.table.list.splice(oldIndex, 1)[0]
          that.table.list.splice(newIndex, 0, currRow)
          console.log('索引', newIndex)
          console.log('拖动数据', currRow)
          console.log('上', that.table.list[newIndex - 1])
          console.log('下', that.table.list[newIndex + 1])
        }
      })
    },
    handleGetSapCode(){
      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择一条信息', duration: 2000 })
      } else {
        this.dialogFull = false
        this.sapCode.dialogStatus = 'sapCode'
        this.sapCode.dialogFormVisible = true
        this.sapCode.table.getdataListParm.parammaps.MAKTX = this.selectList[0].sapcode
        this.getsapCodeList()
      }
    },
    getsapCodeList(){
      GetDataByName(this.sapCode.table.getdataListParm).then(response => {
        if (response.data.list !== null) {
          this.sapCode.table.list = response.data.list
        } else {
          this.sapCode.table.list = []
        }
         this.$refs.saptable.reloadData(this.sapCode.table.list)
      })
    },
    handleSapCodeSearch(){},
    sapCodeData(){

    },
    handleSapCodeSelectionChange(val){
      this.sapCode.selectList = val
      console.log(this.sapCode.selectList,'this.sapCode.selectList')
    },

  }
}
</script>
<style lang="scss" scoped>
  .search{margin-top:10px;}
  $width:350px;
  $left:325px;
  .selectInput{
    position: relative;
    display: inline-block;
    .Input{width: $width;position: relative;}
    .el-icon-arrow-down{width: 30px;height: 30px;position: absolute;left: $left;top:10px;color:#C0C4CC;}
    .el-icon-arrow-up{width: 30px;height: 30px;position: absolute;left: $left;top:10px;color:#C0C4CC;}
    .selectUl{
      z-index: 111;width: $width;background: #fff;border: 1px solid #E4E7ED;box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);margin: -1px 0 0 0;padding: 6px 0; margin: 0;box-sizing: border-box;position: absolute;
      li{
        list-style: none;font-size: 14px; padding: 0 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #606266; height: 50px; line-height: 50px; box-sizing: border-box; cursor: pointer;
        a{float:left;width: 80px;}
        a:hover{color: rgba(0, 204, 102, 0.71); font-weight: 700;}
      }
    }
  }
 </style>
