<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      教学点管理
    </h2>
    <div class="m-core" v-if="tableList.length>0 || pageInfo.page>1">
      <save-form
        :inline="true"
        class="searchForm"
        @submit="search"
        @reset="onReset"
        :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-select
            v-model.trim="searchForm.publicFlag"
            clearable
            filterable
            placeholder="可用状态"
          >
            <el-option label="个人" value="0"></el-option>
            <el-option label="公共" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <el-button
        @click="openTeaching('create')"
        v-permission="'school/add'"
        type="primary"
        style="margin-bottom: 20px"
      >
        新建
      </el-button>
      <!-- 列表 -->
      <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" label="可用状态" width="120px">
            <template slot-scope="scope">
              {{ scope.row.userId ? scope.row.realName : "公共" }}
            </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-if="$helpers.permission('school/update')"
                type="text"
                >修改</el-button
              >
              <el-button
                v-if="
                  scope.row.delFlag == 0 &&
                  $helpers.permission('school/update/stop')
                "
                @click="onUpdateSubmit(scope.row, 2)"
                type="text"
                >停用</el-button
              >
              <el-button
                v-if="
                  scope.row.delFlag == 2 &&
                  $helpers.permission('school/update/open')
                "
                @click="onUpdateSubmit(scope.row, 0)"
                type="text"
                >启用</el-button
              >
              <el-button
                @click="onUpdateSubmit(scope.row, 1)"
                v-if="$helpers.permission('school/update/del')"
                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>
       <emptyPage @submit="openTeaching('create')" title='教学点管理' btnTitle='新建教学点' :context='context' v-else />
    <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="formActionTitle == 'update'"
          prop="user"
          label="可用状态"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.user" disabled></el-input>
        </el-form-item>
        <el-form-item
          v-if="form.source == 2"
          prop="remark"
          label="租赁费用"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model.trim="form.remark"
            type="number"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!--    v-if="form.source == 2" -->
        <el-form-item
          prop="organId"
          label="所属分部"
          :label-width="formLabelWidth"
        >
          <el-select
            :disabled="form.source != 2"
            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>
        <!-- :show-message="addressMessage" -->
        <el-form-item
          prop="address"
          label="上课地点"
          :label-width="formLabelWidth"
        >
          <el-input
            class="text-address"
            v-model.trim="form.address"
            :disabled="true"
          >
          <template   slot="append">
             <el-button
              class="addMapBtn"
              @click="addMap"
              type="primary"
              icon="el-icon-plus"
              >选择</el-button
            >
          </template>

          </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"
    >
      <div style="padding: 0 20px">
        <el-alert
          style="margin: 10px 0"
          title="选中地点:"
          :closable="false"
          type="info"
          :description="addressDetail.address"
        >
        </el-alert>
        <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"
          :events="events"
        >
          <el-amap-marker
            :events="markerEvents()"
            v-for="(marker, index) in markers"
            :key="index"
            :position="marker"
          ></el-amap-marker>
        </el-amap>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="mapStatus = false">取 消</el-button>
        <el-button type="primary" @click="setAddrss">确 定</el-button>
      </span>
    </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", "Geocoder"],
  v: "1.4.4",
});
import emptyPage from '@/components/emptyPage'
export default {
  name: "addressManager",
  components: { pagination,emptyPage },
  data() {
    let self = this;
    return {
      searchForm: {
        search: null,
        organId: null,
        publicFlag: 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" },
        ],
      },
      events: {
        init(o) {},
        zoomchange: (e) => {
          // console.log(e);
        },
        zoomend: (e) => {
          //获取当前缩放zoom值
          // console.log(this.$refs.map.$$getInstance().getZoom());
          // console.log(e);
        },
        click: (e) => {
          this.getpoient(e);
        },
      },
      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: "测试",
      activeAddress: {},
      context:'教学点是乐团、VIP课线下课的教学位置，不同分部可创建不同的教学点，线下课排课时需选择教学点，老师需在课程教学点的定位范围内完成考勤。教学点可设置合作单位提供、租赁两种方式。'
    };
  },
  mounted() {
    this.getList();
    this.getBreachList();
  },
  methods: {
    onTeachingSubmit(formName) {
      // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 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
      this.addressDetail.address = this.form.address;
      this.addressDetail.poi = this.form.longitudeLatitude;
      let poi = this.form.longitudeLatitude;
      let address = this.form.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.form.organId = null;
      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.location;
          lngSum += lng;
          latSum += lat;
          this.markers.push([poi.location.lng, poi.location.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length,
        };
        this.center = [center.lng, center.lat];
      }

      let geocoder = null;
      AMap.plugin(["AMap.Geocoder"], function () {
        geocoder = new AMap.Geocoder();
      });
           let that = this;
      geocoder.getAddress(pois[0].location, function (status, result) {
        if (status === "complete" && result.regeocode) {
          result.regeocode.lnglat = pois[0].location;
          let ct = result.regeocode.addressComponent;
          that.addressDetail = {
            address:
              ct.province +
              "," +
              ct.city +
              "," +
              ct.district +
              "," +
              ct.township +
              ct.street +
              ct.streetNumber,
            poi: pois[0].location.lng + "," + pois[0].location.lat,
          };

          // console.log(that.form.address,that.form.longitudeLatitude)
          // that.form.address = result.regeocode.formattedAddress;
          // that.mapStatus = false
          // that.addressMessage = false
        } else {
          that.$message.error("请重新选择地址");
        }
      });
    },
    getpoient(e) {
      // let geocoder = new AMap.Geocoder()
      this.onSearchResult([{ location:e.lnglat}]);

    },
    markerEvents() {
      // marker 事件添加
      let that = this;
      return {
        click: (e) => {
          this.getpoient(e);
        },
      };
    },
    setAddrss() {
      this.form.address = this.addressDetail.address;
      this.form.longitudeLatitude = this.addressDetail.poi;
      this.mapStatus = false;
      this.addressMessage = false;
    },
    getList() {
      let searchForm = this.searchForm;
      let params = {
        search: searchForm.search ? searchForm.search : null,
        organId: searchForm.organId ? searchForm.organId : null,
        publicFlag: searchForm.publicFlag ? searchForm.publicFlag : 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,
          longitudeLatitude: row.longitudeLatitude,
          user: row.realName ? row.realName : "公共",
        };
      }
    },
    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();
    },
    onReset() {
      this.searchForm = {
        search: null,
        organId: null,
        publicFlag: null,
      };
      this.search();
    },
  },
};
</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;
  }
}
.addMapBtn {
    background-color: var(--color-primary)!important;
    color: #fff!important;
}
.el-input-group__append {
  background: #f5f7fa;
  border-color: #dcdfe6;
  color: #909399;
  &:hover,
  &:active,
  &:focus {
    background: #f5f7fa;
    border-color: #dcdfe6;
    color: #909399;
  }
}
.el-vue-search-box-container {
  position: absolute !important;
  left: 30px;
  margin-top: 10px;
  z-index: 99999 !important;
}
</style>
