<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 === 'status'">
                <el-switch 
                  v-model="d.row.status" 
                  :active-value="AreaSubStatus.NORMAL" 
                  :inactive-value="AreaSubStatus.DISABLED" 
                  @change="(val) => handleStatusChange(d.row, val)"
                />
              </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-edit"
              @click="handleEditBoundary(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 
        v-loading="loading"
        ref="map"
        :area="area" 
        :area-sub-list="areaSubList"
        @edit="handleUpdate"
        @delete="handleDelete"
        @add-boundary="handleAddBoundary"
        @update-boundary="handleUpdateBoundary"
        @update-area-boundary="handleUpdateAreaBoundary"
      />
    </div>
    

    <!-- 子区域编辑对话框 -->
    <area-sub-edit-dialog
      :visible.sync="open"
      :id="editId"
      :area-id="queryParams.areaId"
      :init-data="editInitData"
      @success="handleEditSuccess"
    />
  </div>
</template>

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

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

export default {
  name: "AreaSub",
  mixins: [$showColumns],
  dicts: ['area_sub_type', 'area_sub_status'],
  components: {FormCol, AreaMap, AreaSubEditDialog},
  data() {
    return {
      AreaSubStatus,
      AreaSubType,
      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: "80"},
        {key: 'error', visible: true, label: '误差', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'picture', visible: false, 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,
      // 编辑ID
      editId: null,
      // 编辑初始数据
      editInitData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        id: null,
        name: null,
        type: null,
        areaId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        type: [
          { 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: {
    // 状态变化处理
    handleStatusChange(row, val) {
      updateAreaSub({id: row.id, status: val}).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess("更新成功");
        }
      }).catch(() => {
        row.status = val == AreaSubStatus.NORMAL ? AreaSubStatus.DISABLED : AreaSubStatus.NORMAL;
      })
    },
    // 处理更新子区域边界
    handleUpdateBoundary({areaSub, boundary, longitude, latitude}) {
      console.log(areaSub, boundary, longitude, latitude);
      if (areaSub.id == null) {
        return;
      }

      updateAreaSub({
        id: areaSub.id,
        boundaryStr: boundary,
        longitude: longitude,
        latitude: latitude
      }).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess("更新成功");
          this.getList();
          this.$refs.map.cancelEdit();
        }
      })
    },
    // 处理更新运营区边界
    handleUpdateAreaBoundary({area, boundary, longitude, latitude}) {
      if (area.id == null) {
        return;
      }
      updateArea({
        id: area.id,
        boundaryStr: boundary,
        longitude: longitude,
        latitude: latitude
      }).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess("更新成功");
          this.getArea();
          this.$refs.map.cancelEdit();
        }
      })
    },
    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;
      });
    },
    /** 搜索按钮操作 */
    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
    },
    handleAddBoundary({boundary, longitude, latitude}) {
      this.editId = null;
      this.editInitData = {
        boundaryStr: boundary,
        longitude: longitude,
        latitude: latitude
      };
      this.open = true;
    },
    /** 新增按钮操作 */
    handleAdd(initData) {
      this.editId = null;
      this.editInitData = initData || {};
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editId = row.id || this.ids;
      this.editInitData = {};
      this.open = true;
      this.$nextTick(() => {
        this.$refs.map.focusArea(row);
      });
    },
    handleEditSuccess() {
      this.getList();
      this.$nextTick(() => {
        this.$refs.map.cancelEdit();
      });
    },
    handleEditBoundary(row) {
      this.$refs.map.startBoundaryEdit(row, true);
    },
    /** 删除按钮操作 */
    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>

