<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item class="disFlex">
          <el-input v-model="searchInfo.code" class="lh30 mr10" />
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="onSubmit"
          >查询</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="openDialog"
          >新增</el-button>
          <el-popover
            v-model:visible="deleteVisible"
            placement="top"
            width="160"
          >
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="deleteVisible = false"
              >取消</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="onDelete"
              >确定</el-button>
            </div>
            <template #reference>
              <el-button
                icon="el-icon-delete"
                size="mini"
                type="danger"
                style="margin-left: 10px"
              >批量删除</el-button>
            </template>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="multipleTable"
      border
      stripe
      style="width: 100%"
      tooltip-effect="dark"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="区域编码" prop="code" />
      <el-table-column label="区域名称" prop="name" />
      <el-table-column label="上级区域" prop="parentcode" />
      <!-- <el-table-column label="optimistic字段" prop="optimistic" /> -->
      <el-table-column label="中心点" prop="postition" />
      <el-table-column label="按钮组">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            class="table-button"
            @click="updateOrganization(scope.row)"
          >变更</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteRow(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{ float: 'right', padding: '20px' }"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      title="弹窗操作"
    >
      <el-form
        ref="ruleFormRef"
        :model="formData"
        label-postition="right"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="区域编码:" prop="code">
          <el-input v-model="formData.code" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="区域名称:" prop="name">
          <el-input v-model="formData.name" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上级编码:" prop="parentcode">
          <el-input
            v-model="formData.parentcode"
            clearable
            placeholder="请输入"
          />
        </el-form-item>
        <!-- <el-form-item label="optimistic字段:">
          <el-input v-model.number="formData.optimistic" clearable placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="中心点:" prop="postition">
          <!-- <el-input @click="choosePoint" v-model="formData.postition" disabled placeholder="选择中心点坐标"  /> -->
          <el-button
            type="primary"
            size="mini"
            @click="choosePoint"
          >去地图选择</el-button>
          <span class="ml10" prop="postition">{{ formData.postition }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地图弹框开始 -->
    <el-dialog v-model="dialogMap" title="弹窗操作" width="70%" top="2vh">
      <iframe
        id="mapPage"
        class="map"
        frameborder="0"
        src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=DRGBZ-DMJE3-6SA3I-3ILVP-GMXPT-J3FLR&referer=文明城市创业管理系统"
      />
    </el-dialog>

    <!-- 地图弹框结束 -->
  </div>
</template>

<script>
import {
  createOrganization,
  deleteOrganization,
  deleteOrganizationByIds,
  updateOrganization,
  findOrganization,
  getOrganizationList,
} from '@/api/organization' //  此处请自行替换地址
import infoList from '@/mixins/infoList'

export default {
  name: 'Organization',
  mixins: [infoList],

  data() {
    return {
      // 地图弹框
      dialogMap: false,
      searchID: '1307',
      searchInfo: { parentcode: '1307' },
      listApi: getOrganizationList,
      dialogFormVisible: false,
      type: '',
      deleteVisible: false,
      multipleSelection: [],
      formData: {
        code: '',
        name: '',
        parentcode: '1307',
        optimistic: 0,

        postition: '', // 中心点
      },

      rules: {
        code: [
          {
            required: true,
            message: '区域编码不能为空',
            trigger: 'blur',
          },
        ],
        name: [
          {
            required: true,
            message: '区域名称不能为空',
            trigger: 'blur',
          },
        ],
        parentcode: [
          {
            required: true,
            message: '上级编码不能为空',
            trigger: 'blur',
          },
        ],
        postition: [
          {
            required: true,
            message: '中心点不能为空',
            trigger: 'change',
          },
        ],
      },
    }
  },
  computed: {
    'formData.code': {
      set: {

      }
    }
  },
  async created() {
    await this.getTableData()
    const that = this
    window.addEventListener(
      'message',
      function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module == 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          // console.log('location', loc);
          // console.log(loc.latlng.lat + ',' + loc.latlng.lng)
          that.formData.postition = loc.latlng.lat + ',' + loc.latlng.lng
        }
      },
      false
    )
  },

  methods: {
    // 地图选点
    choosePoint() {
      this.dialogMap = true
    },
    // 条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.searchInfo = {
        parentcode: this.searchID
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteRow(row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.deleteOrganization(row)
      })
    },
    async onDelete() {
      const ids = []
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据',
        })
        return
      }
      this.multipleSelection &&
        this.multipleSelection.map((item) => {
          ids.push(item.ID)
        })
      const res = await deleteOrganizationByIds({ ids })
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功',
        })
        if (this.tableData.length === ids.length && this.page > 1) {
          this.page--
        }
        this.deleteVisible = false
        this.getTableData()
      }
    },
    async updateOrganization(row) {
      const res = await findOrganization({ code: row.code })
      this.type = 'update'
      if (res.code === 0) {
        this.formData = res.data.reorganization
        this.dialogFormVisible = true
      }
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.formData = {
        code: '',
        name: '',
        parentcode: '',
        postition: '',
        optimistic: 0,
      }
    },
    async deleteOrganization(row) {
      const res = await deleteOrganization({ code: row.code })
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功',
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getTableData()
      }
    },
    async enterDialog() {
      this.$refs['ruleFormRef'].validate((valid) => {
        if (valid) {
          // console.log(this.formData)

          switch (this.type) {
            case 'create':

              createOrganization(this.formData)
              break
            case 'update':

              updateOrganization(this.formData)
              break
            default:

              createOrganization(this.formData)
              break
          }

          this.$message({
            type: 'success',
            message: this.type == 'create' ? '创建成功' : '修改成功',
          })
          setTimeout(() => {
            this.getTableData()
            this.closeDialog()
          }, 200)
        }
      })
    },
    openDialog() {
      this.type = 'create'
      this.dialogFormVisible = true
    },
  },
}
</script>

<style>
.map {
  width: 100%;
  height: 80vh;
}
.disFlex .el-form-item__content{
  display: flex;
}
.lh30 {
  line-height: 30px;
}
</style>
