<template>
  <div class='m-container'>
    <h2>
      <div class="squrt"></div>教学点管理
    </h2>
    <div class="m-core">
      <div @click="openTeaching('create')"
           v-permission="'school/add'"
           class='newBand'>新建</div>
      <save-form :inline="true"
               class="searchForm"
               @submit="search"
               :model="searchForm">
        <el-form-item>
          <el-input type="text"
                    clearable
                    v-model.trim="searchForm.search"
                    placeholder="教学点名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.organId"
                     clearable
                     filterable
                     placeholder="请选择分部">
            <el-option v-for="item in selects.branchs"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
        </el-form-item>
      </save-form>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data='tableList'
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align='center'
                           width="55"
                           prop="id"
                           label="编号">
          </el-table-column>
          <el-table-column align='center'
                           prop="name"
                           label="教学点名称">
          </el-table-column>
          <el-table-column align="center"
                           prop="organName"
                           label="所属分部">
          </el-table-column>
          <el-table-column align='center'
                           label="教学点来源"
                           :formatter="filterOrgan"
                           width="120px">
            <!-- <template slot-scope="scope">
              {{ scope.row.cooperationOrganId ? scope.row.cooperationOrganId : '租赁' }}
            </template>  -->
          </el-table-column>
          <el-table-column align='center'
                           width="120px"
                           label="费用">
            <template slot-scope="scope">
              {{ scope.row.cooperationOrganId ? '免费' : scope.row.remark }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="上课地点详情">
            <template slot-scope="scope">
              {{ scope.row.address.split(',').join('') }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="delFlag"
                           label="状态">
            <template slot-scope="scope">
              {{ scope.row.delFlag == 2 ?　'停用' : '启用' }}
            </template>
          </el-table-column>
          <!-- <el-table-column align='center'
                           label="课酬补贴">
            <template slot-scope="scope">
              {{ scope.row.subsidy ? scope.row.subsidy : '无' }}
            </template>
          </el-table-column> -->
          <el-table-column align='center'
                           label="操作">
            <template slot-scope="scope">
              <el-button @click="openTeaching('update', scope.row)"
                         v-permission="'school/update'"
                         type="text">修改</el-button>
              <el-button v-if="scope.row.delFlag == 0"
                         v-permission="'school/update'"
                         @click="onUpdateSubmit(scope.row, 2)"
                         type="text">停用</el-button>
              <el-button v-if="scope.row.delFlag == 2"
                         v-permission="'school/update'"
                         @click="onUpdateSubmit(scope.row, 0)"
                         type="text">启用</el-button>
              <el-button @click="onUpdateSubmit(scope.row, 1)"
                         v-permission="'school/update'"
                         type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination sync :total.sync="pageInfo.total"
                    :page.sync="pageInfo.page"
                    :limit.sync="pageInfo.limit"
                    :page-sizes="pageInfo.page_size"
                    @pagination="getList" />
      </div>
    </div>

    <el-dialog :title="formTitle[formActionTitle]"
               :visible.sync="teachingStatus"
               @close="onFormClose('ruleForm')"
               width="500px">
      <el-form :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="教学点名称"
                      prop="name"
                      :label-width="formLabelWidth">
          <el-input v-model.trim="form.name"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="教学点来源"
                      prop="source"
                      :label-width="formLabelWidth">
          <template v-if="formActionTitle == 'update'">
            <el-select v-model.trim="form.source"
                       style="width: 100% !important;"
                       filterable
                       clearable
                       disabled>
              <el-option label="合作单位"
                         value="1"></el-option>
              <el-option label="租赁"
                         value="2"></el-option>
            </el-select>
          </template>
          <template v-else>
            <el-select v-model.trim="form.source"
                       filterable
                       style="width: 100% !important;"
                       clearable>
              <el-option label="合作单位"
                         value="1"></el-option>
              <el-option label="租赁"
                         value="2"></el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item v-if="form.source == 1"
                      prop="cooperationOrganId"
                      label="合作单位"
                      :label-width="formLabelWidth">
          <el-select v-model.trim="form.cooperationOrganId"
                     filterable
                     style="width: 100% !important;"
                     clearable
                     @change="onCooperationChange">
            <el-option v-for="item in cooperationList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.source == 2"
                      prop="remark"
                      label="费用"
                      :label-width="formLabelWidth">
          <el-input v-model.trim="form.remark"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="form.source == 2"
                      prop="organId"
                      label="所属分部"
                      :label-width="formLabelWidth">
          <el-select v-model.trim="form.organId"
                     clearable
                     style="width: 100% !important;"
                     filterable>
            <el-option v-for="item in selects.branchs"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="address"
                      :show-message="addressMessage"
                      label="上课地点"
                      :label-width="formLabelWidth">
          <el-input class="text-address"
                    v-model.trim="form.address"
                    :disabled="true">
            <el-button slot="append"
                       @click="addMap"
                       type="primary"
                       icon="el-icon-plus">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="课酬补贴"
                      prop="subsidy"
                      :label-width="formLabelWidth">
          <el-input v-model.trim.number="form.subsidy"
                    type="number"
                    autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="onTeachingCancel('ruleForm')">取 消</el-button>
        <el-button type="primary"
                   @click="onTeachingSubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false"
               title="选择地图"
               custom-class="map-container"
               :visible.sync="mapStatus"
               width="800px">
      <el-amap-search-box class="search-box"
                          value="searchValue"
                          :search-option="searchOption"
                          :on-search-result="onSearchResult"></el-amap-search-box>
      <el-amap :zoom="zoom"
               :plugin="plugin"
               :center="center">
        <el-amap-marker :events="markerEvents()"
                        v-for="(marker, index) in markers"
                        :key="index"
                        :position="marker"></el-amap-marker>
      </el-amap>
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
// 地图
(function () {
  let func = EventTarget.prototype.addEventListener;
  let supportsPassive = false
  try {
    let opts = Object.defineProperty({}, 'passive', {
      get: function () {
        supportsPassive = true;
      }
    })
    document.addEventListener("testPassive", null, opts);
    document.removeEventListener('testPassive', null, opts);
  } catch (e) { }

  EventTarget.prototype.addEventListener = function (type, fn, capture) {
    this.func = func;
    capture = capture instanceof Object ? capture : {};
    capture.passive = supportsPassive;
    this.func(type, fn, capture);
  };
}());
import { schoolQueryPage, schoolAdd, schoolUpdate, queryByOrganId, schoolDel } from '@/api/systemManage'
import { getEmployeeOrgan } from '@/api/buildTeam'
import store from '@/store'
import VueAMap from 'vue-amap'
// Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
  key: 'b1e6ac2eb28902ce91a490edf194e000',
  plugin: ['AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Geocoder'],
  v: '1.4.4'
})

export default {
  name: 'addressManager',
  components: { pagination },
  data () {
    let self = this
    return {
      searchForm: {
        search: null,
        organId: null
      },
      searchLsit: [],
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      formActionTitle: 'create',
      formTitle: {
        create: '添加教学点',
        update: '修改教学点'
      },
      teachingStatus: false, // 添加教学点
      formLabelWidth: '100px',
      addressDetail: {},
      form: {
        name: null, // 教学点名称
        source: null, // 来源
        cooperationOrganId: null, // 合作单位
        remark: null,  // 费用
        address: null, // 上课地点
        subsidy: null, // 课酬补贴
        organId: null, // 分部编号
      },
      selectOrganId: null, // 选中的分部编号
      rules: {
        name: [{ required: true, message: '请输入教学点名称', trigger: 'blur' }],
        source: [{ required: true, message: '请选择教学点来源', trigger: 'change' }],
        remark: [{ required: true, message: '请输入费用', trigger: 'blur' }],
        address: [{ required: true, message: '请选择上课地点', trigger: 'blur' }],
        cooperationOrganId: [{ required: true, message: '请选择合作单位', trigger: 'change' }],
        organId: [{ required: true, message: '请选择所属分部', trigger: 'change' }],
        subsidy: [{ type: 'number', message: '课酬补贴只能为数字', trigger: 'blur' }]
      },
      addressMessage: true,
      mapStatus: false,
      zoom: 16,
      center: [114.34371, 30.55939],
      markers: [],
      plugin: [],
      searchOption: {
        city: '',
        citylimit: true,
        pageSize: 1, // 单页显示结果条数
        pageIndex: 1, // 页码
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      },
      cooperationList: [], // 合作单位列表
      searchValue: '测试'
    }
  },
  mounted () {
    this.getList()
    this.getBreachList()
  },
  methods: {
    onTeachingSubmit (formName) { // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.address = this.addressDetail.address
          this.form.longitudeLatitude = this.addressDetail.poi
          // if(this.form.source == 1) { // 判断是租赁还是合作单位
          //   this.form.organId = this.selectOrganId
          // }
          if (this.formActionTitle == 'create') {
            schoolAdd(this.form).then(res => {
              if (res.code == 200) {
                this.$message.success('添加成功')
                this.teachingStatus = false
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else if (this.formActionTitle == 'update') {
            schoolUpdate(this.form).then(res => {
              if (res.code == 200) {
                this.$message.success('修改成功')
                this.teachingStatus = false
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          return false;
        }
      })
    },
    onTeachingCancel (formName) {
      this.teachingStatus = false
      this.$refs[formName].clearValidate()
    },
    addMap () { //
      this.mapStatus = true
      let poi = this.addressDetail.poi
      let address = this.addressDetail.address
      // 获取经纬度
      if (poi) {
        this.markers = []
        this.center = [poi.split(',')[0], poi.split(',')[1]]
        this.markers.push([poi.split(',')[0], poi.split(',')[1]])
      } else if (address && poi == '') {
        let that = this
        //构造地点查询类
        let placeSearch = new AMap.PlaceSearch({
          pageSize: 1, // 单页显示结果条数
          pageIndex: 1, // 页码
        })
        //关键字查询
        placeSearch.search(address, function (status, result) {
          if (status === 'complete') {
            let pois = result.poiList.pois[0]
            poi = pois.location.lng + ',' + pois.location.lat
            that.center = [pois.location.lng, pois.location.lat]
            that.markers.push([pois.location.lng, pois.location.lat])
          }
        })
      }
    },
    onCooperationChange (value) {
      this.cooperationList.forEach(item => {
        if (item.value == value) {
          // this.selectOrganId = item.organId
          this.form.organId = item.organId
        }
      })
    },
    onSearchResult (pois) { // 搜索出来的Marker
      this.markers = [] // 搜索时进行数据重置
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.markers.push([poi.lng, poi.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.center = [center.lng, center.lat];
      }
    },
    markerEvents () { // marker 事件添加
      let that = this
      return {
        click: (e) => {
          let geocoder = new AMap.Geocoder()
          geocoder.getAddress(e.lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              result.regeocode.lnglat = e.lnglat
              let ct = result.regeocode.addressComponent
              that.addressDetail = {
                address: ct.province + ',' + ct.city + ',' + ct.district + ',' + ct.township + ct.street + ct.streetNumber,
                poi: e.lnglat.lng + ',' + e.lnglat.lat
              }
              that.form.address = result.regeocode.formattedAddress
              that.mapStatus = false
              that.addressMessage = false
            } else {
              that.$message.error('请重新选择地址')
            }
          })
        }
      }
    },
    getList () {
      let searchForm = this.searchForm
      let params = {
        search: searchForm.search ? searchForm.search : null,
        organId: searchForm.organId ? searchForm.organId : null,
        rows: this.pageInfo.limit,
        page: this.pageInfo.page
      }
      schoolQueryPage(params).then(res => {
        if (res.code == 200 && res.data) {
          this.tableList = res.data.rows
          this.pageInfo.total = res.data.total
        }
      })
    },
    async getBreachList () { // 获取分部列表
      // 获取当前用户分部
      await this.$store.dispatch('setBranchs')

      let branchIds = []
      this.selects.branchs.forEach(item => {
        branchIds.push(item.id)
      })
      await queryByOrganId({
        organId: branchIds.join(',')
      }).then(res => {
        if (res.code == 200) {
          // 判断是否有数据
          if (!res.data && res.data.length <= 0) return
          res.data.forEach(r => {
            this.cooperationList.push({
              value: r.id,
              organId: r.organId,
              label: r.name
            })
          })
        }
      })
    },
    openTeaching (type, row) {
      // 重置数据
      // this.form = {
      //   id: null,
      //   name: null, // 教学点名称
      //   linkman: null, // 来源
      //   job: null,  // 费用
      //   mobileNo: null, // 合作单位
      // }
      this.teachingStatus = true
      this.formActionTitle = type
      // this.form.organId = ''
      // 修改的时候赋值
      if (type == 'update') {
        this.addressDetail = {
          address: row.address,
          poi: row.longitudeLatitude
        }
        this.form = {
          id: row.id,
          name: row.name, // 教学点名称
          source: row.cooperationOrganId ? "1" : "2", // 来源
          cooperationOrganId: row.cooperationOrganId, // 合作单位
          remark: row.remark,  // 费用
          address: row.address.split(',').join(''), // 上课地点
          subsidy: row.subsidy, // 课酬补贴
          organId: row.organId
        }
      }
    },
    onFormClose (formName) { // 关闭弹窗重置验证
      // this.$refs[formName].clearValidate()
      this.form = {
        name: null, // 教学点名称
        source: null, // 来源
        cooperationOrganId: null, // 合作单位
        remark: null,  // 费用
        address: null, // 上课地点
        subsidy: null, // 课酬补贴
      }
      this.$refs[formName].resetFields()
    },
    filterOrgan (val) {
      let result = ''
      if (val.cooperationOrganId) {
        this.cooperationList.forEach(res => {
          if (res.value == val.cooperationOrganId) {
            result = res.label
          }
        })
      } else {
        result = '租赁'
      }
      return result
    },
    onUpdateSubmit (row, type) {
      let msg
      if (type == 2) {
        msg = '停用'
      } else if (type == 0) {
        msg = '启用'
      } else {
        msg = '删除'
      }
      this.$confirm(`您确定${msg}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        schoolUpdate({
          id: row.id,
          delFlag: type
        }).then(res => {
          if (res.code == 200) {
            this.$message.success('修改成功')
            this.teachingStatus = false
            if (type == 2 || type == 0) {
              row.delFlag = type
            } else {
              this.getList()
            }
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    search () {
      this.pageInfo.page = 1
      this.getList()
    }
  }
}
</script>
<style lang="scss">
.el-select {
  width: auto !important;
}
.el-vue-amap-container {
  width: 100%;
  height: 50vh !important;
}
* {
  // touch-action: pan-y;
  touch-action: none;
}
.map-container {
  .el-dialog__body {
    padding: 0;
  }
}
.el-input-group__append,
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
.el-vue-search-box-container {
  position: absolute !important;
  left: 10px;
  margin-top: 10px;
  z-index: 99999 !important;
}
</style>
