<template>
  <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div class="filter-container" ref="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate"
                 type="primary" icon="edit" v-if="campsite_tag_btn_save">添加
      </el-button>
    </div>
    <el-table :key='tableKey' :data="list" border fit highlight-current-row
              style="width: 100%">
      <el-table-column
        type="index"
        align="center" label="序号" width="65">
      </el-table-column>
      <el-table-column align="center" label="类型名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标签底图">
        <template slot-scope="scope">
          <img :src="scope.row.tagUrl" style="width: 130px;"/>
        </template>
      </el-table-column>

      <el-table-column width="200" align="center" label="筛选条件">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="isSearchChange(scope.row)" v-if="scope.row.isSearch==1&&campsite_btn_sing" ><i style="color: #208ee1;font-size:24px;" class="el-icon-star-on el-icon--right"></i></el-button>
          <el-button size="mini" type="text" @click="isSearchChange(scope.row)" v-if="scope.row.isSearch==0&&campsite_btn_sing" ><i style="font-size:24px;" class="el-icon-star-off el-icon--right"></i></el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button size="small"  class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">{{campsite_tag_btn_update?'编辑':'查看'}}</el-button>
          <el-button v-if="campsite_btn_del" class="el-button el-button--text el-button--small" style="color:red;" size="small" @click="deleteHandler(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
         :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
         layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- 编辑、创建标签弹窗 -->
    <el-dialog :title="modalTitle" :visible.sync="dialogVisible">
      <el-form :model="form" ref="form" :rules="rules" label-width="90px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称" @blur="isExistTag()"></el-input><span v-if="isExist" style="color:red;">标签名已存在</span>
        </el-form-item>
        <!--0-app首页,1-app旅游页；2-租车-->
        <el-form-item label="排序">
          <el-input v-model="form.rank" placeholder="请输入排序值"></el-input>
        </el-form-item>
        <!--BASE_API + -->
        <el-form-item label="标签底图" :style="{display:'block'}">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API+'/api/universal/file/app/unauth/admin/upload'"
            :show-file-list="false"
            :headers="getHeaderWithToken"
            :on-success="handleAvatarSuccess">
            <img v-if="$utils.isString(form.tagUrl) && !$utils.isEmpty(form.tagUrl)" :src="form.tagUrl" style="width:300px;max-height:300px;">
            <i v-else class="el-icon-plus avatar-uploader-icon" style="lineHeight:100px;width:300px;height: 100px;"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandel">取 消</el-button>
        <el-button v-if="modalTitle=='创建' && !isCreate" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-if="modalTitle=='编辑' && !isCreate&&campsite_tag_btn_update" type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import 'static/css/uploadImg.css';// 引入图片上传组件对话框

  import {
    formatDate
  } from 'utils/dateFormattor';

  import {
    toEast8Date,
    deepCopyDate,
    newEast8Date,
    convertDate2Str
  } from 'utils/dateUtils';

  import rsCode from '../../utils/rsCode';

  import {mapGetters} from 'vuex';
  import {
    getToken
  } from 'utils/auth';

  import {
    campsiteTagList,
    setSearchById,
    delCampsiteTag,
    editCampsiteTag,
    existTag,
    addCampsiteTag
  } from 'api/campsiteManage';

  import Element1 from "../admin/menu/components/element";
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";

  export default {
    name: 'tourManage',
    components: {
      ElCol,
      ElRow,
      Element1
    },
    data() {
      return {
		isCreate: false,
        modalTitle: "创建",
        BASE_API: process.env.BASE_API,
        dialogVisible: false,//添加、编辑弹框
        showLoadingBody: false,
        isExist: false,//标签是否已存在
        form: {
          name: undefined,//标签名称
          rank: 0,//排序
          tagUrl: "",//标签底图
          isSearch: 0,//是否是筛选条件
        },
        rules:{
          name: {
            type: "string",
            message: '请输入名称',
            required: true,
            trigger: 'blur'
          }
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
        },
        inline: true,
        tableKey: 0,
        campsite_tag_btn_save: false,//营地标签新增
        campsite_tag_btn_update: false,//标签编辑
        campsite_btn_del: false,//标签删除
        campsite_btn_sing: false,//是否作为筛选条件
      }
    },
    created() {
      this.getList();
      this.campsite_tag_btn_save=this.elements['campsite_tag:btn_save'];//营地标签新增
      this.campsite_tag_btn_update=this.elements['campsite_tag:btn_update'];//标签编辑
      this.campsite_btn_del=this.elements['campsite:btn_del'];//标签删除
      this.campsite_btn_sing=this.elements['campsite:btn_sing'];//是否作为筛选条件
    },
    computed: {
      ...mapGetters([
        'elements',
        'belong2Type'
      ]),
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
    },
    methods: {
      /**
       * 保存时判断标签名称是否已存在
       * */
      isExistTagName(type, formName){
        if(!this.form.name){
          return;
        }
        let params = {
          name: this.form.name
        };
        if(type == 'update'){//编辑
          params.id = this.form.id;
        }
        existTag(params).then(response => {
          if (response.status === 200) {
            this.isExist = response.data;
            if(response.data){
              this.isCreate = false;
            }
            if(!response.data && type == "update"){//编辑
              this.toUpdate(formName);
            }
            if(!response.data && type == "create"){
              //创建
              this.toCreate(formName);
            }
          } else {
            this.$notify({
              title: '失败',
              message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
              type: 'error',
              duration: 2000
            });
          }
        });
      },
      /**
       * 判断标签名是否已存在
       * */
      isExistTag(){
        this.form.name = (this.form.name).trim();
        if(!this.form.name){
          return;
        }
        let params = {
          name: this.form.name
        };
        if(this.modalTitle == "编辑"){
          params.id = this.form.id;
        }
        existTag(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
            });
          }
        });
      },
      /**
       * 添加
       * */
      handleCreate() {
        this.resetTemp();
        this.modalTitle = '创建';
        this.isExist = false;
        this.dialogVisible = true;
      },
      cancelHandel(){
        this.dialogVisible = false;
      },
      /**
       * 底图上传
       * */
      handleAvatarSuccess(res, file) {
        this.form.tagUrl = res.data;
        this.showLoadingBody = false;
      },
      /**
       * 创建营地类型
       * */
      toCreate(formName){
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid && !this.isExist) {
            this.form.visible2 = undefined;
            addCampsiteTag(this.form).then(response => {
              if (response.status === 200) {
                this.dialogVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                });
                this.getList();
              } else {
                this.$notify({
                  title: '失败',
                  message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                  type: 'error',
                  duration: 2000
                });
              }
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 新建标签
       * */
      create(formName){
        this.isCreate = true;//点击了确定按钮-按钮不可用
        this.isExistTagName("create", formName);
      },
      /**
       * 删除
       * */
      deleteHandler(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            delCampsiteTag(row.id).then(response => {
              if (response.status === 200) {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                });
                this.getList();
              } else {
                this.$notify({
                  title: '删除失败',
                  message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                  type: 'error',
                  duration: 2000
                });
              }
            });
        })
      },
      /**
       * 编辑营地类别
       * */
      toUpdate(formName){
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid && !this.isExist) {
            this.form.visible2 = undefined;
            editCampsiteTag(this.form).then(response => {
              if (response.status === 200) {
                this.dialogVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                });
                this.getList();
              } else {
                this.$notify({
                  title: '失败',
                  message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                  type: 'error',
                  duration: 2000
                });
              }
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 编辑-更新
       * */
      update(formName) {
        this.isCreate = true;//点击了确定按钮-按钮不可用
        this.isExistTagName("update", formName);
      },
      /**
       * 深拷贝
       */
      objDeepCopy (source) {
        var sourceCopy = source instanceof Array ? [] : {};
        for (var item in source) {
          sourceCopy[item] = typeof source[item] === 'object' ? objDeepCopy(source[item]) : source[item];
        }
        return sourceCopy;
      },
      /**
       * 编辑
       * */
      handleUpdate(row) {
        this.modalTitle = '编辑';
        this.form = this.objDeepCopy(row);
        this.dialogVisible = true;
      },
      /**
       * 筛选条件
       * */
      isSearchChange(row){
        let params={
          id: row.id,
          status: row.isSearch==0?1:0
        };
        setSearchById(params).then(response => {
          if (response.status === 200) {
            this.getList();
          }
        });
      },
      /**
       * 获取营地标签列表
       * */
      getList() {
        this.listLoading = true;
        campsiteTagList(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
            response.data.data.map(function(item){
              item.visible2 = false;
            });
            listRs = response.data.data;
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      /**
       * 重置标签
       * */
      resetTemp() {
        this.form = {
          name: undefined,//标签名称
          rank: 0,//排序
          tagUrl: "",//标签底图
          isSearch: 0,//是否是筛选条件
        };
      },
    }
  }
</script>
