<template>
  <div class="app-container sub-area-container">
    <div class="sub-area-list">
      <el-alert type="info" :closable="false" :title="`当前运营区：${area.name}`" show-icon style="margin-bottom: 10px;" v-loading="loadingArea"/>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="区域名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入区域名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable @change="handleQuery">
            <el-option
              v-for="dict in dict.type.area_sub_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
            <el-option
              v-for="dict in dict.type.area_sub_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-has-permi="['bst:areaSub:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-has-permi="['bst:areaSub:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-has-permi="['bst:areaSub:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" size="mini" :data="areaSubList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <template v-for="column of showColumns">
          <el-table-column
              :key="column.key"
              :label="column.label"
              :prop="column.key"
              :align="column.align"
              :min-width="column.minWidth"
              :sort-orders="orderSorts"
              :sortable="column.sortable"
              :show-overflow-tooltip="column.overflow"
              :width="column.width"
          >
            <template slot-scope="d">
              <template v-if="column.key === 'id'">
                {{d.row[column.key]}}
              </template>
              <template v-else-if="column.key === 'name'">
                {{d.row.name | dv}}
                <dict-tag :options="dict.type.area_sub_type" :value="d.row.type" size="mini"/>
                <dict-tag :options="dict.type.area_sub_status" :value="d.row.status" size="mini" style="margin-left: 4px;"/>
              </template>
              <template v-else-if="column.key === 'error'">
                {{d.row.error | dv}} 米 
              </template>
              <template v-else-if="column.key === 'picture'">
                <image-preview :src="d.row.picture" :width="40" :height="40"/>
              </template>
              <template v-else>
                {{d.row[column.key]}}
              </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-has-permi="['bst:areaSub:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-has-permi="['bst:areaSub:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="map-container" v-if="area.id != null">
      <area-map :area="area" :area-sub-list="areaSubList"/>
    </div>
    

    <!-- 添加或修改子区域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
        <el-row>
          <form-col :span="span"  label="区域名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入区域名称" />
          </form-col>
          <form-col :span="span"  label="类型" prop="type">
            <el-radio-group v-model="form.type" placeholder="请选择类型">
              <el-radio
                v-for="dict in dict.type.area_sub_type"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </form-col>
          <form-col :span="span"  label="还车误差" prop="error">
            <el-input v-model="form.error" placeholder="请输入还车误差">
              <template slot="append">米</template>
            </el-input>
          </form-col>
          <form-col :span="span"  label="照片" prop="picture">
            <image-upload v-model="form.picture"/>
          </form-col>
          <form-col :span="span"  label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </form-col>
          <form-col :span="span"  label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.area_sub_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </form-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listByAreaId, getAreaSub, delAreaSub, addAreaSub, updateAreaSub } from "@/api/bst/areaSub";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import { getArea } from '@/api/bst/area';
import { SubAreaStatus, SubAreaType } from '@/utils/enums';
import AreaMap from '@/views/bst/areaSub/components/AreaMap.vue';

  // 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "AreaSub",
  mixins: [$showColumns],
  dicts: ['area_sub_type', 'area_sub_status'],
  components: {FormCol, AreaMap},
  data() {
    return {
      SubAreaStatus,
      SubAreaType,
      span: 24,
      listSpan: 10,
      // 字段列表
      columns: [
        {key: 'id', visible: false, label: 'ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: "60"},
        {key: 'name', visible: true, label: '名称', minWidth: null, sortable: true, overflow: false, align: 'left', width: null},
        // {key: 'type', visible: true, label: '类型', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        // {key: 'status', visible: true, label: '状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'error', visible: true, label: '误差', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'picture', visible: true, label: '照片', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'remark', visible: true, label: '备注', minWidth: null, sortable: true, overflow: true, align: 'center', width: "100"},
        {key: 'createTime', visible: false, label: '创建时间', minWidth: null, sortable: true, overflow: false, align: 'center', width: "90"},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 子区域表格数据
      areaSubList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        id: null,
        name: null,
        type: null,
        areaId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      area: {},
      loadingArea: false,
    };
  },
  created() {
    this.queryParams.areaId = this.$route.params.areaId;
    this.getArea();
    this.getList();
  },
  methods: {
    getArea() {
      this.loadingArea = true;  
      getArea(this.queryParams.areaId).then(response => {
        this.area = response.data;
      }).finally(() => {
        this.loadingArea = false;
      });
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询子区域列表 */
    getList() {
      this.loading = true;
      listByAreaId(this.queryParams).then(response => {
        this.areaSubList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: SubAreaType.PARKING,
        areaId: this.queryParams.areaId,
        boundary: null,
        boundaryStr: null,
        error: null,
        longitude: null,
        latitude: null,
        createTime: null,
        picture: null,
        remark: null,
        status: SubAreaStatus.NORMAL
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加子区域";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAreaSub(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改子区域";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAreaSub(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAreaSub(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除子区域编号为"' + ids + '"的数据项？').then(function() {
        return delAreaSub(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/areaSub/export', {
        ...this.queryParams
      }, `areaSub_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.app-main .sub-area-container {
  height: calc(100vh - 50px);
  position: relative;
  overflow: hidden;
  display: flex;
}
.hasTagsView .app-main .sub-area-container  {
  height: calc(100vh - 84px);
}
.sub-area-list {
  position: relative;
  height: 100%;
  width: 700px;
  overflow-y: auto;
  padding-right: 10px;
}
.map-container {
  position: relative;
  height: 100%;
  flex: 1;
}
</style>

