<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="vehicleTypeLabel_btn_save">添加
      </el-button>
    </div>
    <el-table
      :data="list"
      :row-key="getRowKeys" :expand-row-keys="expands"
      style="width: 100%;">
      <el-table-column type="expand">
        <template scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="二级分类名称">
              <span  v-for="item,index in scope.row.children" style="margin-right: 30px;"
                     :key="item.id">{{index+1}}、{{item.name}}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column width="250" align="center" label="一级分类名称">
        <template scope="scope">
          <span>{{scope.row.parent.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="二级分类名称">
        <template scope="scope">
          <span>{{scope.row.childStr}}</span>
          <el-button size="mini" type="text" @click="showMore(scope.row)">查看更多</el-button>
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="排序">
        <template scope="scope">
          <el-button size="mini" type="text" @click="clickRank(scope.row)">{{scope.row.parent.rank?scope.row.parent.rank:0}}</el-button>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="筛选条件" v-if="vehicleTypeLabel_btn_screen">
        <template scope="scope">
          <el-button size="mini" type="text" @click="startUsingChange(scope.row)" v-if="scope.row.parent.startUsing==1" ><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="startUsingChange(scope.row)" v-if="scope.row.parent.startUsing==0" ><i style="font-size:24px;" class="el-icon-star-off el-icon--right"></i></el-button>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="是否多选">
        <template scope="scope">
          <el-button size="mini" type="text" @click="setIsMore(scope.row)" v-if="scope.row.parent.isMore==1&&vehicleTypeLabel_btn_multipleSelection" ><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="setIsMore(scope.row)" v-if="scope.row.parent.isMore==0&&vehicleTypeLabel_btn_multipleSelection" ><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 scope="scope">
          <el-button size="small"  class="el-button el-button--text el-button--small" @click="handleUpdate(scope.row)">{{vehicleTypeLabel_btn_save?'编辑':'查看'}}
          </el-button>
          <el-button  class="el-button el-button--text el-button--small" style="color:red;" v-if="scope.row.parent.id != 1 &&  scope.row.parent.id!= 14&&vehicleTypeLabel_btn_del" 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>
    <!-- 排序 modal弹窗 -->
    <el-dialog :title="modalTitle" :visible.sync="rankDialogVisible">
      <el-form :model="labelForm" :rules="rules" ref="labelForm" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="标签名称">
              <el-input v-model="labelForm.name" disabled placeholder="请输入标签名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="排序" prop="rank">
              <el-input v-model="labelForm.rank" placeholder="请输入排序值"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandel">取 消</el-button>
        <el-button type="primary" @click="updateParentLabelRank('labelForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑、创建 modal弹窗 -->
    <el-dialog :title="modalTitle" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="formRules" ref="form" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="一级分类">
              <el-input v-model="form.parent.name" placeholder="请输入一级分类名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button size="small" class="el-button el-button--primary" type="button" icon="plus" @click="addTag()">添加二级分类</el-button>
          </el-form-item>
        </el-row>
        <el-row v-for="item in form.children"
                :key="item.id" v-if="item.state == 0">
          <el-col :span="8">
            <el-form-item label="二级分类">
              <el-input v-model="item.name" placeholder="请输入二级分类名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="rank">
              <el-input v-model="item.rank" placeholder="请输入排序值"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" size="small" style="margin-left: 10px;" @click="deleteItem(item)">删除</el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandel">取 消</el-button>
        <el-button type="primary" @click="update('form')" v-if="vehicleTypeLabel_btn_save">确 定</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 {
    getLabelList,
    deleteVehicleType,
    setStartUsingById,
    setIsMoreById,
    updateAndAdd,
    updateParentRank
  } from 'api/vehicleType';

  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 {
        tableKey:0,
        modalTitle: "创建",
        dialogVisible: false,//添加、编辑弹框
        showLoadingBody: false,
        expands: [],
        labelForm:{
          name:"",
          rank: "0"
        },//待编辑的排序
        form: {
          parent:{
            id: undefined,
            isMore: 0,
            level: 1,
            name: "",
            parentId: 0,
            rank: "0",
            startUsing: 0,
            state: 0
          },
          children:[{
            id: undefined,
            isMore: 0,
            level: 2,
            name: "",
            parentId: undefined,
            rank: '0',
            startUsing: 0,
            state: 0
          }]
        },
        listQuery: {
          page: 1,
          limit: 20,
          sort: 0,//0-不分页,1-分页
        },
        formRules:{},
        rules:{
          rank:{
            type: 'string',
            required: true,
            message: '请输入排序值1',
            trigger: 'blur'
          }
        },
        list: null,
        total: null,
        listLoading: true,
        inline: true,
        rankDialogVisible: false,//排序弹框
        vehicleTypeLabel_btn_save:false,
        vehicleTypeLabel_btn_del:false,
        vehicleTypeLabel_btn_multipleSelection:false,
        vehicleTypeLabel_btn_screen:false,

      }
    },
    created() {
      this.getList();
      this.vehicleTypeLabel_btn_save=this.elements['vehicleTypeLabel:btn_save'];
      this.vehicleTypeLabel_btn_del=this.elements['vehicleTypeLabel:btn_del'];
      this.vehicleTypeLabel_btn_multipleSelection=this.elements['vehicleTypeLabel:btn_multipleSelection'];
      this.vehicleTypeLabel_btn_screen=this.elements['vehicleTypeLabel:btn_screen'];
    },
    computed: {
      ...mapGetters([
        'elements',
        'belong2Type'
      ])
    },
    methods: {
      /**
       * 添加二级标签
       * */
      addTag(){
        let t = {
          id: undefined,
          isMore: 0,
          level: 2,
          name: "",
          parentId: this.form.parent.id,
          rank: '0',
          startUsing: 0,
          state: 0
        };
        this.form.children.push(t);
      },
      /**
       * 删除时间
       * */
      deleteItem(obj){
        obj.state = 1;
        console.log(obj);
      },
      /**
       * 是否多选
       * */
      setIsMore(row){
        let params = {
          id: row.parent.id,
          isMore: row.parent.isMore==0?1:0
        };
        setIsMoreById(params).then(response => {
          if (response.status === 200) {
            this.getList();
          }
        });
      },
      /**
       * 排序点击事件
       * */
      clickRank(row){
        this.modalTitle = "编辑";
        this.labelForm = row.parent;
        this.labelForm.rank = this.labelForm.rank + "";
        this.rankDialogVisible = true;
      },
      /**
       * 查看更多
       * */
      showMore(row){
        let expands = [];
        expands.push(row.parent.id);
        this.expands = expands;
      },
      getRowKeys (row) {
        return row.parent.id
      },
      /**
       * 更改每页数量
       * */
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      /**
       * 下一页、上一页
       * */
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      /**
       * 添加
       * */
      handleCreate() {
        this.cleanForm();
        this.modalTitle = '创建';
        this.dialogVisible = true;
      },
      /**
       * 删除一个标签
       * */
      deleteHandler(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteVehicleType(row.parent.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;
        this.dialogVisible = true;
      },
      /**
       * 弹框-取消
       * */
      cancelHandel(){
        this.cleanForm();
        this.rankDialogVisible = false;
        this.dialogVisible = false;
      },
      /**
       * 编辑一级标签排序
       * */
      updateParentLabelRank(formName){
        const set = this.$refs;
        let params = {id: this.labelForm.id, rank: this.labelForm.rank};
        set[formName].validate(valid => {
          if (valid) {
            updateParentRank(params)
              .then(response => {
                if (response.status === 200) {
                  this.rankDialogVisible = false;
                  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;
          }
        });
      },
      /**
       * 清空表单
       * */
      cleanForm() {
        this.form = {
          parent:{
            id: undefined,
              isMore: 0,
              level: 1,
              name: "",
              parentId: 0,
              rank: "0",
              startUsing: 0,
              state: 0
          },
          children:[{
            id: undefined,
            isMore: 0,
            level: 2,
            name: "",
            parentId: undefined,
            rank: '0',
            startUsing: 0,
            state: 0
          }]
        };
      },
      /**
       * 获取列表数据
       * */
      getList() {
        this.listLoading = true;
        this.listQuery.sort = 0;
        getLabelList(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.parent.visible2 = false;
              let childStr = [];
              item.children.map(function(citem, index){
                if(index < 3){
                  childStr.push(citem.name);
                }
              });
              item.childStr = childStr.join("、");
            });
            totalCountRs = response.data.totalCount;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        });
      },
      /**
       * 创建
       * */
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid && !this.isExist) {
            tourTagAdd(this.form)
              .then(response => {
                if (response.status === 200) {
                  this.bannerDialogVisible = false;
                  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) {
        const set = this.$refs;
        console.log( set[formName]);
        this.form.childStr = undefined;
        set[formName].validate(valid => {
          if (valid) {
            updateAndAdd(this.form)
              .then(response => {
                if (response.status === 200) {
                  this.dialogVisible = false;
                  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;
          }
        });
      },
      /**
       * 筛选条件
       * */
      startUsingChange(row){
        let params={
          id: row.parent.id,
          startUsing: row.parent.startUsing==0?1:0
        };
        setStartUsingById(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.tourTagDTO.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.tourTagDTO.bannerNums = this.fileList2.length;
      },
      /**
       * banner上传
       * */
      handleBannerSuccess(res, file){
        this.fileList2.push({url:res.data});
        this.form.tourTagBannerDTOS.push({cover:res.data});
        this.form.tourTagDTO.bannerNums = this.fileList2.length;
      },
      getUrl(drivingLicensePath) {
        return process.env.BASE_API +
          '/vehicle/vehicleInfo/download/drivingLicense?realFileRelPath=' + encodeURI(drivingLicensePath);
      },
    }
  }
</script>
