 <template>
  <div class="app-container">
    <div class="operation">


      <el-button v-if="isRoleEdit" class="success" icon="el-icon-plus" style="float: left;" @click="handleCreate1">设置推料时间</el-button>
      <el-button v-if="isRoleEdit" class="success" icon="el-icon-plus" style="float: left;" @click="handleCreate2">设置允许误差时间</el-button>


     <el-button v-if="isRoleEdit" class="success" icon="el-icon-open" style="float: left;" @click="handleTakeEffect">启用</el-button>
      <el-button v-if="isRoleEdit" class="danger" icon="el-icon-turn-off" style="float: left;" @click="handleDisable">禁用</el-button>
      <el-button v-if="isRoleEdit" class="success" style="float: left;" @click="handleCheck">校验</el-button>

      <el-button class="import" style="float: right;" @click="handleHistoryRecords">历史记录</el-button>

    </div>

    <div class="table">
      <el-table
        :key="table.tableKey"
        ref="table"
        v-loading="table.listLoading"
        element-loading-text="给我一点时间"
        :data="table.list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable table-fixed"
        @header-click="headerClick"
        @cell-click="cellClick"
        @selection-change="handleSelect"
        @cell-dblclick="celldblclick"
        :max-height="myHeight"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column :key="1" label="序号" align="center" type="index" width="50px" class-name="small-padding fixed-width" fixed="left" />
        <el-table-column label="栏舍名称" min-width="100px" align="center" class-name="small-padding fixed-width" fixed="left">
          <template slot-scope="scope">

            <span  >{{ scope.row.bname }}</span>

          </template>
        </el-table-column>
        <el-table-column :key="2" label="推料车名称" min-width="70px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.tmrname }}</span>
            <el-select v-if="scope.row.Edit" v-model="scope.row.tmrid" filterable placeholder="推料车名称" class="filter-item" style="width:95%;padding:10px 0;" @change="changeTmrCode(scope.$index, scope.row, $event)">
                  <el-option v-for="item in tmrCodeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :key="3" label="推料车编号" min-width="90px" align="center">
          <template slot-scope="scope">
            <span  >{{ scope.row.tmrcode }}</span>

          </template>
        </el-table-column>
        <el-table-column :key="4" label="推料时间(每天)" min-width="85px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.times }}</span>

            <el-tag v-if="scope.row.Edit" v-for="tag  in  scope.row.timesArr" :key="tag" closable @close="tag_close(scope.$index, scope.row, tag)" type="success">{{tag}}</el-tag>


                   <el-time-picker v-if="scope.row.Edit"
                     v-model="scope.row.times"
                    :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                     value-format="HH:mm"
                     @change="change_time(scope.$index, scope.row, $event)" format="HH:mm"
                    placeholder="任意时间点">
                  </el-time-picker>


          </template>
        </el-table-column>
        <el-table-column :key="5" label="允许误差时间(分钟)" min-width="85px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.allowableerror }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.allowableerror" type="number" style="width:95%;padding:10px 0;"   />
          </template>
        </el-table-column>


        <el-table-column label="是否启用" min-width="90px" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.enable" :disabled="scope.row.NoEdit==true" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"  />
              </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="row.isUpdate && isRoleEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
            <el-button v-if="row.isUpdateSave && isRoleEdit" :disabled="isokDisable" icon="el-icon-folder-checked" class="miniSuccess" @click="updateData(row)" />
            <span v-if="row.isUpdateSave && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isUpdateSave && isRoleEdit" class="minCancel" icon="el-icon-close" @click="updateCancel(row)" />

            <!-- <el-button v-if="isRoleEdit" class="miniDanger" icon="el-icon-delete" @click="handleRowDelete(row)" /> -->

          </template>
        </el-table-column>
      </el-table>
      <span v-if="table.listLoading == false" style="margin-right: 30px;margin-top: 10px;font-size: 14px;">共{{ table.total }}条</span>
      <!-- <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="getList" /> -->
    </div>



     <el-dialog :fullscreen="dialogFull" :visible.sync="create1.dialogFormVisible" :close-on-click-modal="false" width="50%">
      <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" />
            推料计划
          </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="create1.rules" :model="create1.temp" label-position="right" label-width="155px" style="width: 100%;margin:0 auto 50px">

          <el-row>
              <el-col :span="6">
                <el-form-item label="设置时间：" prop="useinbarid">
                   <el-time-picker
                    v-model="timevalue1"
                    :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
                     value-format="HH:mm"
                     @change="change_time1" format="HH:mm"
                    placeholder="任意时间点">
                  </el-time-picker>
                </el-form-item>
              </el-col>

          </el-row>
           <el-row>
               <el-tag v-for="tag in timetags1" :key="tag.name" closable @close="tag_close1(tag)" type="success">{{tag}}</el-tag>

            </el-row>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create1.dialogFormVisible = false;getList()">关闭</el-button>
          <el-button class="save"  @click="create_sure1">确认</el-button>
        </div>
      </div>
    </el-dialog>


    <el-dialog :fullscreen="dialogFull" :visible.sync="create2.dialogFormVisible" :close-on-click-modal="false" width="50%">
      <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" />
            允许误差时间
          </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="create2.rules" :model="create2.temp" label-position="right" label-width="155px" style="width: 100%;margin:0 auto 50px">

          <el-row>
              <el-col :span="12">
              <el-form-item label="允许误差时间(分钟)：" prop="allowableerror">
                <el-input ref="time" v-model="create2.temp.allowableerror" class="filter-item" placeholder="请输入" type="text" />
              </el-form-item>
            </el-col>

          </el-row>



        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create2.dialogFormVisible = false;getList()">关闭</el-button>
          <el-button class="save"  @click="create_sure2">确认</el-button>
        </div>
      </div>
    </el-dialog>


   <!-- 校验 -->
    <el-dialog title="提示" :destroy-on-close="true" :visible.sync="check.dialogFormVisible" :close-on-click-modal="false" width="30%">
      <div class="check">
        <p v-if="check.temp.isDistribution1 == '0'">未启用分配如下：</p>
        <p v-else>当前栏舍已分配完</p>
        {{ check.temp.banme1 }}


        <p v-if="check.temp.isDistribution2 == '0'">未启用栏舍如下：</p>
        <p v-else>当前栏舍已全部启用</p>
        {{ check.temp.banme2 }}
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="save" @click="check.dialogFormVisible=false;">确认</el-button>
      </div>
    </el-dialog>


        <!-- 历史记录 -->
    <el-dialog :fullscreen="dialogFull" :destroy-on-close="true" :visible.sync="history.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" />
             历史记录
          </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-history">
        <div class="search">
          <el-date-picker v-model="history.getdataListParm.parammaps.changeTime" type="date" placeholder="请选择历史记录时间" :clearable="false" style="width: 180px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @change="changeDate" />
          <!-- <el-button class="successBorder" @click="handleApplication">应用</el-button> -->
        </div>
        <div class="table">
          <el-table
            :key="history.tableKey"
            v-loading="history.listLoading"
            element-loading-text="给我一点时间"
            :data="history.list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
          >

            <el-table-column label="栏舍名称" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.barname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="推料车名称" prop="weight" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.tmrname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="推料车编号" prop="weight" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.tmrcode }}</span>
              </template>
            </el-table-column>


            <el-table-column label="推料时间（每天）" min-width="130px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.tisms }}</span>
              </template>
            </el-table-column>
            <el-table-column label="误差时间（分钟）" min-width="180px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.allowableerror }}</span>
              </template>
            </el-table-column>

          </el-table>
          <pagination v-show="history.total>0" :total="history.total" :page.sync="history.getdataListParm.offset" :limit.sync="history.getdataListParm.pagecount" @pagination="getHistoryList" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelClose cancelClose1" @click="history.dialogFormVisible = false; ">关闭</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { GetDataByName, postJson, GetDataByNames, compareSort, ExecDataByConfig, failproccess, PostDataByName, formatNum, checkButtons, checkDates } from '@/api/common'
import Pagination from '@/components/Pagination'
import Pagination2 from '@/components/Pagination2'
import { parseTime, json2excel, handleTableSpan, handleObjectSpanMethod } from '@/utils/index.js'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import axios from 'axios'
import { getToken } from '@/utils/auth'

export default {
  inject: ['reload'],
  name: 'PushMaterialPlan',
  components: { Pagination, Pagination2 },
  data() {
    return {


      history: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {},
        rules: {},
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,

        getdataDateParm: {
          name: 'getPushingHistoryDate',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid')
          }
        },
        getdataListParm: {
          name: 'getPushingHistory',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            changeTime: ''
          }
        }
      },

      tmrCodeList:[
        // {Code: "001", id: 46, name: "一号推料车"},
        //  {Code: "002", id: 47, name: "二号推料车"}
      ],
      table: {
        getdataListParm: {
          name: 'getPushingList',
          page: 1,
          offset: 1,

          pagecount: '',
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),

          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {},


      },


      create1: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: { pastureid: Cookies.get('pastureid'), fname: ''},
        rules: {
          // fname: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          // fclassid: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          // feedcode: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
        }
      },

      create2: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: { pastureid: Cookies.get('pastureid'), allowableerror: ''},
        rules: {
          // fname: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          // fclassid: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          // feedcode: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
        }
      },

      check: {
        dialogFormVisible: false,
        dialogStatus: '',
        getCheckParm: {
          name: 'checkRemainplan',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid')
          }
        },
        temp: {
          bnames: '',
          isDistribution1: '',
          isDistribution2: ''
        }
      },





      timevalue1: new Date(2022, 9, 10, 18, 40),
      timetags1: [],




      dialogFull: false,
      isRoleEdit: [],
      headerList: [],
      pickerMinDate: '',


      rules: {
        cowclassid: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
      },

      selectList: [],




      requestParam: {},
      download: {
        getdataListParm: {
          name: 'getFPList',
          page: 1,
          offset: 1,
          pagecount: 0,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            enable: ''
          }
        },
        list: []
      },
      spanObj: {},
      mergekeys: ['barname', 'sumweight'],
      isShowDialog: false,
      isokDisable: false,
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      myHeight: document.documentElement.clientHeight - 85- 150,
      oldRowList:{},






    }
  },
  computed: {


  },
  created() {
    this.getButtons()

    this.getTMRlist()
    this.getList()

  },

  methods: {
    getButtons() {
      const Edit = 'DhedFormula'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },

    getTMRlist() {

      var send_data = {"name":"getPushingTmrList","page":1,"offset":1,"pagecount":"","returntype":"Map","parammaps":{"dictname":"推料车"}}
      GetDataByName(send_data).then(response => {
        if (response.data.list !== null) {
          this.tmrCodeList = response.data.list
        } else {
          this.tmrCodeList = []
        }
        console.log("tmrCodeList",this.tmrCodeList)
      })
    },


    getList() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          for (let i = 0; i < response.data.list.length; i++) {
            this.$set(response.data.list[i], 'Edit', false) // 编辑
            this.$set(response.data.list[i], 'NoEdit', true) // 不可编辑/输入
            this.$set(response.data.list[i], 'isUpdate', true) // 编辑操作
            this.$set(response.data.list[i], 'isUpdateSave', false) // 编辑保存

          }

          response.data.list.forEach(function(item){
            if(item.times !== ""){
              item.timesArr = item.times.split(',')
            }else{
              item.timesArr = []
            }
          })

          // console.log(response.data.list, sumr)

          this.table.list = response.data.list
          console.log(this.table.list, 'this.table.list')
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
        } else {
          this.table.list = []
        }
        this.table.total = response.data.total
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },


    // 推料车
    changeTmrCode(index,row,item) {
      console.log("推料车:====",index,row,item)
      var Code   = this.tmrCodeList.find(obj => obj.id === row.tmrid).Code
      var itemName   = this.tmrCodeList.find(obj => obj.id === row.tmrid).name
      console.log( "推料车编号:====",Code , itemName)
      this.table.list[index].tmrcode = Code
      this.table.list[index].tmrname = itemName

    },




     // 新增
    handleCreate1() {
      console.log('点击了新增')

      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择推料信息', duration: 2000 })
      } else {
        this.resetTemp1()
        this.dialogFull = false
        this.create1.dialogStatus = 'create'
        this.create1.dialogFormVisible = true
      }


    },
     resetTemp1() {
      this.timetags1 = []
    },


    create_sure1(){
        console.log('timetags1-----',this.timetags1)
        console.log('selectList-----',this.selectList)

            var timeArrRea = this.timetags1

            var selectArr = this.selectList
           var idsArr = []
      selectArr.forEach(function(item){
              idsArr.push(item.id)
      })

            var timeIdArr = []


            selectArr.forEach(function(item){
              timeArrRea.forEach(function(items){
                timeIdArr.push({"time":items,"tmrname":item.tmrname,"tmrid":item.tmrid,"id":item.id})
              })
            })


            console.log("timeIdArr",timeIdArr)



            var send_data = {
              "common":{"returnmap":"0"},
              "data":[
										 {
                       "name":"checkPushing",
                       "resultmaps":{
                         "list":timeIdArr
                        },
										 "children":[
                       {
                         "name":"checkPushing","type":"e","parammaps": {"tmrname":"@checkPushing.tmrname","tmrid":"@checkPushing.tmrid","id":"@checkPushing.id","time":"@checkPushing.time","type":0}
                         }
                         ]
                         }
              ]}




            var send_data2 = {
              "common":{"returnmap":"0"},
              "data":[
                {"name":"insertPushingHistory","type":"e","parammaps":{"ids":idsArr.join(","),"pastureid":Cookies.get('pastureid')}},
                {
                  "name":"delPushingDetailByIds",
                  "type":"e",
                  "parammaps":{"ids":idsArr.join(",")}
                },
								{
                  "name":"insertPushingDetail",
                  "resultmaps":{
                    "list":timeIdArr
                  },
										 "children":[{"name":"insertPushingDetailByPushingId","type":"e","parammaps":
										 {"pastureid":Cookies.get('pastureid'),"id":"@insertPushingDetail.id","time":"@insertPushingDetail.time","type":0}}]}
										 ]}



      checkDates(send_data).then(response => {
        console.log(response)
          if (response.data === true) {
               ExecDataByConfig(send_data2).then(response => {
                  console.log('设置推料', send_data2)
                  console.log('设置推料', response)
                  if (response.msg === 'fail') {
                    this.$notify({ title: '设置失败', message: response.data, type: 'warning', duration: 2000 })
                  } else {

                    this.$notify({ title: '设置成功', message: '设置成功', type: 'success', duration: 2000 })
                    this.create1.dialogFormVisible = false
                    this.getList()

                  }
                })
          } else {
             this.$notify({ title: '设置失败', message: response.data, type: 'warning', duration: 2000 })

          }
        })



    },

    handleCreate2() {


      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择推料信息', duration: 2000 })
      } else {
        console.log('点击了新增')
        this.resetTemp2()
        this.dialogFull = false
        this.create2.dialogStatus = 'create'
        this.create2.dialogFormVisible = true
      }
    },
     resetTemp2() {
      this.create2.temp = { pastureid: Cookies.get('pastureid'),  'allowableerror': '' }
    },


    create_sure2(){
      console.log(this.selectList)
      var allowableerror = this.create2.temp.allowableerror

      var selectArr = this.selectList
      var idsArr = []
      selectArr.forEach(function(item){
              idsArr.push(item.id)
      })

      var send_data = {"name":"updateAllowableerrorByIds","parammaps":{"allowableerror":allowableerror,"ids":idsArr.join(",")}}

      PostDataByName(send_data).then(response => {
        if (response.msg === 'fail') {
                this.$notify({ title: '设置失败', message: response.data, type: 'warning', duration: 2000 })
              } else {

                this.$notify({ title: '设置成功', message: '设置成功', type: 'success', duration: 2000 })
                this.create2.dialogFormVisible = false
                this.getList()

              }
      })
    },








    change_time1(tag){
      console.log("tag", tag)
        console.log("timetags1", this.timetags1)

     this.timetags1.push(tag)

    },




    tag_close1(tag){
        console.log("tag", tag)
        console.log("timetags1", this.timetags1)


        this.timetags1.splice(this.timetags1.indexOf(tag), 1);
    },



    change_time(index,row,item){
        console.log("item", index,row,item)

        this.table.list[index].timesArr.push(item)


    },
    tag_close(index,row,tag){
        console.log("tag", index,row,tag)
        this.table.list[index].timesArr.splice(this.table.list[index].timesArr.indexOf(tag), 1);

    },



    // 校验
    handleCheck() {
      console.log('点击了校验')
      this.check.dialogStatus = 'check'
      this.check.dialogFormVisible = true
      this.getCheckList()
    },
    getCheckList() {
      var check_data = {"name":"checkPushingBar","offset":0,"pagecount":0,"parammaps":{"pastureid":Cookies.get('pastureid')}}

      GetDataByName(check_data).then(response => {
        console.log(response)
        if (response.data.list[0].banme1 !== undefined) {
          this.check.temp.isDistribution1 = 0
          this.check.temp.banme1 = response.data.list[0].banme1
        } else {
          this.check.temp.isDistribution1 = 1
        }

        if (response.data.list[0].banme2 !== undefined) {
          this.check.temp.isDistribution2 = 0
          this.check.temp.banme2 = response.data.list[0].banme2
        } else {
          this.check.temp.isDistribution2 = 1
        }
      })
    },

    handleTakeEffect() {

      console.log(this.selectList)
      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择推料信息', duration: 2000 })
      } else {
        MessageBox.confirm('当前选中' + this.selectList.length + '条信息，是否生效?', {
          confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
        }).then(() => {


          var selectArr = this.selectList
          var idsArr = []

          selectArr.forEach(function(item){
            idsArr.push(item.id)
          })

          var send_data =  {
            "name":"updateEnableByIds",
            "parammaps":{"enable":"1","ids":idsArr.join(",")}
          }
          GetDataByName(send_data).then(response => {


             if (response.msg == 'fail') {
              this.$notify({ title: '生效失败', message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.$notify({ title: '', message: '生效成功', type: 'success', duration: 2000 })
              this.getList()
            }

          })

        })
      }
    },
    handleDisable() {
      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择推料信息', duration: 2000 })
      } else {
        MessageBox.confirm('当前选中' + this.selectList.length + '条信息，是否禁用?', {
          confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
        }).then(() => {
          var selectArr = this.selectList
          var idsArr = []

          selectArr.forEach(function(item){
            idsArr.push(item.id)
          })

          var send_data =  {
            "name":"updateEnableByIds",
            "parammaps":{"enable":"0","ids":idsArr.join(",")}
          }
          GetDataByName(send_data).then(response => {


             if (response.msg == 'fail') {
              this.$notify({ title: '禁用失败', message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.$notify({ title: '', message: '禁用成功', type: 'success', duration: 2000 })
              this.getList()
            }

          })
        })
      }
    },






    renderHeader(h, { column, $index }) { // h即为cerateElement的简写，具体可看vue官方文档
      return h(
        'div',
        [
          h('span', column.label),
          h('i', {
            class: 'el-icon-unlock',
            ref: 'el-icon-unlock',
            style: 'margin-left:5px;'
          })
        ]
      )
    },

    headerClick(column, event) {
      console.log(column, event)
      this.headerList.push(event)
      for (let i = 0; i < this.table.list.length; i++) {
          if (this.table.list[i].Edit == true) {
            if (event.target.outerHTML == '<i class="el-icon-unlock" style="margin-left: 5px;"></i>') {
              event.target.className = 'el-icon-lock'
              this.$set(this.table.list[i], 'isTwoWeight', true) // 锁住不可编辑
            } else if (event.target.outerHTML == '<i class="el-icon-lock" style="margin-left: 5px;"></i>') {
              event.target.className = 'el-icon-unlock'
              this.$set(this.table.list[i], 'isTwoWeight', false) // 解锁可编辑
            }
          }
        }
    },






    celldblclick(row, column, cell, event) {
      console.log(row, '=====')
      this.handleUpdate(row)
    },
    // 编辑
    handleUpdate(row) {
      console.log(row)
      this.oldRowList = {...row}
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      // 编辑true,不可编辑false
      row.Edit = true
      row.NoEdit = false
      // 编辑false,编辑保存true
      row.isUpdate = false
      row.isUpdateSave = true

    },
    updateData(row) {


      console.log('点击了编辑保存', row)

       row.pastureid =  Cookies.get('pastureid')


      if (row.tmrid === '' || row.tmrid == null ) {
        this.$message({ type: 'error', message: '推料车名称不能为空', duration: 2000 })
        return false
      }

     const positiveInteger = /^[0-9]\d*$/
      if (!positiveInteger.test(parseFloat(row.allowableerror))) {
        this.$message({
          type: 'error',
          message: '允许误差数请输入0-60正整数',
          duration: 2000
        })
        return false
      } else if(parseFloat(row.allowableerror) > 60){
        this.$message({
          type: 'error',
          message: '允许误差数请输入0-60正整数',
          duration: 2000
        })
        return false
      }






      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)


      var timeArrRea = row.timesArr
      var timesTempArr = []
      timeArrRea.forEach(function(item){
        timesTempArr.push({"time":item})
      })

      var send_data = {
        "common":{"returnmap":"0"},
        "data":[
          {
            "name":"checkPushing","resultmaps":{"list":timesTempArr},
						"children":[
              {
                "name":"checkPushing","type":"v",
                "parammaps": {
                  "tmrname":row.tmrname,
                  "tmrid":row.tmrid,
                  "id":row.id,
                  "time":"@checkPushing.time",
                  "type":0
                }
              }
            ]
          }
        ]
      }



      if(row.id == 0){
         var send_data2 =  {
           "common":{"returnmap":"0"},
           "data":[
              {"name":"insertPushing","type":"e",
               "parammaps": row
              },
							{"name":"insertPushingDetail",
              "resultmaps":{
                "list":timesTempArr
              },
							"children":[
                {
                  "name":"insertPushingDetail","type":"e","parammaps":
										 {
                       "pastureid":Cookies.get('pastureid'),
                       "barid":row.barid,"time":"@insertPushingDetail.time","type":0}}]}
										 ]}
      }else {

        var send_data2 = {
          "common":{"returnmap":"0"},
          "data":[
            {"name":"insertPushingHistory","type":"e","parammaps":{"ids":row.id,"pastureid":Cookies.get('pastureid')}},
            {"name":"updatePushing","type":"e",
            "parammaps":row
            },
						{"name": "delPushingDetail","type": "e",
            "parammaps": {"id": row.id }
            },
						{"name":"insertPushingDetail",
            "resultmaps":{"list":timesTempArr},
						"children":[
              {"name":"insertPushingDetail","type":"e",
              "parammaps":
										 {"pastureid":Cookies.get('pastureid'),
                       "barid":row.barid,"time":"@insertPushingDetail.time","type":0}}]}
					]}

      }


      checkDates(send_data).then(response => {
        console.log(response)
          if (response.data === true) {
              ExecDataByConfig(send_data2).then(response => {
                console.log('编辑保存发送参数', send_data2)
                console.log('编辑保存', response)
                if (response.msg === 'fail') {
                  this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
                } else {

                  this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })

                  this.getList()

                }
              })
          } else {
             this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })

          }
        })



    },
    updateCancel(row) {
      console.log('点击了编辑取消')
      // 编辑false,不可编辑true
      row.Edit = false
      row.NoEdit = true
      // 编辑true,编辑保存false
      row.isUpdate = true
      row.isUpdateSave = false
      // this.reload()
      for (let i = 0; i < this.headerList.length; i++) {
        if (this.headerList[i].target.className == 'el-icon-lock') {
          this.headerList[i].target.className = 'el-icon-unlock'
          this.$set(this.headerList[i].target, 'className', 'el-icon-unlock')
        }
      }
      console.log(this.table.getdataListParm.offset)
      this.table.getdataListParm.offset = this.table.getdataListParm.offset
      this.getList()
      // this.$router.push('/formulationPlan/dhedFormula')
    },
    cellClick(row, column, event) {
      console.log(column)
    },
    handleSelect(val) {
      console.log('勾选数据', val)
      this.selectList = val
    },

    tableRowClassName({ row }) {
      // console.log(row)
      if (row.isColor == '0') {
        return 'red-row'
      } else {
        return ''
      }
    },






    // 历史记录
    handleHistoryRecords() {
      console.log('点击了历史记录')
      this.dialogFull = false
      this.history.dialogStatus = 'history'
      this.history.dialogFormVisible = true
      this.getDateList()
    },
    // 历史时间
    getDateList() {
      GetDataByName(this.history.getdataDateParm).then(response => {
        console.log('table数据', response)
        if (response.data.list !== null) {
          this.history.getdataListParm.parammaps.changeTime = response.data.list[0].changeTime
          this.getHistoryList()
        } else {
          this.history.getdataListParm.parammaps.changeTime = ''
        }
      })
    },
    changeDate() {
      this.getHistoryList()
    },

    getHistoryList() {
      this.history.listLoading = true
      GetDataByName(this.history.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          console.log('table数据', response.data.list)
          this.history.list = response.data.list
          this.history.pageNum = response.data.pageNum
          this.history.pageSize = response.data.pageSize
        } else {
          this.history.list = []
        }
        this.history.total = response.data.total
        setTimeout(() => {
          this.history.listLoading = false
        }, 100)
      })
    },


    // 应用
    handleApplication() {
      console.log('点击了应用')
      MessageBox.confirm('是否确认将' + this.history.getdataListParm.parammaps.date + '的数据应用到当前?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.requestParam.name = 'applyFPdate'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.pastureid = Cookies.get('pastureid')
        this.requestParam.parammaps.date = this.history.getdataListParm.parammaps.date
        PostDataByName(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })

            this.getList()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消应用' })
      })
    },


    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },

    blurBw(row) {
      console.log(row)
    },
    focusBw(row) {
      console.log(row)
    }
  }
}
</script>
<style lang="scss" scoped>
  .search {
    clear: both;
  }

  .table {
    margin-top: 10px;
  }
  .el-tag{margin-right: 5px;}
</style>
<style lang="scss">
  .red-row{
    background: #fde2e2 !important;
  }
</style>
