<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="toutag_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 scope="scope">
          <span>{{scope.row.tourTagDTO.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="封面图">
        <template scope="scope">
          <img :src="scope.row.tourTagDTO.img" style="width:100%;max-height:100px;">
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="轮播图">
        <template scope="scope">
          <span>{{scope.row.tourTagDTO.bannerNums}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="旅行数量">
        <template scope="scope">
          <span>{{scope.row.tourTagDTO.count}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="排序">
        <template scope="scope">
          <span>{{scope.row.tourTagDTO.rank}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="热门标签">
        <template scope="scope">
          <!--isHot-->
          <el-button size="mini" type="text" @click="tourTagHotChange(scope.row)" v-if="scope.row.tourTagDTO.isHot==1&&tourtag_btn_hot" ><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="tourTagHotChange(scope.row)" v-if="scope.row.tourTagDTO.isHot==0&&tourtag_btn_hot" ><i style="font-size:24px;" class="el-icon-star-off el-icon--right"></i></el-button>
          <!--<el-icon v-if="scope.row.tourTagDTO.isHot==1" style="color: #208ee1;" class="el-icon-star-on" @click="tourTagHotChange(scope.row)"></el-icon>-->
          <!--<el-icon v-else class="el-icon-star-off" @click="tourTagHotChange(scope.row)"></el-icon>-->
        </template>
      </el-table-column>
      <el-table-column align="center" width="100" label="操作"  fixed="right">
        <template scope="scope">
          <el-button size="small"  class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">{{tourtag_btn_update?'编辑':'查看'}}
          </el-button>
          <el-button  class="el-button el-button--text el-button--small" style="color:red;"  size="small" @click="deleteHandler(scope.row)" v-if="tourtag_btn_del">删除</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.pageNo" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-- banner modal弹窗 -->
    <el-dialog :title="modalTitle" :visible.sync="bannerDialogVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="90px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称" @blur="isExistTourTag()"></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="请输入排序值" type="number" min="0"></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.img) && !$utils.isEmpty(form.img)" :src="form.img" 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-item label="轮播图" :style="{display:'block'}">
          <el-upload
            class="upload-demo"
            :headers="getHeaderWithToken"
            :action="BASE_API+'/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="form.bannerNums<5" size="small" type="primary">点击上传</el-button>
          </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 && tourtag_btn_update" type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .el-upload-list{
    display: flex;
    width: 100px;
  }
  .el-upload-list li{
    margin-left: 10px;
  }
</style>
<script>
  import 'static/css/uploadImg.css';// 引入图片上传组件对话框

  import {
    formatDate
  } from 'utils/dateFormattor';

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

  import {
    getTourTagList,
    tourTagUpdate,
    tourTagAdd,
    tourTagHot,
    deleteTourTag,
    existTourTag
  } from 'api/tourManage';

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

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

  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";
  import ElIcon from "../../../node_modules/element-ui/packages/icon/src/icon.vue";

  export default {
    name: 'tourManage',
    components: {
      ElIcon,
      ElCol,
      ElRow,
      Element1
    },
    data() {
      return {
        BASE_API: process.env.BASE_API,
        isCreate: false,//是否点击了确定按钮
        isExist: false,//标签是否已存在
        tableKey:0,
        modalTitle: "创建",
        bannerDialogVisible: false,//添加、编辑弹框
        showLoadingBody: false,
        fileList2: [],//轮播图
        form: {
          bannerNums: undefined,
          count: undefined,
          ctrTime: undefined,
          describe: undefined,
          id: undefined,
          img: undefined,
          isDel: undefined,
          isHot: undefined,
          name: undefined,
          rank: 0
        },
        listQuery: {
          pageNo: 1,
          pageSize: 20
        },
        rules: {
          name: {
            type: 'string',
            required: true,
            message: '请输入标签名称',
            trigger: 'blur'
          },
          rank:{
            type: 'string',
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          },
          img: {
            type: 'string',
            required: true,
            message: '请上传封面图',
          },
          banner:{
            required: true,
            message: '请上传轮播图',
          }
        },
        list: null,
        total: null,
        listLoading: true,
        inline: true,
        toutag_btn_save: false,//旅游标签添加
        tourtag_btn_update: false,//旅游标签编辑
        tourtag_btn_del: false,//旅游标签删除
        tourtag_btn_hot: false,//更改是否作为热门标签
      }
    },
    created() {
      this.getList();
      this.toutag_btn_save=this.elements['toutag:btn_save'];//旅游标签添加
      this.tourtag_btn_update=this.elements['tourtag:btn_update'];//旅游标签编辑
      this.tourtag_btn_del=this.elements['tourtag:btn_del'];//旅游标签删除
      this.tourtag_btn_hot=this.elements['tourtag:btn_hot'];//更改是否作为热门标签
    },
    computed: {
      ...mapGetters([
        'elements',
        'belong2Type'
      ]),
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
    },
    methods: {
      handleSizeChange(val) {
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNo = val;
        this.getList();
      },
      /**
       * 添加
       * */
      handleCreate() {
        this.cleanForm();
        this.modalTitle = '创建';
        this.bannerDialogVisible = true;
      },
      /**
       * 保存时判断标签名称是否已存在
       * */
      isExistTagName(type, formName){
        this.form.name = (this.form.name).trim();
        let params = {
          name: this.form.name
        };
        if(type == 'update'){//编辑
          params.id = this.form.id;
        }
        existTourTag(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
            });
          }
        });
      },
      /**
       * 判断标签名是否已存在
       * */
      isExistTourTag(){
        this.form.name = (this.form.name).trim();
        let params = {
          name: this.form.name
        };
        if(this.modalTitle == "编辑"){
          params.id = this.form.id;
        }
        existTourTag(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
            });
          }
        });
      },
      /**
       * 删除
       * */
      deleteHandler(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteTourTag(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
              });
            }
          });
        })
      },
      /**
       * 操作-编辑
       * */
      handleUpdate(row){
        this.modalTitle = '编辑';
        this.cleanForm();
        this.form = row.tourTagDTO;
        this.form.tourTagBannerDTOS = row.tourTagBannerDTOS?row.tourTagBannerDTOS: [];
        let fileList2 = [];
        if(row.tourTagBannerDTOS){
          row.tourTagBannerDTOS.map(function(item){
            let p = {
              url: item.cover
            };
            fileList2.push(p);
          });
        }
        this.fileList2 = fileList2;
        this.bannerDialogVisible = true;
      },
      /**
       * 弹框-取消
       * */
      cancelHandel(){
        this.cleanForm();
        this.bannerDialogVisible = false;
      },
      /**
       * 清空表单
       * */
      cleanForm() {
        this.form = {
          bannerNums: 0,
          count: undefined,
          ctrTime: undefined,
          describe: undefined,
          id: undefined,
          img: undefined,
          isDel: undefined,
          isHot: undefined,
          name: undefined,
          rank: 0
        };
        this.isExist = false;
        this.fileList2 = [];//轮播图
      },
      showImgDialog(drivingLicensePath) {
        this.licenceSrcUrl = this.getDrivingLicenseUrl(drivingLicensePath);
        this.dialogForm4LicenceVisible = true;
      },
      /**
       * 获取banner列表数据
       * */
      getList() {
        this.listLoading = true;
        getTourTagList(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
            listRs = response.data.data;
            response.data.data.map(function(item){
//              item.type = item.type+"";
              item.visible2 = false;
            });
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        });
      },
      /**
       * 创建请求
       * */
      toCreate(formName){
        const set = this.$refs;
//        if(!this.form.tourTagBannerDTOS){
//          this.$notify({
//            title: '警告',
//            message: '请上传轮播图',
//            type: 'warning',
//            duration: 2000
//          });
//          this.isCreate = false;//点击后确定按钮不可用
//          return;
//        }
        set[formName].validate(valid => {
          if (valid && !this.isExist) {
            let tourTagDTO = {
              bannerNums: this.form.bannerNums,
              img: this.form.img,
              name: this.form.name,
              rank: this.form.rank
            };
            tourTagAdd({tourTagDTO: tourTagDTO, tourTagBannerDTOS: this.form.tourTagBannerDTOS})
              .then(response => {
                this.isCreate = false;//点击后确定按钮不可用
                if (response.status === 200) {
                  this.bannerDialogVisible = 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 {
            this.isCreate = false;//点击后确定按钮不可用
            return false;
          }
        });
      },
      /**
       * 创建
       * */
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.isCreate = true;//点击后确定按钮不可用
            this.isExistTagName("create", formName);
          }
        });
      },
      /**
       * 编辑-确定按钮
       * */
      update(formName){
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.isCreate = true;//点击后确定按钮不可用
            this.isExistTagName("update", formName);
          }
        });
      },
      /**
       * 编辑-更新
       * */
      toUpdate(formName) {
        const set = this.$refs;
        if(!this.form.tourTagBannerDTOS){
          this.$notify({
            title: '警告',
            message: '请上传轮播图',
            type: 'warning',
            duration: 2000
          });
          this.isCreate = false;//点击后确定按钮不可用
          return;
        }
        set[formName].validate(valid => {
          if (valid && !this.isExist) {
            let tourTagDTO = {
              id: this.form.id,
              bannerNums: this.form.bannerNums,
              img: this.form.img,
              name: this.form.name,
              rank: this.form.rank
            };
            tourTagUpdate({tourTagDTO: tourTagDTO, tourTagBannerDTOS: this.form.tourTagBannerDTOS}).then(response => {
              this.isCreate = false;//点击后确定按钮不可用
              if (response.status === 200) {
                this.bannerDialogVisible = 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 {
            this.isCreate = false;//点击后确定按钮不可用
            return false;
          }
        });
      },
      /**
       * 热门标签
       * */
      tourTagHotChange(row){
        let params={
          id: row.tourTagDTO.id,
          state: row.tourTagDTO.isHot==0?1:0
        };
        tourTagHot(params).then(response => {
          if (response.status === 200) {
            this.getList();
          }});
      },
      /**
       * 上传图片
       * @param file
       * @returns {boolean}
       */
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/GIF 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!');
        }
        this.showLoadingBody = true;
        return isJPG && isLt2M;
      },
      /**
       * 封面图上传
       * */
      handleAvatarSuccess(res, file) {
        this.form.img = res.data;
        this.showLoadingBody = false;
      },
      /**
       * 删除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.tourTagBannerDTOS.map(function(item){
          if(item.cover != file.url){
            arr.push(item);
          }
        });
        this.form.tourTagBannerDTOS = arr;
        this.form.bannerNums = this.fileList2.length;
      },
      /**
       * banner上传
       * */
      handleBannerSuccess(res, file){
        this.fileList2.push({url:res.data});
        this.form.tourTagBannerDTOS.push({cover:res.data});
        this.form.bannerNums = this.fileList2.length;
      },
      /**
       * 操作-删除
       * */
      deleteHandler(row) {
        deleteTourTag(row.tourTagDTO.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
            });
          }
        });
      },
      getUrl(drivingLicensePath) {
        return process.env.BASE_API +
          '/vehicle/vehicleInfo/download/drivingLicense?realFileRelPath=' + encodeURI(drivingLicensePath);
      },
    }
  }
</script>
