<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="getdataListParm.parammaps.pastureName" placeholder="牧场" class="filter-item" style="width: 110px">
        <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <el-select v-model="getdataListParm.parammaps.inpastureId" clearable placeholder="调入牧场" class="filter-item" style="width: 110px">
        <el-option v-for="item in findAllPastureIn" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="getdataListParm.parammaps.DBCode" placeholder="调拨单号" clearable style="width: 180px;" class="filter-item" />
      <el-input v-model="getdataListParm.parammaps.eqname" placeholder="调拨设备名称" clearable style="width: 180px;" class="filter-item" />
      <el-input v-model="getdataListParm.parammaps.assetCode" placeholder="资产编号" clearable style="width: 180px;" class="filter-item" />
      <el-date-picker ref="inputDatetime" v-model="getdataListParm.parammaps.inputDatetime" class="inputDatetime" type="datetimerange" style="width: 250px;top:-3px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <div>
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
    >
      <el-table-column label="序号" align="center" type="index" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨单号" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.DBCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调出牧场" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.outPastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调入牧场" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.inPastureName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨设备" min-width="90px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.eqName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资产编号" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.assetCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨人" min-width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.empName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨日期" sortable prop="transferDate" min-width="80px" align="center" />
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="form_see(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="90%">
      <div class="app-add">
        <el-form ref="createTemp" :rules="rules" :model="createTemp" label-position="right" label-width="115px" style="width: 90%;margin:0 auto 30px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="调拨单号：" prop="DBCode">
                <el-input ref="DBCode" v-model="createTemp.DBCode" placeholder="请输入调拨单号" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="调出牧场：" prop="outPasture">
                <el-select v-if="dialogStatus==='create'" v-model="createTemp.outPasture" placeholder="调出牧场" class="filter-item" style="width:100%" disabled>
                  <el-option v-for="item in findAllPasture" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-input v-if="dialogStatus==='see'" ref="outPastureName" v-model="createTemp.outPastureName" placeholder="请输入调出牧场" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="调入牧场：" prop="inPasture">
                <el-select v-model="createTemp.inPasture" placeholder="调入牧场" class="filter-item" style="width:100%" :disabled="dialogStatus==='see'" @change="changePastureIn">
                  <el-option v-for="item in findAllPastureIn" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="调入部门：" prop="deptInId">
                <el-select v-if="dialogStatus==='create'" v-model="createTemp.deptInId" placeholder="调入部门" class="filter-item" style="width:100%" :disabled="dialogStatus==='see'" @change="changeDeptIn">
                  <el-option v-for="item in findAllDepartIn" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-input v-if="dialogStatus==='see'" ref="indept" v-model="createTemp.indept" placeholder="请输入调出牧场" disabled />

              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资产编号：" prop="assetCode">
                <el-autocomplete ref="assetCode" v-model="createTemp.assetCode" value-key="assetCode" class="inline-input" :fetch-suggestions="assetNumberSearch" placeholder="请输入内容" :disabled="dialogStatus==='see'" style="width:100%;" @select="handleAssetNumberSelect" @blur="blurAssetNumber">
                  <template slot-scope="{ item }">
                    <span class="addr">{{ item.assetCode }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备名称：" prop="eqName">
                <el-autocomplete ref="eqName" v-model="createTemp.eqName" value-key="eqName" class="inline-input" :fetch-suggestions="formNameSearch" placeholder="请输入内容" :disabled="dialogStatus==='see'" style="width:100%;" @select="handleformNameSelect" @blur="blurFormName">
                  <template slot-scope="{ item }">
                    <div class="name" style="display: inline;">{{ item.eqName }}</div>
                    <span class="addr">{{ item.eqCode }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备内部编号：" prop="eqCode">
                <el-autocomplete ref="eqCode" v-model="createTemp.eqCode" value-key="eqCode" class="inline-input" :fetch-suggestions="formNumberSearch" placeholder="请输入内容" :disabled="dialogStatus==='see'" style="width:100%;" @select="handleformNumberSelect" @blur="blurFormNumber">
                  <template slot-scope="{ item }">
                    <div class="name" style="display: inline;">{{ item.eqName }}</div>
                    <span class="addr">{{ item.eqCode }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="调出部门：" prop="outdept">
                <el-input ref="outdept" v-model="createTemp.outdept" placeholder="请输入调出部门" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格：" prop="specification">
                <el-input ref="specification" v-model="createTemp.specification" placeholder="请输入规格" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="品牌：" prop="brand">
                <el-input ref="brand" v-model="createTemp.brand" placeholder="请输入品牌" style="width:100%" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="调拨人：" prop="empName">
                <el-select v-model="createTemp.empName" placeholder="调出人" class="filter-item" style="width:100%" :disabled="dialogStatus==='see'">
                  <el-option v-for="item in findAllEmploye" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="调拨日期：" prop="transferDate">
                <el-date-picker v-model="createTemp.transferDate" :picker-options="pickerOptions" type="date" placeholder="调拨日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%" :disabled="dialogStatus==='see'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="备注：" prop="note">
                <el-input ref="note" v-model="createTemp.note" placeholder="请输入备注" style="width:100%" :disabled="dialogStatus==='see'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:5px">
          <el-button v-if="dialogStatus==='create'" type="primary" :disabled="isokDisable" @click="dialogStatus==='create'?add_dialog_save():add_dialog_save()">保存并关闭</el-button>
          <el-button @click="dialogFormVisible = false; getdataListParm.parammaps.inputDatetime = ''">取消并关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入
// eslint-disable-next-line no-unused-vars
import { GetDataByName, GetDataByNames, ExecDataByConfig, PostDataByName } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils/index.js'
// eslint-disable-next-line no-unused-vars
import { validateEMail } from '@/utils/validate.js'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// eslint-disable-next-line no-unused-vars
import { parse } from 'querystring'
import Cookies from 'js-cookie'
export default {
  name: 'EquipmentAllocation',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      findAllProvider: [],
      findAllAssetType: [],
      findAllPasture: [],
      findAllDepart: [],
      findAllEmploye: [],
      findAllPastureIn: [], // 调入牧场
      requestParams: [
        { name: 'findAllProvider', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllAssetType', offset: 0, pagecount: 0, params: [] },
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }},
        { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'findAllEmploye', offset: 0, pagecount: 0, parammaps: { 'pastureId': Cookies.get('pastureid') }},
        { name: 'getPastureList', offset: 0, pagecount: 0, parammaps: {}}
      ],
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      rules: {
        outPasture: [{ required: true, message: '必填', trigger: 'blur' }],
        inPasture: [{ required: true, message: '必填', trigger: 'blur' }],
        deptInId: [{ required: true, message: '必填', trigger: 'blur' }],
        assetCode: [{ required: true, message: '必填', trigger: 'blur' }],
        eqName: [{ required: true, message: '必填', trigger: 'blur' }],
        eqCode: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      getdataListParm: {
        name: 'geteqTransferList',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureName: Cookies.get('pasturename'),
          inputDatetime: '',
          startTime: '',
          stopTime: '',
          inpastureId: '',
          DBCode: '',
          eqname: '',
          assetCode: ''
        }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '新增',
        see: '查看设备信息'
      },
      requestFilterParams: {
        name: 'geteqbyNameCode',
        page: 0,
        offset: 0,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      createTemp: {
        DBCode: '',
        outPasture: this.$store.state.user.pastureid,
        inPasture: '',
        indept: '',
        assetCode: '',
        eqName: '',
        eqCode: '',
        outdept: '',
        specification: '',
        brand: '',
        empName: Cookies.get('employename'),
        transferDate: parseTime(new Date(), '{y}-{m}-{d}'),
        note: ''
      },
      isokDisable: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()// 当天之前的时间可选
        }
      },
      getParmCreateNumber: {
        name: 'autoCreatCode',
        returntype: 'Map',
        parammaps: {
          pastureId: Cookies.get('pastureid'),
          codeType: 'DB'
        }
      },
      postDataPramas: {},
      findAllDepartIn: [], // 调入部门
      getParmDeptList: { name: 'findAllDepart', offset: 0, pagecount: 0, parammaps: {}}
    }
  },
  created() {
    this.get_select_list()
    this.getList()
  },

  methods: {
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllProvider = response.data.findAllProvider.list
        this.findAllAssetType = response.data.findAllAssetType.list
        this.findAllPasture = response.data.findAllPasture.list
        this.findAllDepart = response.data.findAllDepart.list
        this.findAllEmploye = response.data.findAllEmploye.list
        this.findAllPastureIn = response.data.getPastureList.list
      })
    },
    getList() {
      this.listLoading = true
      if (this.$refs['inputDatetime'] !== undefined && this.$refs['inputDatetime'].value !== null) {
        this.getdataListParm.parammaps.startTime = this.$refs['inputDatetime'].value[0]
        this.getdataListParm.parammaps.stopTime = this.$refs['inputDatetime'].value[1]
      } else {
        this.getdataListParm.parammaps.startTime = ''
        this.getdataListParm.parammaps.stopTime = ''
      }
      GetDataByName(this.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.list = response.data.list
        } else {
          this.list = []
        }
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    form_search() {
      console.log('点击了搜索')
      this.listLoading = true
      if (this.getdataListParm.parammaps.inputDatetime1 === null) {
        this.getdataListParm.parammaps.inputDatetime1 = ''
      }
      this.getdataListParm.offset = 1
      this.getList()
    },
    resetCreateTemp() {
      this.createTemp = {
        DBCode: '',
        outPasture: this.$store.state.user.pastureid,
        inPasture: '',
        indept: '',
        assetCode: '',
        eqName: '',
        eqCode: '',
        outdept: '',
        specification: '',
        brand: '',
        empName: Cookies.get('employename'),
        transferDate: parseTime(new Date(), '{y}-{m}-{d}'),
        note: ''
      }
    },
    form_add() {
      this.resetCreateTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['createTemp'].clearValidate()
      })
      this.getCreateNumber()
    },
    getCreateNumber() {
      GetDataByName(this.getParmCreateNumber).then(response => {
        this.$nextTick(() => {
          console.log('调拨单号', response.data.list[0].orderCode)
          this.createTemp.DBCode = response.data.list[0].orderCode
          this.$forceUpdate()
        })
      })
    },

    changePastureIn(item) {
      console.log(item)
      if (this.findAllDepartIn.find(obj => obj.id === item)) {
        console.log(this.findAllPastureIn.find(obj => obj.id === item).name)
        this.$set(this.createTemp, 'pastureName', this.findAllPastureIn.find(obj => obj.id === item).name)
      }
      this.getParmDeptList.parammaps.pastureId = item
      this.getdeptList()
    },
    getdeptList() {
      GetDataByName(this.getParmDeptList).then(response => {
        this.$nextTick(() => {
          this.findAllDepartIn = response.data.list
        })
      })
    },
    changeDeptIn(item) {
      if (this.findAllDepartIn.find(obj => obj.id === item)) {
        console.log(this.findAllDepartIn.find(obj => obj.id === item).name)
        this.$set(this.createTemp, 'indept', this.findAllDepartIn.find(obj => obj.id === item).name)
      }
    },
    assetNumberSearch(queryString, cb) {
      this.requestFilterParams.parammaps['eqCode'] = queryString
      this.requestFilterParams.parammaps['eqName'] = ''
      this.requestFilterParams.parammaps['assetCode'] = ''
      this.requestFilterParams.parammaps['pastureId'] = this.$store.state.user.pastureid
      GetDataByName(this.requestFilterParams).then(response => {
        cb(response.data.list)
      })
    },
    formNumberSearch(queryString, cb) {
      this.requestFilterParams.parammaps['eqCode'] = queryString
      this.requestFilterParams.parammaps['eqName'] = ''
      this.requestFilterParams.parammaps['assetCode'] = ''
      this.requestFilterParams.parammaps['pastureId'] = this.$store.state.user.pastureid
      GetDataByName(this.requestFilterParams).then(response => {
        cb(response.data.list)
      })
    },
    formNameSearch(queryString, cb) {
      this.requestFilterParams.parammaps['eqCode'] = ''
      this.requestFilterParams.parammaps['eqName'] = queryString
      this.requestFilterParams.parammaps['assetCode'] = ''
      this.requestFilterParams.parammaps['pastureId'] = this.$store.state.user.pastureid
      GetDataByName(this.requestFilterParams).then(response => {
        cb(response.data.list)
      })
    },
    handleAssetNumberSelect(item) {
      console.log(item)
      this.$set(this.createTemp, 'assetCode', item.assetCode)
      this.$set(this.createTemp, 'eqName', item.eqName)
      this.$set(this.createTemp, 'eqCode', item.eqCode)
      this.$set(this.createTemp, 'deptName', item.deptName)
      this.$set(this.createTemp, 'specification', item.specification)
      this.$set(this.createTemp, 'brand', item.brand)
      this.$set(this.createTemp, 'outdept', item.deptName)
      this.$set(this.createTemp, 'eqId', item.eqId)
    },
    handleformNumberSelect(item) {
      console.log(item)
      this.$set(this.createTemp, 'assetCode', item.assetCode)
      this.$set(this.createTemp, 'eqName', item.eqName)
      this.$set(this.createTemp, 'eqCode', item.eqCode)
      this.$set(this.createTemp, 'deptName', item.deptName)
      this.$set(this.createTemp, 'specification', item.specification)
      this.$set(this.createTemp, 'brand', item.brand)
      this.$set(this.createTemp, 'outdept', item.deptName)
      this.$set(this.createTemp, 'eqId', item.eqId)
    },

    handleformNameSelect(item) {
      console.log(item)
      this.$set(this.createTemp, 'assetCode', item.assetCode)
      this.$set(this.createTemp, 'eqName', item.eqName)
      this.$set(this.createTemp, 'eqCode', item.eqCode)
      this.$set(this.createTemp, 'deptName', item.deptName)
      this.$set(this.createTemp, 'specification', item.specification)
      this.$set(this.createTemp, 'brand', item.brand)
      this.$set(this.createTemp, 'outdept', item.deptName)
      this.$set(this.createTemp, 'eqId', item.eqId)
    },
    blurAssetNumber(item) {
      this.$set(this.createTemp, 'assetCode', '')
      this.$set(this.createTemp, 'eqName', '')
      this.$set(this.createTemp, 'eqCode', '')
      this.$set(this.createTemp, 'deptName', '')
      this.$set(this.createTemp, 'specification', '')
      this.$set(this.createTemp, 'brand', '')
      this.$set(this.createTemp, 'outdept', '')
      this.$set(this.createTemp, 'eqId', '')
    },
    blurFormName(item) {
      this.$set(this.createTemp, 'assetCode', '')
      this.$set(this.createTemp, 'eqName', '')
      this.$set(this.createTemp, 'eqCode', '')
      this.$set(this.createTemp, 'deptName', '')
      this.$set(this.createTemp, 'specification', '')
      this.$set(this.createTemp, 'brand', '')
      this.$set(this.createTemp, 'outdept', '')
      this.$set(this.createTemp, 'eqId', '')
    },
    blurFormNumber(item) {
      this.$set(this.createTemp, 'assetCode', '')
      this.$set(this.createTemp, 'eqName', '')
      this.$set(this.createTemp, 'eqCode', '')
      this.$set(this.createTemp, 'deptName', '')
      this.$set(this.createTemp, 'specification', '')
      this.$set(this.createTemp, 'brand', '')
      this.$set(this.createTemp, 'outdept', '')
      this.$set(this.createTemp, 'eqId', '')
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          console.log(this.createTemp)
          if (this.createTemp.DBCode == '' || this.createTemp.DBCode == null || this.createTemp.DBCode == undefined) {
            GetDataByName(this.getParmCreateNumber).then(response => {
              this.$nextTick(() => {
                console.log('调拨单号', response.data.list[0].orderCode)
                this.createTemp.DBCode = response.data.list[0].orderCode
                this.$forceUpdate()
                this.add_dialog_saveSave()
              })
            })
          } else {
            this.add_dialog_saveSave()
          }
        }
      })
    },
    add_dialog_saveSave() {
      this.postDataPramas.common = { 'returnmap': '0' }
      this.postDataPramas.data = []
      this.postDataPramas.data[0] = { 'name': 'inserteqTransfer', 'type': 'e', 'parammaps': {
        eqName: this.createTemp.eqName,
        eqCode: this.createTemp.eqCode,
        eqId: this.createTemp.eqId,
        brand: this.createTemp.brand,
        assetCode: this.createTemp.assetCode,
        DBCode: this.createTemp.DBCode,
        outPasture: this.createTemp.outPasture,
        inPasture: this.createTemp.inPasture,
        empName: this.createTemp.empName,
        transferDate: this.createTemp.transferDate,
        outdept: this.createTemp.outdept,
        indept: this.createTemp.indept,
        note: this.createTemp.note
      }}
      this.postDataPramas.data[1] = { 'name': 'updateEqTransfer', 'type': 'e', 'parammaps': {
        eqId: this.createTemp.eqId
      }}
      this.postDataPramas.data[2] = { 'name': 'createNewEq', 'type': 'e', 'parammaps': {
        eqId: this.createTemp.eqId,
        pastureId: this.createTemp.inPasture,
        deptInId: this.createTemp.deptInId,
        pastureName: this.createTemp.pastureName,
        departmentName: this.createTemp.indept
      }}

      ExecDataByConfig(this.postDataPramas).then(response => {
        console.log('新增保存发送参数', this.postDataPramas)
        if (response.msg === 'fail') {
          this.$notify({
            title: '保存失败',
            message: response.data,
            type: 'warning',
            duration: 2000
          })
        } else {
          this.getdataListParm.parammaps.inputDatetime = ''
          this.getList()
          this.dialogFormVisible = false
          this.createTemp.providerName = ''
          this.$notify({
            title: '',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    form_see(row) {
      // this.resetCreateTemp()
      this.createTemp.eqCode = ''
      console.log('点击了查看', row)
      this.createTemp = Object.assign({}, row)
      this.dialogStatus = 'see'
      this.dialogFormVisible = true
    }

  }
}
</script>
