<template>
  <div class="app-container">
    <div class="operation">
      <el-button class="success" @click="form_add">新增合同</el-button>
      <el-button class="import" style="float: right;" @click="form_inport">导入</el-button>
      <el-dropdown style="float: right;margin-right: 10px;">
        <el-button class="export">导出</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="form_export(1)">导出模板</el-dropdown-item>
          <el-dropdown-item @click.native="form_export(2)">导出数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="search">
      <el-date-picker v-model="table.getdataListParm.parammaps.inputDatetime" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px;" />
      <el-button class="el-icon-arrow-left elIconArrowLeft" @click="handleBefore" />
      <el-button class="el-icon-arrow-right elIconArrowRight" @click="handleNext" />
      <el-select v-model="table.getdataListParm.parammaps.providerid" filterable placeholder="请选择供应商" class="filter-item" style="width: 150px;" clearable>
        <el-option v-for="(item,index) in supplierList" :key="index" :label="item.providerName" :value="item.id" />
      </el-select>
      <el-button class="successBorder" @click="form_search">查询</el-button>
      <el-button class="successBorder" @click="form_clear">重置</el-button>
    </div>

    <div class="table">
      <el-table :key="table.tableKey" 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">
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.contractcode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商" min-width="130px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.providername }}</span>
          </template>
        </el-table-column>
        <el-table-column label="录入日期" min-width="110px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.operatetime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" min-width="110px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" disabled active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button class="miniPrimary" @click="form_see(row)">查看</el-button>
            <el-button class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button class="miniDanger" @click="form_delete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>

    <!-- 新增 -->
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="90%">
      <div class="app-add">
        <el-form ref="createTemp" :rules="create.rules" :model="create.createTemp" label-position="right" label-width="160px" style="width: 90%;margin:0 auto">
          <el-row>
            <el-col :span="8">
              <el-form-item label="合同编号:" prop="contractcode">
                <el-input ref="contractcode" v-model="create.createTemp.contractcode" class="filter-item" placeholder="合同编号" type="text" :disabled="create.dialogStatus !== 'create'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商:" prop="providerid">
                <el-select v-model="create.createTemp.providerid" filterable placeholder="请选择供应商" class="filter-item" style="width: 100%;" :disabled="create.dialogStatus !== 'create'" @change="changeSupplier">
                  <el-option v-for="(item,index) in supplierList" :key="index" :label="item.providerName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="录入日期:" prop="operatetime">
                <el-date-picker v-model="create.createTemp.operatetime" class="filter-item" type="date" placeholder="录入日期" :disabled="create.dialogStatus==='see'" :clearable="false" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="添加饲料:" prop="feedid">
                <el-select v-model="create.createTemp.feedid" filterable placeholder="请选择饲料" class="filter-item" style="width: 100%;" :disabled="create.dialogStatus==='see'" @change="changeFeedNameAdd">
                  <el-option v-for="(item,index) in feedNameAddList" :key="index" :label="item.fname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否启用:" prop="enable">
                <el-switch v-model="create.createTemp.enable" :disabled="create.dialogStatus==='see'" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :key="create.tableKey" v-loading="create.listLoading" element-loading-text="给我一点时间" :data="create.list" border fit highlight-current-row style="width: 100%;margin-bottom: 50px;" :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.feedname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="饲料价格" min-width="130px" align="center">
            <template slot-scope="scope">
              <el-input v-if="create.dialogStatus !=='see'" ref="input" v-model="scope.row.price" type="number" :step="0.01" placeholder="最多两位小数" style="width:80%;padding:10px 0;" />
              <span v-else> {{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="create.dialogStatus !=='see'" label="操作" align="center" width="120" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <a class="smallDanger" @click="handleFeedDelete(row)">删除</a>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false; ">关闭</el-button>
          <el-button v-if="create.dialogStatus !== 'see'" class="success" :disabled="isokDisable" @click="create.dialogStatus==='create'?add_dialog_save():form_edit_save()">确认</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { GetDataByName, GetDataByNames, checkButtons, calculativeWidth, ExecDataByConfig, failproccess } from '@/api/common'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils/index.js'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
export default {
  name: 'FeedContract',
  components: { Pagination },
  data() {
    return {
      isRoleEdit: [],
      send_select_list: [
        { name: 'getProviderListEnable', offset: 0, pagecount: 0, parammaps: { pastureid: Cookies.get('pastureid') } },
        { name: 'getFeedListEnable', offset: 0, pagecount: 0, parammaps: { pastureid: Cookies.get('pastureid') } }
      ],
      supplierList: [], // 供应商
      feedNameAddList: [], // 饲料名称
      table: {
        getdataListParm: {
          name: 'getBigContractList',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            inputDatetime: '',
            startTime: '',
            stopTime: ''
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true
      },
      textMap: {
        create: '新增合同',
        update: '编辑合同',
        see: '查看合同'
      },
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        createTemp: {
          pastureid: Cookies.get('pastureid'), 'providerid': '', 'providername': '', 'emp': Cookies.get('employename'), 'enable': 1, 'operatetime': parseTime(new Date(), '{y}-{m}-{d}')
        },
        rules: {
          contractcode: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          providerid: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
        },
        getdataListParm: {
          name: 'getContractList',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {}
        },
        listLoading: false,
        tableKey: 0,
        list: []
      },
      requestParam: {},
      isokDisable: false,
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },

  created() {
    this.get_auto_buttons()
    this.get_select_list()
    this.get_table_data()
  },

  methods: {
    get_auto_buttons() {
      const Edit = 'FeedContract'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    get_select_list() {
      GetDataByNames(this.send_select_list).then(response => {
        this.supplierList = response.data.getProviderListEnable.list
        this.feedNameAddList = response.data.getFeedListEnable.list
      })
    },
    handleBefore() {
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        var start = new Date(this.table.getdataListParm.parammaps.inputDatetime[0].setDate(this.table.getdataListParm.parammaps.inputDatetime[0].getDate() - 1))
        var stop = new Date(this.table.getdataListParm.parammaps.inputDatetime[1].setDate(this.table.getdataListParm.parammaps.inputDatetime[1].getDate() - 1))
        this.table.getdataListParm.parammaps.inputDatetime.length = 0
        this.table.getdataListParm.parammaps.inputDatetime.push(start, stop)
        this.table.getdataListParm.parammaps.startTime = parseTime(start, '{y}-{m}-{d}')
        this.table.getdataListParm.parammaps.stopTime = parseTime(stop, '{y}-{m}-{d}')
        this.$forceUpdate()
        this.get_table_data()
      }
    },
    handleNext() {
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        var start = new Date(this.table.getdataListParm.parammaps.inputDatetime[0].setDate(this.table.getdataListParm.parammaps.inputDatetime[0].getDate() + 1))
        var stop = new Date(this.table.getdataListParm.parammaps.inputDatetime[1].setDate(this.table.getdataListParm.parammaps.inputDatetime[1].getDate() + 1))
        this.table.getdataListParm.parammaps.inputDatetime.length = 0
        this.table.getdataListParm.parammaps.inputDatetime.push(start, stop)
        this.table.getdataListParm.parammaps.startTime = parseTime(start, '{y}-{m}-{d}')
        this.table.getdataListParm.parammaps.stopTime = parseTime(stop, '{y}-{m}-{d}')
        this.$forceUpdate()
      }
    },
    get_table_data() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        this.table.getdataListParm.parammaps.startTime = parseTime(this.table.getdataListParm.parammaps.inputDatetime[0], '{y}-{m}-{d}')
        this.table.getdataListParm.parammaps.stopTime = parseTime(this.table.getdataListParm.parammaps.inputDatetime[1], '{y}-{m}-{d}')
      } else {
        this.table.getdataListParm.parammaps.inputDatetime = ''
        this.table.getdataListParm.parammaps.startTime = ''
        this.table.getdataListParm.parammaps.stopTime = ''
      }
      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      this.table.getdataListParm.parammaps.inputDatetime = ''
      this.table.getdataListParm.parammaps.startTime = ''
      this.table.getdataListParm.parammaps.stopTime = ''
      this.table.getdataListParm.parammaps.providerid = ''
    },

    resetCreateTemp() {
      this.create.createTemp = {
        pastureid: Cookies.get('pastureid'), 'providerid': '', 'providername': '', 'emp': Cookies.get('employename'), 'enable': 1, 'operatetime': parseTime(new Date(), '{y}-{m}-{d}')
      }
      this.create.list = []
    },
    form_add() {
      console.log('点击了新增')
      this.resetCreateTemp()
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
    },
    // 供应商
    changeSupplier(item) {
      this.create.createTemp.providername = this.supplierList.find(obj => obj.id == item).providerName
    },
    // 新增饲料
    changeFeedNameAdd(item) {
      var obj = {}
      obj.feedid = item
      obj.feedname = this.feedNameAddList.find(obj => obj.id == item).fname
      obj.pastureid = this.feedNameAddList.find(obj => obj.id == item).pastureid
      obj.price = ''
      obj.myId = (new Date()).valueOf()
      for (let i = 0; i < this.create.list.length; i++) {
        if (this.create.list[i].feedid == item) {
          this.$message({ type: 'warning', message: '添加饲料不可重复', duration: 2000 })
          return false
        }
      }
      this.create.list.push(obj)
    },
    handleFeedDelete(row) {
      for (let i = 0; i < this.create.list.length; i++) {
        console.log(this.create.list[i])
        if (this.create.list[i].myId === row.myId) {
          var listAddIndex = this.create.list.indexOf(this.create.list[i])
        }
        if (listAddIndex > -1) {
          this.create.list.splice(listAddIndex, 1)
          return
        }
      }
    },

    add_dialog_save() {
      console.log('点击了新增保存')
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          console.log(this.create.list.length)
          if (this.create.list.length == 0) {
            this.$message({ type: 'warning', message: '请添加饲料', duration: 2000 })
            return false
          }
          const rulesPrice = /^\d+(\.\d{1,2})?$/
          for (let i = 0; i < this.create.list.length; i++) {
            if (this.create.list[i].price == '') {
              this.$message({ type: 'warning', message: '饲料价格不可为空', duration: 2000 })
              return false
            }
            if (!rulesPrice.test(parseFloat(this.create.list[i].price))) {
              this.$message({ type: 'warning', message: '饲料价格最多保留两位小数', duration: 2000 })
              return false
            }
          }
          this.create.createTemp.operatetime = parseTime(this.create.createTemp.operatetime, '{y}-{m}-{d}')
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          this.requestParam.data[0] = {            'name': 'insertBigContract', 'type': 'e', 'parammaps': {
              'pastureid': this.create.createTemp.pastureid,
              'contractcode': this.create.createTemp.contractcode,
              'providerid': this.create.createTemp.providerid,
              'providername': this.create.createTemp.providername,
              'emp': this.create.createTemp.emp,
              'enable': this.create.createTemp.enable,
              'operatetime': this.create.createTemp.operatetime
            }          }
          this.requestParam.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.create.list } }
          this.requestParam.data[1].children = []
          this.requestParam.data[1].children[0] = {            'name': 'insertContract', 'type': 'e', 'parammaps': {
              pastureid: '@insertSpotList.pastureid',
              bigid: '@insertBigContract.LastInsertId',
              feedid: '@insertSpotList.feedid',
              feedname: '@insertSpotList.feedname',
              price: '@insertSpotList.price'
            }          }
          ExecDataByConfig(this.requestParam).then(response => {
            if (response.msg === 'fail') {
              failproccess(response, this.$notify)
            } else {
              this.$notify({ title: '', message: '成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.get_table_data()
            }
          })
        }
      })
    },
    form_edit(row) {
      console.log('点击了编辑')
      this.create.dialogStatus = 'update'
      this.create.dialogFormVisible = true
      this.create.createTemp = Object.assign({}, row)
      this.create.getdataListParm.parammaps.pastureid = row.pastureid
      this.create.getdataListParm.parammaps.id = row.id
      this.getSeeList()
    },
    form_edit_save() {
      console.log('点击了编辑保存')
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          console.log(this.create.list.length)
          if (this.create.list.length == 0) {
            this.$message({ type: 'warning', message: '请添加饲料', duration: 2000 })
            return false
          }
          const rulesPrice = /^\d+(\.\d{1,2})?$/
          for (let i = 0; i < this.create.list.length; i++) {
            if (this.create.list[i].price == '') {
              this.$message({ type: 'warning', message: '饲料价格不可为空', duration: 2000 })
              return false
            }
            if (!rulesPrice.test(parseFloat(this.create.list[i].price))) {
              this.$message({ type: 'warning', message: '饲料价格最多保留两位小数', duration: 2000 })
              return false
            }
          }
          this.create.createTemp.operatetime = parseTime(this.create.createTemp.operatetime, '{y}-{m}-{d}')
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          this.requestParam.data[0] = {            'name': 'updateBigContract', 'type': 'e', 'parammaps': {
              'pastureid': this.create.createTemp.pastureid,
              'id': this.create.createTemp.id,
              'operatetime': this.create.createTemp.operatetime,
              'enable': this.create.createTemp.enable
            }          }
          this.requestParam.data[1] = {            'name': 'deleteContract', 'type': 'e', 'parammaps': {
              'pastureid': this.create.createTemp.pastureid,
              'id': this.create.createTemp.id
            }          }
          this.requestParam.data[2] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.create.list } }
          this.requestParam.data[2].children = []
          this.requestParam.data[2].children[0] = {            'name': 'insertContract', 'type': 'e', 'parammaps': {
              pastureid: '@insertSpotList.pastureid',
              bigid: this.create.createTemp.id,
              feedid: '@insertSpotList.feedid',
              feedname: '@insertSpotList.feedname',
              price: '@insertSpotList.price'
            }          }
          ExecDataByConfig(this.requestParam).then(response => {
            if (response.msg === 'fail') {
              failproccess(response, this.$notify)
            } else {
              this.$notify({ title: '', message: '成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.get_table_data()
            }
          })
        }
      })
    },
    form_see(row) {
      console.log('点击了查看')
      this.create.dialogStatus = 'see'
      this.create.dialogFormVisible = true
      this.create.createTemp = Object.assign({}, row)
      this.create.getdataListParm.parammaps.pastureid = row.pastureid
      this.create.getdataListParm.parammaps.id = row.id
      this.getSeeList()
    },
    getSeeList() {
      this.create.listLoading = true
      GetDataByName(this.create.getdataListParm).then(response => {
        console.log('查看table数据', response.data.list)
        if (response.data.list !== null) {
          this.create.list = response.data.list
        } else {
          this.create.list = []
        }
        setTimeout(() => {
          this.create.listLoading = false
        }, 100)
      })
    },

    form_delete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        console.log('点击了删除')
        this.requestParam.common = { 'returnmap': '0' }
        this.requestParam.data = []
        this.requestParam.data[0] = {          'name': 'deleteBigContract', 'type': 'e', 'parammaps': {
            'pastureid': row.pastureid,
            'id': row.id
          }        }
        this.requestParam.data[1] = {          'name': 'deleteContract', 'type': 'e', 'parammaps': {
            'pastureid': row.pastureid,
            'id': row.id
          }        }
        ExecDataByConfig(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            failproccess(response, this.$notify)
          } else {
            this.$notify({ title: '', message: '成功', type: 'success', duration: 2000 })
            this.get_table_data()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    form_inport() {
      console.log('点击了导入')
    },
    // 导出
    form_export(item) {
      if (item == 1) {
        console.log('点击了导出模板')
      } else {
        console.log('点击了导出数据')
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.search {
  margin-top: 10px;
}
.table {
  margin-top: 10px;
}
</style>
<style>
.inputDatetime .el-range-separator {
  padding: 0;
  margin: 0 10px;
}
</style>
