<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.communityId" placeholder="社区编号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.communityName" placeholder="社区名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.provinceId" placeholder="省" style="width: 90px" class="filter-item" @change="getCityList">
        <el-option v-for="item in provinceList" :key="item.id" :label="item.province" :value="item.id"/>
      </el-select>
      <el-select v-model="listQuery.cityId" placeholder="市" class="filter-item" style="width: 130px" @change="getDistrictList">
        <el-option v-for="item in cityList" :key="item.id" :label="item.city" :value="item.id"/>
      </el-select>
      <el-select v-model="listQuery.districtId" placeholder="区县乡" class="filter-item" style="width: 130px">
        <el-option v-for="item in districtList" :key="item.id" :label="item.district" :value="item.id"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus" @click="handleCreate">添加</el-button>
      <el-button v-waves class="filter-item" type="info" icon="el-icon-warning" @click="clearListQuery">清空</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
      @sort-change="sortChange">
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="50"/>
      <el-table-column label="社区编号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="社区名称" align="center">
        <template slot-scope="scope">
          <span @click="handleLook(scope.row)" style="color: #409EFF;cursor: pointer">{{ scope.row.communityName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="社区别名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.communityAlias }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在地区" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物业人员数量" align="center">
        <template slot-scope="scope">
          <span>52</span>
        </template>
      </el-table-column>
      <el-table-column label="已核户主数量" align="center">
        <template slot-scope="scope">
          <span>123</span>
        </template>
      </el-table-column>
      <el-table-column label="已核家属数量" align="center">
        <template slot-scope="scope">
          <span>345</span>
        </template>
      </el-table-column>
      <el-table-column label="已核租客数量" align="center">
        <template slot-scope="scope">
          <span>234</span>
        </template>
      </el-table-column>
      <el-table-column label="物业管理员" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="高德坐标" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.longitude }},{{ scope.row.latitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="录入时间" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" :current-page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" :page-sizes="[5, 10, 20, 30]" @pagination="getList" /> -->
    <el-pagination
      :total="total"
      :current-page="listQuery.pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="detail" label-position="left" label-width="100px" style="margin-left:50px;">
        <el-form-item label="社区名称*">
          <el-input v-model="detail.communityName"/>
        </el-form-item>
        <el-form-item label="社区别名">
          <el-input v-model="detail.communityAlias"/>
        </el-form-item>
        <el-form-item label="所在区县*">
          <el-select v-model="detail.provinceId" placeholder="省" style="width: 90px" class="filter-item" @change="getEditCityList">
            <el-option v-for="item in provinceList" :key="item.id" :label="item.province" :value="item.id"/>
          </el-select>
          <el-select v-model="detail.cityId" placeholder="市" class="filter-item" style="width: 130px" @change="getEditDistrictList">
            <el-option v-for="item in editCityList" :key="item.id" :label="item.city" :value="item.id"/>
          </el-select>
          <el-select v-model="detail.districtId" placeholder="区县乡" class="filter-item" style="width: 130px">
            <el-option v-for="item in editDistrictList" :key="item.id" :label="item.district" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="高德坐标*">
          <el-input
            v-model="detail.longitude"
            placeholder="经度"/>
          <el-input
            v-model="detail.latitude"
            placeholder="纬度"/>
        </el-form-item>
        <!-- <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box> -->
        <div style="width:100%;height:200px;">
          <el-amap ref="map" :events="events" :center="mapCenter" :zoom="12" class="amap-demo" vid="amapDemo" >
            <el-amap-marker v-for="(item,index) in markers" :key="index" :position="item" />
          </el-amap>
        </div>
        <el-form-item label="管理员姓名*">
          <el-input
            v-model="detail.userName"
            placeholder="建议先填写运营人员姓名"/>
        </el-form-item>
        <el-form-item label="管理员账号*">
          <el-input
            v-model="detail.loginName"
            placeholder="建议先填写运营人员手机号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="'查看'" :visible.sync="dialogLookFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="detail" label-position="left" label-width="100px" style="margin-left:50px;">
        <el-form-item label="社区名称">
          <span>{{ detail.communityName }}</span>
        </el-form-item>
        <el-form-item label="社区别名">
          <span>{{ detail.communityAlias }}</span>
        </el-form-item>
        <el-form-item label="所在区县">
          <span>{{ getProvinceName(detail.provinceId) + getCityName(detail.cityId) + getDistrictName(detail.districtId) }}</span>
        </el-form-item>
        <el-form-item label="高德坐标">
          <span>{{ '经度: ' + detail.longitude }}</span>
          <span>{{ '纬度: ' + detail.latitude }}</span>
        </el-form-item>
        <!-- <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box> -->
        <div style="width:100%;height:200px;">
          <el-amap ref="map" :events="events" :center="mapCenter" :zoom="12" class="amap-demo" vid="amapDemo" >
            <el-amap-marker v-for="(item,index) in markers" :key="index" :position="item" />
          </el-amap>
        </div>
        <el-form-item label="管理员姓名">
          <span>{{ detail.userName }}</span>
        </el-form-item>
        <el-form-item label="管理员账号">
          <span>{{ detail.loginName }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogLookFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogLookFormVisible = false,handleUpdate(detail)">修 改</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  computed: {
    ...mapState('community', {
      list: s => s.list,
      detail: s => s.detail,
      total: s => s.total,
      provinceList: s => s.provinceList,
      cityList: s => s.cityList,
      districtList: s => s.districtList,
      editCityList: s => s.editCityList,
      editDistrictList: s => s.editDistrictList
    })
  },
  data() {
    var _self = this
    return {
      events: {
        click: (e) => {
          // _self.postData.Coordinate = e.lnglat.lat + ',' + e.lnglat.lng
          _self.detail.longitude = e.lnglat.lng
          _self.detail.latitude = e.lnglat.lat
        }
      },
      markers: [],
      searchOption: {
        city: '南京',
        citylimit: false
      },
      mapCenter: [118.789509, 32.019989],
      tableKey: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        communityId: undefined,
        communityName: undefined,
        provinceId: undefined,
        cityId: undefined,
        districtId: undefined
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogLookFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        createData: [{ type: 'date', required: true, message: 'createData is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getProvinceList()
  },
  methods: {
    ...mapMutations('community', {
      resetDetail: 'resetDetail',
      setDetail: 'setDetail'
    }),
    ...mapActions('community', [
      'FetchCommunityList',
      'CreateCommunity',
      'UpdateCommunity',
      'FetchProvinceList',
      'FetchCityList',
      'FetchDistrictList',
      'FetchEditCityList',
      'FetchEditDistrictList'
    ]),
    onSearchResult(pois) { // 搜索地图
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          const { lng, lat } = poi
          lngSum += lng
          latSum += lat
          this.markers.push([poi.lng, poi.lat])
        })
        const center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.mapCenter = [center.lng, center.lat]
      }
    },
    setCurrent(item) {
      this.setDetail({ ...item })
    },
    getList() {
      this.listLoading = true
      this.FetchCommunityList(this.listQuery).then(() => {
        this.listLoading = false
      }).catch(() => {
        this.loading = false
        console.log('get list error')
      })
    },
    getProvinceList() {
      this.FetchProvinceList().then(() => {
      }).catch(() => {
        console.log('get list error')
      })
    },
    getCityList() {
      this.listQuery.cityId = undefined
      this.listQuery.districtId = undefined
      this.FetchCityList(this.listQuery.provinceId).then(() => {
      }).catch(() => {
        console.log('get list error')
      })
    },
    getDistrictList() {
      this.listQuery.districtId = undefined
      this.FetchDistrictList(this.listQuery.cityId).then(() => {
      }).catch(() => {
        console.log('get list error')
      })
    },
    getEditCityList() {
      this.FetchEditCityList(this.detail.provinceId).then(() => {
      }).catch(() => {
        console.log('get list error')
      })
    },
    getEditDistrictList() {
      this.FetchEditDistrictList(this.detail.cityId).then(() => {
      }).catch(() => {
        console.log('get list error')
      })
    },
    clearListQuery() {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = 20
      this.listQuery.communityId = undefined
      this.listQuery.communityName = undefined
      this.listQuery.provinceId = undefined
      this.listQuery.cityId = undefined
      this.listQuery.districtId = undefined
      this.getList()
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.listQuery.pageNum = val
      this.getList()
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.CreateCommunity(this.detail).then((res) => {
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$message({
                message: '创建成功',
                type: 'success'
              })
              this.getList()
            }else if (res.code == 0) {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.setCurrent(row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getEditCityList()
      this.getEditDistrictList()
    },
    handleLook(row) {
      this.setCurrent(row)
      this.dialogLookFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getEditCityList()
      this.getEditDistrictList()
    },
    handleCreate() {
      this.resetDetail()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.UpdateCommunity(this.detail).then((res) => {
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$message({
                message: '更新成功',
                type: 'success'
              })
              this.getList()
            }else if (res.code == 0) {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    padDate(value) {
      value = value < 10 ? '0' + value : value
      return value
    },
    formatDate(val) {
      var value = new Date(val)
      var year = value.getFullYear()
      var month = this.padDate(value.getMonth() + 1)
      var day = this.padDate(value.getDate())
      var hour = this.padDate(value.getHours())
      var minutes = this.padDate(value.getMinutes())
      var seconds = this.padDate(value.getSeconds())
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getProvinceName(provinceId) {
      const tempProvince = this.provinceList
      for (const i in tempProvince) {
        if (tempProvince[i].id === provinceId) {
          return tempProvince[i].province
        }
      }
    },
    getCityName(cityId) {
      const tempCity = this.editCityList
      for (const i in tempCity) {
        if (tempCity[i].id === cityId) {
          return tempCity[i].city
        }
      }
    },
    getDistrictName(districtId) {
      const tempDistrict = this.editDistrictList
      for (const i in tempDistrict) {
        if (tempDistrict[i].id === districtId) {
          return tempDistrict[i].district
        }
      }
    },
  }
}
</script>
