<template>
  <div class="app-container">
    <div class="search">
      <el-input v-model="table.parammaps.name" placeholder="请输入牧场名称" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.parammaps.manager_user" placeholder="请输入负责人姓名" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.parammaps.manager_phone" placeholder="请输入手机号" style="width: 180px;" class="filter-item" clearable />
      <el-date-picker v-model="table.parammaps.inputDatetime" :clearable="false" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px;margin-right: 10px;" />
      <el-select v-model="table.parammaps.is_show" 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>
      <el-button class="successBorder" @click="handleSearch">查询</el-button>
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isAdd" icon="el-icon-plus" class="success" @click="handleCreate">添加牧场</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 type="selection" align="center" width="50" />
        <el-table-column label="序号" min-width="130px" align="center" prop="id" />
        <el-table-column label="牧场名称" min-width="100px" align="center" prop="name" />
        <el-table-column label="登录账号" min-width="100px" align="center" prop="account" />
        <el-table-column label="负责人姓名" min-width="100px" align="center" prop="manager_user" />
        <el-table-column label="手机号" min-width="100px" align="center" prop="manager_phone" />
        <el-table-column label="牧场地址" min-width="100px" align="center" prop="address" />
        <el-table-column label="添加时间" min-width="100px" align="center" prop="created_at_format" />
        <el-table-column label="状态" min-width="110px" 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>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <a v-if="isResetpassword" class="correcting" size="mini" style="width: 80px;" @click="handleResetPassword(row)">重置密码</a>
            <span v-if="isEdit" class="centerSpan">|</span>
            <a v-if="isEdit" class="correcting" @click="handleUpdate(row)">编辑</a>
            <span v-if="isDelete" class="centerSpan">|</span>
            <a v-if="isDelete" class="correcting" @click="handleRowDelete(row)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.page" :limit.sync="table.page_size" @pagination="getList" />
    </div>
    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[edit.dialogStatus]" :visible.sync="edit.dialogFormVisible" :close-on-click-modal="false"
      width="50%">
      <div class="edit">
        <div class="content">
          <el-form ref="editTemp" :rules="rules" :model="edit.temp" label-position="right" label-width="115px" style="width: 90%;margin:0 auto 30px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="牧场名称:" prop="name">
                  <el-input ref="name" v-model="edit.temp.name" placeholder="请输入牧场名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="登录账号:" prop="account">
                  <el-input ref="account" v-model="edit.temp.account" placeholder="请输入登录账号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="初始密码" prop="username">
                  <span>123456</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="负责人姓名:" prop="manager_user">
                  <el-input ref="manager_user" v-model="edit.temp.manager_user" placeholder="请输入负责人姓名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="手机号:" prop="manager_phone">
                  <el-input ref="manager_phone" v-model="edit.temp.manager_phone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="牧场地址:" prop="address">
                  <el-input ref="address" v-model="edit.temp.address" placeholder="请输入牧场地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom: 40px;">
          <el-button class="cancelClose cancelClose" @click="edit.dialogFormVisible = false;getList(); ">关闭</el-button>
          <el-button class="save" :disabled="isokDisable"
            @click="edit.dialogStatus == 'add' ? createData():updateData()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postJson,getJson,delJson,checkButtons } from '@/api/common'
import Cookies from 'js-cookie'
import { MessageBox } from 'element-ui'
import { validatePhone } from '@/utils/validate'
import Pagination from '@/components/Pagination'
export default {
  name: 'PastureList',
  components: { Pagination },
  data() {
    return {
      enableList: JSON.parse(sessionStorage.downlist).is_show,
      table: {
        page: 1,
        page_size: parseInt(Cookies.get('pageCount')),
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        parammaps: {
          name: '',manager_user:'',manager_phone:'',is_show:'',inputDatetime:[],end_time:'',start_time:''
        }
      },
      edit: {
        dialogStatus: '',
        dialogFormVisible: false,
        temp: {
          name:'',
          account:'',
          username:'',
          manager_user:'',
          manager_phone:'',
          address:''
        }
      },
      rules: {
        name: [{
          required: true,
          message: '必填',
          trigger: 'blur'
        }],
        account: [{
          required: true,
          message: '必填',
          trigger: 'blur'
        }],
        manager_user: [{
          required: true,
          message: '必填',
          trigger: 'blur'
        }],
        manager_phone: [{ validator: validatePhone,required: true, trigger: 'blur' }],
        address: [{
          required: true,
          message: '必填',
          trigger: 'blur'
        }],
      },
      create:{
        dialogStatus:'',
        dialogFormVisible: false,
        temp:{},
        rules:{}
      },
      isokDisable: false,
      textMap: {
        add: '添加牧场',
        update:'编辑牧场'
      },
      isAdd:'',isEdit:'',isResetpassword:'',isDelete:'',isEnable:'',
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' }

    }
  },

  created() {
    this.getButton()
    this.getList()
  },
  methods: {
    getButton(){
      const add = 'rangeManagement:pastureList:add'
      this.isAdd = checkButtons(add)
      const edit = 'rangeManagement:pastureList:edit'
      this.isEdit = checkButtons(edit)
      const resetpassword = 'rangeManagement:pastureList:resetpassword'
      this.isResetpassword = checkButtons(resetpassword)
      const del = 'rangeManagement:pastureList:delete'
      this.isDelete = checkButtons(del)
      const enable = 'rangeManagement:pastureList:enable'
      this.isEnable = checkButtons(enable)
    },
    getList(){
      this.table.listLoading = true
      let page = this.table.page
      let page_size = this.table.page_size
      let url = 'api/v1/ops/pasture/list' + '?page=' + page + '&page_size=' + page_size
      let data = {
        "name":this.table.parammaps.name,
        "manager_user":this.table.parammaps.manager_user,
        "manager_phone":this.table.parammaps.manager_phone
      }
      if(this.table.parammaps.is_show !== ''){
        data.is_show = this.table.parammaps.is_show
      }
      if(this.table.parammaps.inputDatetime !== null && this.table.parammaps.inputDatetime.length > 0){
        data.created_start_time = this.table.parammaps.inputDatetime[0].getTime() / 1000
        data.created_end_time = this.table.parammaps.inputDatetime[1].getTime()  / 1000 + 86400
      }
      postJson(url, data).then(response => {
        if (response.code == 200) {
          this.table.list = response.data.list
          this.table.total = response.data.total
          this.table.pageNum = response.data.page
          this.table.pageSize = response.data.page_size
        } else {
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 1000)
      })
    },

    handleSearch() {
      this.table.page = 1
      this.getList()
    },
    handleRefresh() {
      this.table.parammaps.name = ''
      this.table.parammaps.manager_user = ''
      this.table.parammaps.manager_phone = ''
      this.table.parammaps.is_show = ''
      this.table.parammaps.inputDatetime = []
      this.table.parammaps.created_start_time = ''
      this.table.parammaps.created_end_time = ''
      this.table.page = 1
      this.getList()
    },
    handleEnableChange(index, row) {
      let url = 'api/v1/ops/pasture/is_show'
      let data = {
        "user_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()
        }
      })
    },


    handleCreate(){
      this.edit.dialogStatus = 'add'
      this.edit.dialogFormVisible = true
      this.edit.temp= {
        name:'',
        account:'',
        username:'',
        manager_user:'',
        manager_phone:'',
        address:''
      }
    },
    createData(){
      this.$refs['editTemp'].validate((valid) => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          let url = 'api/v1/ops/pasture/add'
          let data = {
            'name': this.edit.temp.name,
            "account": this.edit.temp.account,
            "manager_user": this.edit.temp.manager_user,
            "manager_phone": this.edit.temp.manager_phone,
            "address": this.edit.temp.address,
            "is_show": this.edit.temp.is_show,
            // "create_user": Cookies.get('username')
          }
          console.log(data)
          postJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.edit.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    handleUpdate(row) {
      console.log('点击了编辑')
      this.edit.dialogStatus = 'update'
      this.edit.dialogFormVisible = true
      this.edit.temp = Object.assign({},row)
    },
    updateData() {
      this.$refs['editTemp'].validate((valid) => {
        if (valid) {
          this.isokDisable = true
          setTimeout(() => {
            this.isokDisable = false
          }, 1000)
          let url = 'api/v1/ops/pasture/edit'
          let data = {
            "id":this.edit.temp.id,
            'name': this.edit.temp.name,
            "manager_user": this.edit.temp.manager_user,
            "address": this.edit.temp.address,
            "manager_phone": this.edit.temp.manager_phone,
            "account": this.edit.temp.account
          }
          postJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.edit.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    handleRowDelete(row){
      MessageBox.confirm('确定删除吗?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        let url = 'api/v1/ops/pasture/'
        // let data = 10011
        let data = row.id
        delJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      })
    },
    handleResetPassword(row) {
      MessageBox.confirm('是否确认将此牧场密码重置为默认密码123456？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'api/v1/ops/pasture/rest_password/' + row.id
        let data = {}
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      })
    },
  }
}
</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>
