<template>
  <div class="pasture">
    <div class="rect rect-form">
      <el-form
        :inline="true"
        :model="dataForm"
        size="mini">
        <el-form-item style="width: 500px">
          <el-input
            v-model="dataForm.key"
            placeholder="请输入名称/地址/负责人/建立日期"
            clearable style="width: 500px">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            icon="el-icon-search" 
            @click="getDataList()">
            查 询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="rect rect-table">
      <el-form
        :inline="true"
        :model="dataForm"
        size="mini">
        <el-form-item>
          <el-button 
            type="primary" 
            icon="el-icon-plus" 
            @click="addOrUpdateHandle()">
            新 增
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-delete" 
            type="danger" 
            @click="deleteHandle()" 
            :disabled="selectionDataList.length <= 0">
            删 除
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        height="540"
        border
        stripe
        :data="dataList"
        @selection-change="selectionChangeHandle"
        v-loading="dataListLoading"
        style="width: 100%"
        :header-cell-style="{background:'rgb(245,245,245)',color:'#000',height: '45px',fontSize: '13px',fontWeight: 'normal',borderBottom: '1px solid #ccc'}" 
        :cell-style="{color: '#888',fontSize: '13px'}"
        size="mini">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <el-table-column
          prop="name"
          header-align="left"
          align="left"
          label="名称">
        </el-table-column>
        <el-table-column
          prop="frontLocation"
          header-align="left"
          align="left"
          label="地址">
          <template slot-scope="scope">
            {{ scope.row.frontLocation? scope.row.frontLocation.split(',').join(''): '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="manager"
          header-align="center"
          align="center"
          label="负责人"
          width="150">
        </el-table-column>
        <el-table-column
          prop="buildTime"
          header-align="center"
          align="center"
          :show-overflow-tooltip="true"
          label="建立日期"
          width="150">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage">
        </el-pagination>
      </div>
      <el-dialog
        :title="!form.id ? '新增' : '修改'"
        :close-on-click-modal="false"
        :visible.sync="visible"
        @close="cancel"
        width="600px">
        <el-form 
          :model="form" 
          :rules="dataRule" 
          ref="form" 
          @keyup.enter.native="formSubmit()" 
          label-width="80px"
          size="mini"
          style="margin-left: 20px;width: 500px">
          <el-form-item label="牧场名称" prop="name">
            <el-input v-model="form.name" placeholder="牧场名称"></el-input>
          </el-form-item>
          <!-- FIXME: 管理员下拉 -->
          <el-form-item label="管理员" prop="manager">
            <el-input v-model="form.manager" placeholder="牧场管理员"></el-input>
          </el-form-item>
          <el-form-item label="省市区" prop="selectedOptions">
            <el-cascader
              :options="options"
              v-model="form.selectedOptions"
              @change="getlocation" 
              placeholder="请选择省市区"
              style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="具体地址" prop="location2">
            <el-input v-model="form.location2" placeholder="地址"></el-input>
          </el-form-item>
          <el-form-item label="建立日期" prop="buildTime">
            <el-date-picker
              v-model="form.buildTime"
              type="date" 
              value-format="yyyy-MM-dd" 
              placeholder="选择建立日期"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="cancel">关闭</el-button>
          <el-button size="mini" type="primary" @click="formSubmit()">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { regionData, CodeToText } from "element-china-area-data"
export default {
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [
        {
          buildTime: '',
          id: '',
          location: '',
          manager: '',
          name: '',
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: '',
        location1: '',
        location2: '',
        manager: '',
        name: '',
        buildTime: '',
        selectedOptions: [],
        loc: ''
      },
      options: regionData,
      selectedOptions: [],
      loc: '',
      dataRule: { // 校验规则
        name: [
          { required: true, message: '牧场名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符之间', trigger: ['blur', 'change'] },
          { type: 'string' , message: '只允许输入中英文、数字、-与_', pattern: /[\w\u4E00-\u9FA5\-]+$/g }
        ],
        manager: [
          { required: true, message: '管理员不能为空', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符之间', trigger: ['blur', 'change'] },
          { type: 'string' , message: '只允许输入中英文、数字、-与_', pattern: /[\w\u4E00-\u9FA5\-]+$/g }
        ],
        selectedOptions: [
          { required: true, message: '省市区不能为空', trigger: 'blur' }
        ],
        location2: [
          { required: true, message: '具体地址不能为空', trigger: 'blur' },
          { type : 'string' , message: '只允许输入中英文、数字、_、！与!的输入', pattern: /[\w\u4E00-\u9FA5\!\！]+$/g }
        ],
        buildTime: [
          { required: true, message: '日期不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  activated () {
    this.getDataList()
  },
  methods: {
    // 变色
    tableRowClassName({row, rowIndex}) {
      console.log(row);
      if (rowIndex%2 === 0) {
        return 'warning-row';
      }
      return '';
    },
    comLocation(location) {
      let arr = location.split(",")
      let loc = ''
      if (arr.length === 1) {
        return location
      }
      for (let i = 0; i < arr.length - 1; i++) {
        loc += CodeToText[arr[i]]
      }
      loc += arr[arr.length - 1]
      return loc
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/management/farm/list'),
        method: 'post',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          keyword: this.dataForm.key
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
          this.$message.error(data.msg)
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 获取地址
    getlocation () {
      var loc = "";
      this.form.location1 = ''
      for (let i = 0; i < this.form.selectedOptions.length; i++) {
        loc += CodeToText[this.form.selectedOptions[i]]
        this.form.location1 += this.form.selectedOptions[i] + ','
      }
      this.loc = loc
      console.log(loc);
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 新增 or 修改牧场
    addOrUpdateHandle (row) {
      // 显示牧场新增 or 修改面板
      this.visible = true
      if (row) {
        let location = row.location
        let arr = location.split(",")
        this.form.selectedOptions = []
        if (arr.length === 1) {
          return
        }
        this.form.location1 = ''
        for (let i = 0; i < arr.length - 1; i++) {
          this.form.selectedOptions.push(arr[i])
          this.form.location1 += arr[i] + ','
        }
        this.form.buildTime = row.buildTime
        this.form.id = row.id
        this.form.manager = row.manager
        this.form.name = row.name 
        this.form.location2 = arr[arr.length - 1]
      }
    },
    // 选择n个牧场
    selectionChangeHandle (val) {
      this.selectionDataList = val
      // val.forEach(item => {
      //   this.selectionDataList.push(item.id)
      // });
    },
    // 删除n个牧场
    deleteHandle (pasture) {
      let ids = pasture? [pasture.id]: this.selectionDataList.map(item => item.id)
      let names = pasture? [pasture.name]: this.selectionDataList.map(item => item.name)
      console.log(names);
      this.$confirm(`确定${pasture ? '删除' : '批量删除'}${names.join()}牧场？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除操作
        if (this.selectionDataList.length < 0) {
          return
        }
        this.$http({
          url: this.$http.adornUrl('/management/farm/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(result => {
          if (result.data.code === 0) {
            this.$message({
              message: '成功删除牧场',
              type: 'success',
              duration: 1000
            })
            // pageIndex修正
            this.totalPage -= this.selectionDataList.length
            let pages = Math.ceil(this.totalPage / this.pageSize)
            this.pageIndex = this.pageIndex > pages? pages: this.pageIndex
            this.pageIndex = this.pageIndex < 1? pages: this.pageIndex
          } else {
            this.$confirm(result.data.msg, '删除失败', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              console.log('牧场删除失败');
            }).catch(() => {})
          }
          this.resetForm()
          this.selectionDataList = []
        })
      }).catch(() => {})
    },
    formSubmit () {
      if (this.form.id) {
        /** 修改 */
        // 输入是否完整
        if (!this.confirmComplete()) {
          return
        }
        // 输入长度是否合法
        if (!this.confirmLength()) {
          return
        }
        // 输入是否合法
        if (!this.confirmInput()) {
          return
        }
        // 进行修改操作
        this.$http({
          url: this.$http.adornUrl('/management/farm/update'),
          method: 'post',
          data: this.$http.adornData({
            id: this.form.id,
            location: this.form.location,
            manager: this.form.manager,
            name: this.form.name,
            buildTime: this.form.buildTime,
            frontLocation: this.form.loc
          })
        }).then(result => {
          if (result.data.code === 0) {
            this.resetForm();
            this.visible = false;
            this.$message({
              message: '成功修改牧场信息',
              type: 'success',
              duration: 1000
            })
          } else {
            if (result.data.code === 600) {
              let msg = result.data.msg.split('-')
              this.$message({
                message: `牧场名称 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
                type: "error",
                duration: 1000,
                dangerouslyUseHTMLString: true
              })
              return
            }
            this.$message.error(result.data.msg);
          }
        })
      } else {
        /** 新增 */
        // 输入是否完整
        if (!this.confirmComplete(1)) {
          return
        }
        // 输入长度是否合法
        if (!this.confirmLength()) {
          return
        }
        // 输入是否合法
        if (!this.confirmInput()) {
          return
        }
        // 进行新增操作
        this.$http({
          url: this.$http.adornUrl('/management/farm/save'),
          method: 'post',
          data: this.$http.adornData({
            location: this.form.location,
            manager: this.form.manager,
            name: this.form.name,
            buildTime: this.form.buildTime,
            frontLocation: this.form.loc
          })
        }).then(result => {
          if (result.data.code === 0) {
            // 新增pageIndex的修正
            this.totalPage++
            let pages = Math.ceil(this.totalPage / this.pageSize)
            this.pageIndex = this.pageIndex < pages? pages: this.pageIndex
            this.resetForm();
            this.visible = false;
            this.$message({
              message: '成功添加牧场',
              type: 'success',
              duration: 1000
            })
          } else {
            if (result.data.code === 600) {
              let msg = result.data.msg.split('-')
              this.$message({
                message: `牧场名称 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
                type: "error",
                duration: 1000,
                dangerouslyUseHTMLString: true
              })
              return
            }
            this.$message.error(result.data.msg)
          }
        })
      }
    },
    // 清空form
    resetForm () {
      for (let i in this.form) {
        this.form[i] = ''
      }
      this.form.selectedOptions = []
      this.getDataList()
    },
    // 取消
    cancel () {
      this.visible = false
      // 如果新增，则不保留form
      if (this.form.id) {
        this.resetForm()
      }
    },
    // 校验输入是否完整
    validComplete (val) {
      // var loc = "";
      // this.form.location1 = ''
      // for (let i = 0; i < this.form.selectedOptions.length; i++) {
      //   loc += CodeToText[this.form.selectedOptions[i]]
      //   this.form.location1 += this.form.selectedOptions[i] + ','
      // }
      // this.loc = loc
      // this.form.location = this.form.location1 + this.form.location2
      // this.form.loc = this.loc + this.form.location2
      // val && (delete this.form.id)
      // for (let i in this.form) {
      //   if (!this.form[i].toString()) {
      //     return false
      //   }
      // }
      // return true

      /** 给地址加上, */
      var loc = [];
      this.form.location1 = ''
      for (let i = 0; i < this.form.selectedOptions.length; i++) {
        loc.push(CodeToText[this.form.selectedOptions[i]])
        this.form.location1 += this.form.selectedOptions[i] + ','
      }
      this.loc = loc
      this.form.location = this.form.location1 + this.form.location2
      this.form.loc = loc.join(',') + ',' + this.form.location2
      val && (delete this.form.id)
      for (let i in this.form) {
        if (!this.form[i].toString()) {
          return false
        }
      }
      return true
    },
    // 如不完整，则提示
    confirmComplete (val) {
      if (this.validComplete(val)) {
        return true
      }
      this.$confirm(`所有项均为必填项`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('牧场输入不完整');
      }).catch(() => {})
      return false
    },
    // 校验输入是否合法
    validInput () {
      // 只允许中文、英文、数字、-、_的输入，取反
      const reg = /[^\w\u4E00-\u9FA5\_\-]/g
      if (reg.test(this.form.name)) {
        return 0
      }
      if (reg.test(this.form.manager)) {
        return 1
      }
      // 只允许中文、英文、下划线、！、!的输入
      const a = /[^\w\u4E00-\u9FA5\!\！]/g
      if (a.test(this.form.location2)) {
        return 2
      }
      // 不允许纯数字、字母的出现
      const b = /^[\w]*([a-zA-Z][0-9]|[0-9][a-zA-Z])[\w]*$/
      // 不允许纯符号的出现
      const c = /^[\_\-\!\！]*[\_\-\!\！]*$/
      if (b.test(this.form.name) || b.test(this.form.manager) || b.test(this.form.location2) || c.test(this.form.name) || c.test(this.form.manager) || c.test(this.form.location2)) {
        return 3
      }
      // 建立日期不得大于今日
      let build = new Date(this.form.buildTime)
      let now = new Date()
      if (build > now) {
        console.log('建立日期有误');
        return 4
      }
      return 5
    },
    // 如不合法，则提示
    confirmInput () {
      if (this.validInput() === 5) {
        return true
      }
      let msg = [
        '牧场名称只允许中英文、数字、-、_的输入',
        '管理员只允许中英文、数字、-、_的输入',
        '具体地址只允许中英文、数字、_、！与!的输入',
        '不允许输入纯数字、纯字母或纯符号',
        '建立日期选择有误'
      ]
      this.$confirm(msg[this.validInput()], '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('输入不合法');
      }).catch(() => {})
      return false
    },
    // 长度校验
    validLength () {
      if (this.form.name.length > 50) {
        return false
      }
      if (this.form.manager.length > 5) {
        return false
      }
      return true
    },
    // 如长度不合法，则提示
    confirmLength () {
      if (this.validLength()) {
        return true
      }
      this.$confirm(`牧场名称长度限制50，管理员姓名长度限制5`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('输入不合法');
      }).catch(() => {})
      return false
    }
  }
}
</script>
<style scoped>
.rect {
  background-color: #fff;
  padding: 30px 15px;
  border-radius: 5px;
  border: 1px solid #e8e8e8;
}
.rect-form {
  padding-bottom: 10px;
}
.rect-table {
  margin-top: 20px;
}
.demo-table-expand {
  font-size: 0;
  margin-left: 40px;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
}
.el-table .height {
  background: rgba(254, 254, 254, 0.5);
}
/deep/ .el-table--mini td, .el-table--mini th {
  padding: 3px 0 !important;
  height: 20px !important;
}
/deep/ .el-checkbox__input.is-checked+.el-checkbox__label {
  color: rgb(24,144,255);
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__inner:hover {
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: rgb(24,144,255);
}
/deep/.el-table #select .cell .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
</style>