<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-select
        class="filter-item"
        v-model="activityId"
        placeholder="搜索活动"
      >
        <el-option
          v-for="(item, index) in crud.data"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
      <el-button
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-search"
        @click="toquer"
        >搜索</el-button
      >
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :append-to-body="true"
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="600px;"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        >
          <el-form-item label="活动名称" :label-width="formLabelWidth">
            <el-input v-model="form.name" style="width: 370px" />
          </el-form-item>
          <!-- <el-form-item label="cateId" :label-width="formLabelWidth">
            <el-input v-model="form.cateId" style="width: 370px;" />
          </el-form-item> -->
          <el-form-item label="图片" :label-width="formLabelWidth">
            <single-pic
              v-model="form.images"
              type="image"
              :num="1"
              :width="150"
              :height="150"
            />
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth">
            <el-input v-model="form.price" style="width: 370px" />
          </el-form-item>
          <el-form-item label="活动分类" :label-width="formLabelWidth">
            <!-- <el-input v-model="form.cateId" style="width: 370px;" /> -->
            <el-select
              class="filter-item"
              v-model="form.cateId"
              style="width: 370px"
              placeholder="请选择活动的分类"
            >
              <el-option
                v-for="(item, index) in option"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动标签" :label-width="formLabelWidth">
            <!-- <el-input v-model="form.name" style="width: 370px;" /> -->
            <el-tag
              :key="index"
              v-for="(tag,index) in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(1)"
              @blur="handleInputConfirm(2)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
              >+添加新的标签</el-button
            >
          </el-form-item>
          <el-form-item label="热门" :label-width="formLabelWidth">
            <el-switch
              v-model="form.hot"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="推荐" :label-width="formLabelWidth">
            <el-switch
              v-model="form.recommend"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">筹备中</el-radio>
              <el-radio :label="1">报名中</el-radio>
              <el-radio :label="2">报名结束</el-radio>
              <el-radio :label="3">已完成</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="报名开始时间" :label-width="formLabelWidth">
            <el-date-picker
              :picker-options="pickerOptions"
              style="width: 370px"
              v-model="form.applyStartTime"
              type="datetime"
              placeholder="选择报名开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="报名结束时间" :label-width="formLabelWidth">
            <el-date-picker
              :picker-options="pickerOptions"
              style="width: 370px"
              v-model="form.applyEndTime"
              type="datetime"
              placeholder="选择报名结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动开始时间" :label-width="formLabelWidth">
            <el-date-picker
              :picker-options="pickerOptions"
              style="width: 370px"
              v-model="form.activityStartTime"
              type="datetime"
              placeholder="选择活动开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动结束时间" :label-width="formLabelWidth">
            <el-date-picker
              :picker-options="pickerOptions"
              style="width: 370px"
              v-model="form.activityEndTime"
              type="datetime"
              placeholder="选择活动结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="地址" :label-width="formLabelWidth">
            <el-input v-model="form.address" style="width: 370px" />
          </el-form-item>
          <el-form-item label="经纬度" :label-width="formLabelWidth">
            <!-- <el-input v-model="form.longitude" style="width: 370px;" /> -->
            <el-input v-model="lnglat" style="width: 370px">
              <el-button slot="append" type="primary" @click="toMap"
                >打开地图</el-button
              >
            </el-input>
            <el-drawer
              :append-to-body="true"
              title="选择地点"
              :visible.sync="mapVisible"
              size="50%"
            >
              <div class="drawer-body">
                <div id="map"></div>
                <div id="myPageTop">
                  <table>
                      <tr>
                          <td>
                              <label>请输入关键字：</label>
                          </td>
                      </tr>
                      <tr>
                          <td>
                              <input id="tipinput"/>
                          </td>
                      </tr>
                  </table>
                </div>
              </div>
            </el-drawer>
          </el-form-item>
          <!-- <el-form-item label="纬度" :label-width="formLabelWidth">
            <el-input v-model="form.latitude" style="width: 370px;" />
          </el-form-item> -->
          <el-form-item label="人数限制" :label-width="formLabelWidth">
            <el-input-number v-model="form.limit" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              autosize
              v-model="form.desc"
              style="width: 370px"
            ></el-input>
          </el-form-item>
          <el-form-item label="内容" :label-width="formLabelWidth">
            <!-- <el-input  type="textarea" autosize v-model="form.content" style="width: 370px;"></el-input> -->
            <ueditor-wrap
              v-model="form.content"
              :config="myConfig"
              @beforeInit="addCustomDialog"
              style="width: 90%"
            ></ueditor-wrap>
          </el-form-item>
          <!-- <el-form-item label="浏览次数" :label-width="formLabelWidth">
            <el-input v-model="form.visitTimes" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="喜欢次数" :label-width="formLabelWidth">
            <el-input v-model="form.likeTimes" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="分享次数" :label-width="formLabelWidth">
            <el-input v-model="form.shareTimes" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="收藏次数" :label-width="formLabelWidth">
            <el-input v-model="form.collectTimes" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="标签" :label-width="formLabelWidth">
            <el-input v-model="form.flag" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="phone" :label-width="formLabelWidth">
            <el-input v-model="form.phone" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="contact" :label-width="formLabelWidth">
            <el-input v-model="form.contact" style="width: 370px;" />
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.cu === 2"
            type="primary"
            @click="crud.submitCU"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-if="columns.visible('name')"
          prop="name"
          label="活动名称"
          align="center"
        />
        <el-table-column
          v-if="columns.visible('images')"
          prop="images"
          label="活动图片"
          align="center"
        >
          <template slot-scope="scope">
            <a
              v-if="scope.row.images !== null"
              :href="scope.row.images"
              style="color: #42b983"
              target="_blank"
              ><img :src="scope.row.images" alt="点击打开" class="el-avatar"
            /></a>
            <a
              v-if="scope.row.images == null"
              href="https://dss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2694643916,1778468996&fm=11&gp=0.jpg"
              style="color: #42b983"
              target="_blank"
              ><img
                src="https://dss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2694643916,1778468996&fm=11&gp=0.jpg"
                alt="点击打开"
                class="el-avatar"
            /></a>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="columns.visible('cateId')" prop="cateId" label="cateId" align="center" /> -->
        <el-table-column
          v-if="columns.visible('price')"
          prop="price"
          label="价格(元)"
          align="center"
        />
        <el-table-column
          v-if="columns.visible('status')"
          prop="status"
          label="状态"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">{{ "筹备中" }}</span>
            <span v-if="scope.row.status == 1">{{ "报名中" }}</span>
            <span v-if="scope.row.status == 2">{{ "报名结束" }}</span>
            <span v-if="scope.row.status == 3">{{ "已完成" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('activityStartTime')"
          prop="activityStartTime"
          label="活动开始时间"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.activityStartTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('activityEndTime')"
          prop="activityEndTime"
          label="活动结束时间"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.activityEndTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('applyStartTime')"
          prop="applyStartTime"
          label="报名开始时间"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyStartTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('applyEndTime')"
          prop="applyEndTime"
          label="报名结束时间"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyEndTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('address')"
          prop="address"
          label="地址"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns.visible('limit')"
          prop="limit"
          label="人数限制"
          align="center"
        />
        <!-- <el-table-column v-if="columns.visible('createTime')" prop="createTime" label="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          v-permission="['admin', 'activity:edit', 'activity:del']"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudActivity from "@/api/activity";
import { add, adds, activityFlag, posts } from "@/api/ActiveInterface";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import MaterialList from "@/components/material";
import singlePic from "@/components/singlematerial";
import UeditorWrap from "vue-ueditor-wrap";
import MapLoader from "@/utils/amap"
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "活动",
  url: "api/activity",
  sort: "id,desc",
  crudMethod: { ...crudActivity },
});
const defaultForm = {
  id: null,
  name: null,
  cateId: null,
  images: "",
  price: null,
  status: 0,
  activityStartTime: null,
  activityEndTime: null,
  applyStartTime: null,
  applyEndTime: null,
  address: "",
  limit: 1,
  desc: null,
  content: null,
  visitTimes: null,
  likeTimes: null,
  shareTimes: null,
  collectTimes: null,
  createTime: null,
  updateTime: null,
  flag: "",
  phone: null,
  contact: null,
  hot: false,
  recommend: false,
  longitude: "",
  latitude: "",
};
let map = null;
export default {
  name: "Activity",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    MaterialList,
    singlePic,
    UeditorWrap,
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ["is_enable"],
  data() {
    return {
      pickerOptions: {
        disabledDate(date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() <= Date.now();
        },
      },
      // position:[116.473179,39.993169],

      lnglat: "",
      mapVisible: false,
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      formLabelWidth: "120px",
      activityId: null,
      option: [],
      permission: {
        add: ["activity:add"],
        edit: ["activity:edit"],
        del: ["activity:del"],
      },
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: '100%', // 初始容器宽度
        UEDITOR_HOME_URL: '/UEditor/',
        serverUrl: ''
      },
      rules: {},
    };
  },
  watch: {},
  created() {
    this.classification();
    this.activityFlags();
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.lnglat = form.longitude + "," + form.latitude;
      this.form.flag = this.dynamicTags.toString();
    },
    // [CRUD.HOOK.beforeToAdd](crud, form) {
    //  console.log(form)
    //   this.$router.push({
    //       path:'/activitys/activitys/form',
    //     })
    // },
    // [CRUD.HOOK. beforeToEdit](crud, form) {
    //  console.log(form)
    //  this.$router.push({
    //       path:'/activitys/activitys/form',
    //       query:{rows:form}
    //     })
    // },

    toquer() {
      let plams = {
        page: 0,
        size: 10,
        sort: "id,desc",
        activity_id: this.activityId,
      };
      add(plams).then((res) => {
        console.log(res, "是否有数据");
      });
      //  console.log(this.activityId)
    },
    classification() {
      let plams = {
        page: 0,
        size: 100,
        sort: "id,desc",
      };
      adds(plams).then((res) => {
        console.log(res);
        this.option = res.content;
      });
    },
    activityFlags() {
      this.dynamicTags = [];
      let plams = {
        page: 0,
        size: 100,
        sort: "id,desc",
      };
      activityFlag(plams).then((res) => {
        res.content.forEach((item) => {
          this.dynamicTags.push(item.name);
        });
        console.log(res);
      });
    },
    addCustomDialog() {
      console.log("上传图片");
      window.UE.registerUI(
        "yshop",
        function (editor, uiName) {
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: "/yshop/materia/index",
            editor: editor,
            name: uiName,
            title: "上传图片",
            cssRules: "width:1200px;height:500px;padding:20px;",
          });
          this.dialog = dialog;

          var btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;z-index:9999`,
            onclick: function () {
              dialog.render();
              dialog.open();
            },
          });

          return btn;
        },
        37
      );
    },
    handleClose(tag) {
      console.log("1");
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      console.log(this.flag);
    },

    showInput() {
      console.log("2");
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
      console.log(this.dynamicTags, "多少");
    },

    handleInputConfirm(val) {
      this.form.flag = this.dynamicTags.toString();
      // let plam = {
      //   name:this.dynamicTags.pop
      // }
      console.log(val);
      if (val == 1) {
        console.log(this.dynamicTags, "数据");
      } else if (val == 2) {
        console.log(this.dynamicTags, "测试数据");
        let plame = {
          name: this.dynamicTags[this.dynamicTags.length - 1],
        };

        posts(plame).then((res) => {
          console.log(res);
        });
      }
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // fomrt(val){
    //   console.log(val,'有没有触发')
    //   this.position = [114.31667,30.51667]
    //   console.log(this.position)
    // }
    getMap() {
      let _this = this;
      //创建地图
      this.map = new AMap.Map("map", {
        zoom: 13,
        center: [114.31667, 30.51667],
      });
        //输入提示
      var autoOptions = {
          input: "tipinput"
      };
      var auto = new AMap.Autocomplete(autoOptions);
      AMap.event.addListener(auto, "select", this.select); //注册监听，当选中某条记录时会触发
      //地图点击事件
      this.map.on("click", this.showInfoClick);
    },
    showInfoClick(e) {
        let _this = this;
        this.map.clearMap(); //清理地图
        let lng = e.lnglat.getLng(); //获取经度
        let lat = e.lnglat.getLat(); //获取纬度
        //marker点
        let marker = new AMap.Marker({
          position: [lng, lat],
          offset: new AMap.Pixel(-13, -30),
        });
        _this.lnglat = lng + "," + lat; //将经纬度绑定至input输入框

        _this.map.add(marker); //加载点
        this.map.setFitView(); //缩放至地图
        console.log(_this.lnglat.split(","), "经纬度");
        _this.form.longitude = _this.lnglat.split(",")[0];
        _this.form.latitude = _this.lnglat.split(",")[1];
      },
    select(e) {
      var placeSearch = new AMap.PlaceSearch({
          map: this.map
      });  //构造地点查询类
      placeSearch.setCity(e.poi.adcode);
      placeSearch.search(e.poi.name,(status,res)=>{
        console.log(res)
        let pois = res.poiList.pois
        // res.pois 
        
      });  //关键字查询查询
      
    },
    //展示抽屉，执行获取坐标经纬度的方法
    toMap() {
      this.mapVisible = true;
      MapLoader().then((res)=>{
        //调用方法创建地图
        this.getMap();
      })
      // setTimeout(() => {
      //   //调用方法创建地图
      //   this.getMap();
      // }, 0);
    },
  },
};
</script>

<style>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
#edui_fixedlayer{
  z-index: 2021 !important;
}

.el-drawer__header span{
  font-size: 16px;
}
.drawer-body{
  width: 100%;
  height: 100%;
}
#map{
  width: 100%;
  height: 80%;
}
#myPageTop {
    position: absolute;
    top: 5px;
    right: 10px;
    background: #fff none repeat scroll 0 0;
    border: 1px solid #ccc;
    margin: 10px auto;
    padding: 6px;
    font-size: 14px;
}
.amap-sug-result{position:absolute;z-index:9999;background-color:#fefefe;border:1px solid #d1d1d1;bottom:auto}
.auto-item:hover{background-color:#cae1ff}
.auto-item{white-space:nowrap;font-size:12px;cursor:pointer;padding:4px}
.auto-item-span{color:#c1c1c1;padding-left:4px}
</style>
