<template>
  <div>
    <new-table :height="600" :title="title" :listData="farmList" :tableItems="tableItems" :shows="tableShows" @selectionChange="selectionChange">
      <template #right>
        <el-button  size="mini" type="primary" v-if="hasPerm('farmAdmin:add')" style="margin-right: 10px" @click="addFarm">添加牧场</el-button>
        <el-button size="mini" type="danger" v-if="hasPerm('farmAdmin:del')" style="margin-right: 10px" @click="delAll">批量删除</el-button>
      </template>
      <template #handler="scope">
        <el-button type="primary" size="mini" style="margin-right: 10px" @click="edit(scope.row)" v-if="hasPerm('farmAdmin:edit')">编辑</el-button>
        <el-popconfirm
            title="是否删除这个牧场"
            @confirm="del(scope.row)"
        >
          <el-button size="mini" slot="reference" v-if="hasPerm('farmAdmin:del')" type="danger">删除</el-button>
        </el-popconfirm>
      </template>
    </new-table>
    <el-dialog
        :title=" showType ? '编辑牧场' : '新增牧场'"
        :visible.sync="dialogVisible"
        width="30%">
        <div>
          <el-form :rules="rules" ref="ruleForm" size="mini" :model="form" label-width="80px">
            <el-form-item label="牧场名称" prop="farmName">
              <el-input v-model="form.farmName"></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>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="reset">取 消</el-button>
          <el-button type="primary" @click="onSubmit('ruleForm')">确 定</el-button>
         </span>
    </el-dialog>
  </div>
</template>

<script>
import { regionData, CodeToText } from "element-china-area-data"
import { addFarm, editFarm, delFarm } from '@/utils/api.js';
import NewTable from "@/components/newTable/NewTable";
import { mapState, mapActions } from 'vuex';
export default {
  name: "FarmAdmin",
  components: {
    NewTable
  },
  computed: {
    ...mapState(['farmList'])
  },
  data() {
    return {
      title: '牧场列表',
      options: regionData,
      tableItems: [
        {
          prop: 'farmName',
          label: '牧场名称',
          minWidth: '100',
          slotName: 'farmName'
        },
        {
          prop: 'frontLocation',
          label: '牧场地址',
          minWidth: '100',
          slotName: 'frontLocation'
        },
        {
          label: '操作',
          minWidth: '100',
          slotName: 'handler'
        }
      ],
      tableShows: {
        showIndex: true,
        showSelect: true,
      },
      showType: false,
      dialogVisible: false,
      form: {
        farmName: '',
        selectedOptions: ''
      },
      rules: {
        farmName: [{  required: true, message: '请输入牧场名称', trigger: 'blur' }],
        selectedOptions: [{  required: true, message: '请输入牧场名称', trigger: 'change' }],
      },
      select: [],
    }
  },
  methods: {
    ...mapActions(['GetFarm']),
    init() {
      this.GetFarm();
    },
    addFarm() {
      this.dialogVisible = true;
      this.showType = false;
    },
    edit(row) {
      this.dialogVisible = true;
      this.showType = true;
      this.form.farmName = row.farmName;
      this.form.id = row.id;
      this.form.selectedOptions = row.location.split(',')
    },
    // 批量选择
    selectionChange(data) {
      this.select = [];
      if(data.length > 0) {
        data.forEach(item => {
          this.select.push(item.id)
        })
      } else {
        this.select = []
      }
    },
    delAll() {
      if(this.select.length > 0) {
        let str = this.select.toString();
        let params = {
          ids: str
        }
        this.$confirm('此操作将永久删除这些牧场, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(111);
          delFarm(params).then(res => {
            if(res.code === 10000) {
              this.$message.success('删除成功!');
              this.init();
              this.select = [];
            } else {
              this.$message.error('删除失败!');
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$message.error('请先选择要删除的牧场');
      }
    },
    del(row) {
      let params = {
        ids: row.id
      }
      delFarm(params).then(res => {
        if(res.code === 10000) {
          this.$message.success('删除成功')
          this.init()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 确认
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.showType) {
            let params = {
              id: this.form.id,
              farmName: this.form.farmName,
              location: this.form.selectedOptions.join(','),
              frontLocation: this.loc
            }
            editFarm(params).then(res => {
              this.reset();
              if(res.code === 10000) {
                this.init();
                this.$message.success('编辑成功！')
              } else {
                this.$message.error('编辑失败');
              }
            })
          } else {
            let params = {
              farmName: this.form.farmName,
              location: this.form.selectedOptions.join(','),
              frontLocation: this.loc
            }
            addFarm(params).then(res => {
              this.reset();
              if(res.code === 10000) {
                this.init();
                this.$message.success('添加成功！')
              } else {
                this.$message.error('添加失败');
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置
    reset() {
      this.dialogVisible = false;
      this.showType = false;
      this.form = {
        farmName: '',
        selectedOptions: ''
      }
      this.loc = ''
    },
    // 获取地址
    getlocation () {
      var loc = [];
      for (let i = 0; i < this.form.selectedOptions.length; i++) {
        loc.push(CodeToText[this.form.selectedOptions[i]])
      }
      this.loc = loc.join(',')
    },
  },
  mounted() {
    // this.init()
  }
}
</script>

<style scoped>

</style>
