<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">-->
<!--      <el-form-item label="仪器型号" prop="instrumentModel">-->
<!--        <el-input-->
<!--          v-model="queryParams.instrumentModel"-->
<!--          placeholder="请输入仪器型号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模式名称" prop="modeName">-->
<!--        <el-input-->
<!--          v-model="queryParams.modeName"-->
<!--          placeholder="请输入模式名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模式描述" prop="modeDesc">-->
<!--        <el-input-->
<!--          v-model="queryParams.modeDesc"-->
<!--          placeholder="请输入模式描述"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模式封面图片" prop="modeBanner">-->
<!--        <el-input-->
<!--          v-model="queryParams.modeBanner"-->
<!--          placeholder="请输入模式封面图片"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模式视频" prop="modeVideo">-->
<!--        <el-input-->
<!--          v-model="queryParams.modeVideo"-->
<!--          placeholder="请输入模式视频"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模式分类(每个仪器有不一样的模式分类)" prop="modeClass">-->
<!--        <el-input-->
<!--          v-model="queryParams.modeClass"-->
<!--          placeholder="请输入模式分类(每个仪器有不一样的模式分类)"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="是否属于舱体模式：0、不是 1、是" prop="isCabinMode">-->
<!--        <el-input-->
<!--          v-model="queryParams.isCabinMode"-->
<!--          placeholder="请输入是否属于舱体模式：0、不是 1、是"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="模式时长" prop="modeTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.modeTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择模式时长">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="准备视频" prop="preparationVideo">-->
<!--        <el-input-->
<!--          v-model="queryParams.preparationVideo"-->
<!--          placeholder="请输入准备视频"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="启动图片GIF" prop="beganVideo">-->
<!--        <el-input-->
<!--          v-model="queryParams.beganVideo"-->
<!--          placeholder="请输入启动图片GIF"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="暂停图片GIF" prop="pauseVideo">-->
<!--        <el-input-->
<!--          v-model="queryParams.pauseVideo"-->
<!--          placeholder="请输入暂停图片GIF"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
<!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:mode:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:mode:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:mode:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:mode:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="仪器类型" align="center" prop="instrumentType" >
        <template slot-scope="scope">
          <span v-show="scope.row.instrumentType == 1">非iot仪器</span>
          <span v-show="scope.row.instrumentType == 2">iot仪器</span>
        </template>
      </el-table-column>
      <el-table-column label="仪器型号" align="center" prop="instrumentModel" />
      <el-table-column label="模式类型" align="center" prop="modeType" />
      <el-table-column label="模式分类" align="center" prop="modeClass" />
      <el-table-column label="模式名称" align="center" prop="modeName" />
      <el-table-column label="模式时长" align="center" prop="modeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模式封面图片" align="center" prop="modeBanner" >
        <template slot-scope="scope">
          <el-image :src="scope.row.modeBanner" style="width: 60px;height: 80px" :preview-src-list="[scope.row.modeBanner]">
            <div slot="placeholder" class="image-slot"><span class="dot"></span>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="解锁小程序标签" align="center" prop="lockWechatTag" />
      <el-table-column label="解锁外部标签" align="center" prop="lockCompanyTag" />
      <el-table-column label="备注 " align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:mode:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:mode:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模式列表对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :before-close="closeOpen">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仪器类型" prop="instrumentType">
          <el-select v-model="form.instrumentType">
            <el-option label="非iot仪器" :value="1" :key="1"></el-option>
            <el-option label="iot仪器" :value="2" :key="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模式名称" prop="modeName">
          <el-input v-model="form.modeName" placeholder="请输入模式名称" maxlength="10"/>
        </el-form-item>
        <el-form-item label="模式描述" prop="modeDesc">
          <el-input v-model="form.modeDesc" placeholder="请输入模式描述" maxlength="10"/>
        </el-form-item>
        <el-form-item label="模式封面" prop="modeBanner">
          <el-upload
            :action="upload.url"
            :headers="upload.headers"
            :file-list="bannerList"
            list-type="picture-card"
            :on-preview="handlePreviewFile"
            :on-success="handleBannerFileSuccess"
            :before-upload="beforeBannerUpload"
            :on-remove="handleRemoveBanner">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="模式视频" prop="modeVideo">
          <el-upload
            class="upload-demo"
            :action="upload.url"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleFileSuccess"
            :headers="upload.headers"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传视频文件，且不超过50M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="解锁小程序标签" prop="showWechatTagId" label-width="120px">
          <treeselect v-model="form.lockWechatTagArray" :options="chatTagOptions" :multiple="true" :show-count="true" placeholder="请选择小程序标签" :disable-branch-nodes="true" />
        </el-form-item>
        <el-form-item label="解锁外部标签" prop="showCompanyTagId" label-width="120px">
          <treeselect v-model="form.lockCompanyTagArray" :options="tagOptions" :multiple="true" :show-count="true" placeholder="请选择外部标签" :disable-branch-nodes="true" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="50"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">重 置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMode, getMode, delMode, addMode, updateMode } from "@/api/system/mode";
import {getToken} from "@/utils/auth";
import { tagTreeSelect } from "@/api/system/wechatTab";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Mode",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      tagOptions: [],
      chatTagOptions: [],
      // 模式列表表格数据
      modeList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 封面list
      fileList: [],
      bannerList:[],
      // 上传参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/upload"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        instrumentType: null,
        instrumentModel: null,
        modeName: null,
        modeDesc: null,
        modeBanner: null,
        modeVideo: null,
        modeType: null,
        modeClass: null,
        isCabinMode: null,
        modeTime: null,
        preparationVideo: null,
        beganVideo: null,
        pauseVideo: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        instrumentType: [
          { required: true, message: "模式类型不能为空", trigger: "blur" }
        ],
        modeName: [
          { required: true, message: "模式名称不能为空", trigger: "blur" }
        ],
        modeBanner: [
          { required: true, message: "封面图片不能为空", trigger: "blur" }
        ],
        modeVideo: [
          { required: true, message: "模式视频不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询模式列表列表 */
    getList() {
      this.loading = true;
      listMode(this.queryParams).then(response => {
        this.modeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    closeOpen(){
      this.fileList = [];
      this.bannerList = [];
      this.open = false;
    },
    // 取消按钮
    cancel() {
      // this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        instrumentType: null,
        instrumentModel: null,
        modeName: null,
        modeDesc: null,
        modeBanner: null,
        modeVideo: null,
        modeType: null,
        modeClass: null,
        isCabinMode: null,
        modeTime: null,
        preparationVideo: null,
        beganVideo: null,
        pauseVideo: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
      this.bannerList = [];
      this.fileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模式";
      this.form.instrumentType = 1;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.bannerList = [];
      this.fileList = [];
      getMode(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模式";
        this.fileList.push({
          name: this.handleFileInfo(this.form.modeVideo),
          url: this.form.modeVideo
        })
        this.bannerList.push({
          name: this.handleFileInfo(this.form.modeBanner),
          url: this.form.modeBanner
        })
      });
    },
    handleFileInfo(url) {
      if (url) {
        const filePath = url.substring(0, url.lastIndexOf("/"));
        // 获取文件名（包括扩展名）
        const fileNameWithExtension = url.substr(filePath.length + 1);
        return fileNameWithExtension
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMode(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMode(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模式列表编号为"' + ids + '"的数据项？').then(function() {
        return delMode(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查询标签下拉树结构 */
    getDeptTree() {
      tagTreeSelect({type: 2}).then(response => {
        this.tagOptions = response.data;
      });
      tagTreeSelect({type: 1}).then(response => {
        this.chatTagOptions = response.data;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/mode/export', {
        ...this.queryParams
      }, `mode_${new Date().getTime()}.xlsx`)
    },
    handleRemove(file, fileList) {
      console.log('调用了')
      this.fileList = [];
    },
    handleRemoveBanner(file, fileList) {
      // console.log('调用了删除')
      this.bannerList = [];
    },
    handlePreview(file) {
      console.log(file);
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList, item) {
      console.log('上传后的结果==>',JSON.stringify(response))
      if(response.code == '200') {
        this.fileList = [];
        this.fileList.push({
          name: response.data.name,
          url: response.data.url,
        })
        this.form.modeVideo = response.data.url;
      }
    },
    // 封面上传成功处理
    handleBannerFileSuccess(response, file, fileList, item) {
      console.log('上传后的结果==>',JSON.stringify(response))
      if(response.code == '200') {
        this.bannerList = [];
        this.form.modeBanner = response.data.url;
        this.bannerList.push({name:response.data.name,url:response.data.url});
      }
    },
    handlePreviewFile(file){
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeBannerUpload(){
      // if(this.bannerList.length == 1){
      //   this.$message.error('当前封面图片只支持上传一张');
      //   return false;
      // }
    }
  }
};
</script>
