<template>
  <!-- 营地：创建、编辑 -->
  <div>
    <h4>{{title}}</h4>
    <el-form :model="form" :rules="rules" ref="form" label-width="90px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="营地名称">
            <el-input v-model="form.name" placeholder="请输入营地名称" @blur="checkName()"></el-input><span v-if="isExist" style="color:red;">标签名已存在</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="营地地址">
            <el-input v-model="form.addressStr" readonly placeholder="请输入营地地址" :on-icon-click="selectDestination" icon="edit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客服电话">
            <el-input v-model="form.servicePhone" placeholder="请输入客服电话"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="联系人">
            <el-input v-model="form.concat" placeholder="请输入联系人"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="联系电话">
            <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="营地类型" prop="approvers">
        <span  v-for="item in form.campsiteTagListVos"
               :key="item.id" style="border: 1px solid #ccc; padding: 5px 10px;border-radius: 5px;margin-right: 10px;">{{item.name}}</span>
        <el-button size="small" class="el-button el-button--primary" type="button" icon="edit" @click="editLable(form.campsiteTagListVos)">编辑</el-button>
      </el-form-item>
      <el-row>
        <el-col :span="4">
          <el-form-item label="热度值">
            <el-input v-model="form.hot" placeholder="请输入热度值"  type="number" min="0"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!--BASE_API + -->
      <el-form-item label="封面图" :style="{display:'block'}">
        <el-upload
          class="upload-demo"
          :headers="getHeaderWithToken"
          action="https://xxtest.upyuns.com/api/universal/file/app/unauth/admin/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          list-type="picture">
          <img v-if="$utils.isString(form.logo) && !$utils.isEmpty(form.logo)" :src="form.logo" style="width:300px;max-height:300px;">
          <i v-else class="el-icon-plus avatar-uploader-icon" style="lineHeight:100px;width:300px;height: 100px;border: 1px dashed #ccc;"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="轮播图" :style="{display:'block'}">
        <el-upload
          class="upload-demo"
          :headers="getHeaderWithToken"
          action="https://xxtest.upyuns.com/api/universal/file/app/unauth/admin/upload"
          :on-remove="handleRemove"
          :file-list="fileList2"
          :on-success="handleBannerSuccess"
          list-type="picture">
          <div slot="tip" class="el-upload__tip">最多上传5张</div>
          <el-button v-if="fileList2.length<5" size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-tabs v-model="activeName2" type="card" @tab-click="handleClick">
        <el-tab-pane label="营地详情" name="first">
          <!--<Editor  v-if="activeName2=='first'" @input="handelContentIncrease" :value="form.content" :myQuillEditor="'myQuillEditorContent'" :activeName2="activeName2"></Editor>-->
          <div class="editor-container" v-if="activeName2=='first'">
            <UE  :editorId="activeName2" :defaultMsg="form.content" :config=config ref="ue"  @ready="editorReadyEvent"></UE>
          </div>
        </el-tab-pane>
        <el-tab-pane label="配套&收费" name="second">
          <!--<Editor v-if="activeName2=='second'" @input="handelIntroduceIncrease" :value="form.configure" :myQuillEditor="'myQuillEditorIntroduce'" :activeName2="activeName2"></Editor>-->
          <div class="editor-container" v-if="activeName2=='second'">
            <UE :editorId="activeName2" :defaultMsg="form.configure" :config=config ref="ue"  @ready="editorReadyEvent"></UE>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-form-item></el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" v-if="title=='创建' && !isCreate && campsiteshop_btn_update" @click="create()">确 定</el-button>
      <el-button type="primary" v-if="title=='编辑' && !isCreate && campsiteshop_btn_update" @click="update()">确 定</el-button>
    </div>
    <!--编辑营地地址-->
    <campsiteModal v-if="showCampsiteVisible && campsiteshop_btn_update" :obj="campsiteObj" v-on:campsiteEvent = "campsiteEvent"></campsiteModal>
    <!--编辑营地标签-->
    <campsiteLabelModal v-if="editLableVisible && campsiteshop_btn_update" :allLabelList="allLabelList" :checkList="checkList" v-on:tourLabelEvent = "tourLabelEvent"></campsiteLabelModal>
  </div>
</template>
<style>
  textarea{
    display: none;
  }
  .info{
    border-radius: 10px;
    line-height: 20px;
    padding: 10px;
    margin: 10px;
    background-color: #ffffff;
  }
  .el-upload-list{
    display: flex;
    width: 100px;
  }
  .el-upload-list li{
    margin-left: 10px;
  }
</style>
<script>
//  import Editor from "../../modal/editorTool";//富文本
  import UE from '../../modal/Ueditor';//百度ue富文本
  import campsiteLabelModal  from "../../tourManage/modal/tourLabelModal";//标签
  import campsiteModal  from "./campsiteModal";//营地地址
  import {
    getOneCampsiteShop,
    campsiteAllTagList,
    editCampsiteShop,
    addCampsiteShop,
    existCampsiteShop
  } from 'api/campsiteManage';

  import {
    getSonRegionByCodes,
    getRegionByCodes,
  } from 'api/base_info/region/';

  import rsCode from '../../../utils/rsCode';
  import {
    getToken
  } from '../../../utils/auth';
  import {mapGetters} from 'vuex';
  export default {
    props: ["oneRow", "title", "campsiteshop_btn_update"],
    name: 'upkeepDialog',
    components: {
      UE,
      campsiteModal,
      campsiteLabelModal
    },
    data() {
      return {
        defaultMsg: '这里是UE测试',
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 350
        },
        isExist:false,//名称是否已存在
        campsiteObj: {},//营地地址
        departureList: [],//出发地列表
        departureObj:{name: ""},//出发地
        pathway: [],//途径地
        isCreate: false,//是否点击了创建-确定
        fileList2:[],
        activeName2: '',//行程亮点
        form: {
          id: undefined,
          name: undefined,//营地名称
          hot: 0,//营地热度
          servicePhone: "",//客服电话
          phone: "",//联系电话
          province: undefined,//省份
          provinceName: undefined,//省份名称
          city: undefined,//市编号
          cityName: undefined,//市名称
          address: undefined,//详细地址
          latitude: undefined,
          longitude: undefined,
          content: '',//营地详情
          concat: "",//联系人
          logo:undefined,//封面图
          configure: '',//配套&收费
          campsiteTagListVos: [],//营地类型
          carouse:[],//banner轮播
        },
        showCampsiteVisible: false,//编辑营地地址
        rules: {
          name: [
            {
              type: 'string',
              required: true,
              message: '请输入消息内容',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 100,
              message: '长度小于 100 个字符',
              trigger: 'blur'
            }
          ]
        },
        checkList:[],//已选中的标签
        allCompanies: {},
        allCompaniesArr: [],
        oneTourDialogVisible: false,
        editLableVisible: false,//营地标签
        allLabelList: [],//全部营地标签
      }
    },
    created() {
      this.getAllLabelList();
    },
    watch: {
      oneTourDialogVisible(newValue, oldValue){
        if(!newValue){
          this.cleanForm();
        }
      },
    },
    mounted() {
      this.cleanForm();
      if(this.title == "编辑"){
        let row = this.oneRow;
        this.getOne(row.id);
      } else {
        this.activeName2 = "first";
      }
      this.oneTourDialogVisible = true;
    },
    computed: {
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
    },
    methods: {
      /**
       * 判断标签名是否已存在
       * */
      checkName(){
        this.form.name = (this.form.name).trim();
        if(!this.form.name){
          return;
        }
        let params = {
          name: this.form.name
        };
        if(this.title == "编辑"){
          params.id = this.form.id;
        }
        existCampsiteShop(params).then(response => {
          if (response.status === 200) {
            this.isExist = response.data;
          } else {
            this.$notify({
              title: '失败',
              message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      /**
       * 编辑营地标签
       * */
      editLable(list){
        console.log(list);
        this.editLableVisible = true;
      },
      /**
       * 创建
       * */
      create(){
//        this.isCreate = true;
        let carouse = [];//营地轮播图
        this.form.carouse.map(function (item) {
          let c = {
            id: item.id,
            imgUrl: item.imgUrl
          };
          carouse.push(c);
        });
        /**
         * 营地类别
         * */
        let campsiteTagDTOS = [];
        this.form.campsiteTagListVos.map(function (item) {
          campsiteTagDTOS.push(item.id);
        });
        let params = {
          name: this.form.name,//营地名称
          logo: this.form.logo,//封面图
          content: this.form.content,//营地详情
          configure: this.form.configure,//配套&收费
          hot: this.form.hot,//营地热度
          campsiteTagDTOS: campsiteTagDTOS,//营地类别
          carouselDTOS: carouse,//轮播图
          concat: this.form.concat,//联系人
          servicePhone: this.form.servicePhone,//客服电话
          phone: this.form.phone,//联系电话
          province: this.campsiteObj.province,//省份
          provinceName: this.campsiteObj.provinceName,//省份名称
          city: this.campsiteObj.city,//市编号
          cityName: this.campsiteObj.cityName,//市名称
          address: this.campsiteObj.address,//详细地址
          latitude: this.campsiteObj.latitude,
          longitude: this.campsiteObj.longitude,
        };
        console.log(params);
        this.isExistCampsiteShop("create", params);
      },
      /**
       * 判断营地名称是否已存在
       * */
      isExistCampsiteShop(type, datas){
        if(!this.form.name){
          return;
        }
        let params = {
          name: this.form.name
        };
        if(type == 'update'){//编辑
          params.id = this.form.id;
        }
        existCampsiteShop(params).then(response => {
          if (response.status === 200) {
            this.isExist = response.data;
            if(response.data){
              this.isCreate = false;
            }
            if(!response.data && type == "update"){//编辑
              this.toUpdate(datas);
            }
            if(!response.data && type == "create"){
              //创建
              this.toCreate(datas);
            }
          } else {
            this.$notify({
              title: '失败',
              message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      /**
       * 编辑
       * */
      update(){
        this.isCreate = true;
        let carouse = [];//营地轮播图
        this.form.carouse.map(function (item) {
          let c = {
            id: item.id,
            imgUrl: item.imgUrl
          };
          carouse.push(c);
        });
        /**
         * 营地类别
         * */
        let campsiteTagDTOS = [];
        this.form.campsiteTagListVos.map(function (item) {
          campsiteTagDTOS.push(item.id);
        });
        let params = {
          id: this.form.id,
          name: this.form.name,//营地名称
          logo: this.form.logo,//封面图
          content: this.form.content,//营地详情
          configure: this.form.configure,//配套&收费
          hot: this.form.hot,//营地热度
          campsiteTagDTOS: campsiteTagDTOS,//营地类别
          carouselDTOS: carouse,//轮播图
          concat: this.form.concat,//联系人
          servicePhone: this.form.servicePhone,//客服电话
          phone: this.form.phone,//联系电话
          province: this.campsiteObj.province,//省份
          provinceName: this.campsiteObj.provinceName,//省份名称
          city: this.campsiteObj.city,//市编号
          cityName: this.campsiteObj.cityName,//市名称
          address: this.campsiteObj.address,//详细地址
          latitude: this.campsiteObj.latitude,
          longitude: this.campsiteObj.longitude,
        };
        console.log(params);
        this.isExistCampsiteShop("update", params);
      },
      /**
       * 更新
       * */
      toUpdate(params){
        editCampsiteShop(params).then(response => {
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            });
            this.$emit("oneCampsiteDialogEvent", true);
          } else {
            this.$notify({
              title: '编辑失败',
              message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      /**
       * 创建
       * */
      toCreate(params){
        editCampsiteShop(params).then(response => {
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            });
            this.$emit("oneCampsiteDialogEvent", true);
          } else {
            this.$notify({
              title: '创建失败',
              message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      /**
       * 获取全部营地类型
       * */
      getAllLabelList() {
        campsiteAllTagList().then(response => {
          this.allLabelList = response;
        });
      },

      /**
       * 关闭营地地址弹框
       * */
      campsiteEvent(obj){
        this.showCampsiteVisible = false;
        if(obj){
          this.campsiteObj = obj;
          let provinceObj = getRegionByCodes([obj.province]);
          let cityObj = getRegionByCodes([obj.city]);
          this.campsiteObj.provinceName = provinceObj[0].name;
          this.campsiteObj.cityName = cityObj[0].name;
          this.form.addressStr = this.campsiteObj.provinceName + this.campsiteObj.cityName + this.campsiteObj.address;
          console.log(this.campsiteObj);
        }
      },
      /**
       * 编辑营地地址
       * */
      selectDestination(){
        let that = this;
        this.campsiteObj.showTitle = "营地地址编辑";
        this.campsiteObj.eventName ='campsiteEvent';
        this.campsiteObj.keyword = this.campsiteObj.address;
        this.showCampsiteVisible = true;
      },
      /**
       * 关闭营地标签弹框
       * */
      tourLabelEvent(obj){
        let that = this;
        this.editLableVisible = false;
        let arr = [];
        let ckeckList = [];
        if(obj){
          this.allLabelList.map(function(item){
            obj.map(function(b){
              if(item.name == b){
                arr.push(item);
                ckeckList.push(b);
              }
            });
          });
          this.form.campsiteTagListVos = arr;
          this.checkList = ckeckList;
          console.log(obj);
        }
      },
      /**
       * 获取一条营地
       * */
      getOne(id){
        let that = this;
        getOneCampsiteShop(id).then(response => {
          this.form = response.data;
          this.campsiteObj = {
            address: response.data.address,
            province: response.data.province,
            provinceName: response.data.provinceName,
            city: response.data.city,
            cityName: response.data.cityName,
            latitude: response.data.latitude,
            longitude: response.data.longitude,
          };
          response.data.addressStr = this.campsiteObj.provinceName + this.campsiteObj.cityName + this.campsiteObj.address;
          let arr = [];
          that.allLabelList.map(function(b){
            response.data.campsiteTagListVos.map(function(item){
              if(item.id == b.id){
                arr.push(item.name);
              }
            });
          });
          this.checkList = arr;

          //轮播
          let fileList2 = [];
          response.data.carouse.map(function (p) {
            let pp = {
              id: p.id,
              url: p.imgUrl
            };
            fileList2.push(pp);
          });
          this.fileList2 = fileList2;
          this.activeName2 = "first";
        })
      },
      /**
       * 旅游-弹框-取消
       * */
      cancel() {
        this.cleanForm();
        this.$emit("oneCampsiteDialogEvent", false);
      },
      /**
       * 配套&收费  富文本
       * */
      handelIntroduceIncrease(step){
        this.form.configure = step;
      },
      /**
       * 富文本  营地详情
       * */
      editorReadyEvent(instance){
        let t = this;
        instance.addListener('contentChange', () => {
          if(t.activeName2 == "first"){
            t.form.content = instance.getContent();
          } else if(t.activeName2 == "second"){
            t.form.configure = instance.getContent();
          }
        });
      },
      /**
       * 删除banner
       * */
      handleRemove(file, fileList){
        let list = [];
        fileList.map(function(item){
          if(item.url != file.url){
            list.push(item);
          }
        });
        this.fileList2 = list;
        let arr = [];
        this.form.carouse.map(function(item){
          if(item.imgUrl != file.url){
            arr.push(item);
          }
        });
        this.form.carouse = arr;
      },
      /**
       * 封面图上传
       * **/
      handleAvatarSuccess(res, file){
        this.form.logo = res.data;
      },
      /**
       * banner上传
       * */
      handleBannerSuccess(res, file){
        this.fileList2.push({url:res.data});
        this.form.carouse.push({imgUrl:res.data});
      },
      /**
       * 清空旅游弹框数据
       */
      cleanForm() {
        this.campsiteObj ={name: ""};//营地地址
        this.fileList2=[];
        this.activeName2= '';//营地详情
        this.form = {
          id: undefined,
          name: undefined,//营地名称
          hot: 0,//营地热度
          servicePhone: "",//客服电话
          phone: "",//联系电话
          province: undefined,//省份
          provinceName: undefined,//省份名称
          city: undefined,//市编号
          cityName: undefined,//市名称
          address: undefined,//详细地址
          latitude: undefined,
          longitude: undefined,
          content: '',//营地详情
          concat: "",//联系人
          logo:undefined,//封面图
          configure: '',//配套&收费
          campsiteTagListVos: [],//营地类型
          carouse:[],//banner轮播
        };
        this.showCampsiteVisible= false;//编辑营地地址
      }
    }
  }
</script>
