<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="sceneModeId">
        <el-select v-model="queryParams.sceneModeId" placeholder="场景类型" clearable>
          <el-option
            v-for="item in SceneModeName"
            :key="item.sceneModeId"
            :label="item.sceneModeName"
            :value="item.sceneModeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="isNeedTenant"
        label="租户" prop="tenantId">
        <el-select v-model="queryParams.tenantId" placeholder="租户" clearable>
          <el-option
            v-for="item in TenantName"
            :key="item.tenantId"
            :label="item.tenantName"
            :value="item.tenantId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否默认" prop="defaultFlag">
        <el-select v-model="queryParams.defaultFlag" placeholder="是否默认" clearable>
          <el-option
            v-for="dict in dict.type.hw_scene_default_flag"
            :key ="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="场景名称" prop="sceneName">
        <el-input
          v-model="queryParams.sceneName"
          placeholder="请输入场景名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="sceneName">
        <el-input
          v-model="queryParams.sceneName"
          placeholder="请输入内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人电话" prop="sceneName">
        <el-input
          v-model="queryParams.sceneName"
          placeholder="请输入内容"
          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="['business:scene: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="['business:scene: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="['business:scene: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="['business:scene:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sceneList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="场景ID" align="center" prop="sceneId" />-->
      <el-table-column label="场景名称" align="center" prop="sceneName" />
      <el-table-column label="所属租户" align="center" prop="tenantName" >

      </el-table-column>
      <el-table-column label="场景类型" align="center" prop="sceneModeName" />
      <el-table-column label="是否默认" align="center" prop="defaultFlag" >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.hw_scene_default_flag"
            :value="scope.row.defaultFlag"
          >
          </dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="场景描述" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="测试数据保留周期（天）" align="center" prop="testPreserveTime" />
      <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="['business:scene:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:scene: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="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="场景名称" prop="sceneName">
          <el-input v-model="form.sceneName" placeholder="请输入场景名称" />
        </el-form-item>
<!--        ，关联hw_tenant的tenant_id-->
<!--        <el-form-item label="租户ID" prop="tenantId">-->
<!--          <el-input v-model="form.tenantId" placeholder="请输入租户ID，关联hw_tenant的tenant_id" />-->
<!--        </el-form-item>-->
        <el-form-item label="所属租户" >
          <el-select v-model="form.tenantId" placeholder="请选择租户">
            <el-option
              v-for="item in TenantName"
              :key="item.tenantId"
              :label="item.tenantName"
              :value="item.tenantId">
            </el-option>
          </el-select>
        </el-form-item>
<!--        ，关联表hw_scene_mode的scene_mode_id-->
<!--        <el-form-item label="场景类型" prop="sceneModeId">-->
<!--          <el-input v-model="form.sceneModeId" placeholder="请输入场景类型，关联表hw_scene_mode的scene_mode_id" />-->
<!--        </el-form-item>-->
        <el-form-item label="场景类型" >
          <el-select v-model="form.sceneModeId" placeholder="请选择场景类型">
            <el-option
              v-for="item in SceneModeName"
              :key="item.sceneModeId"
              :label="item.sceneModeName"
              :value="item.sceneModeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="认证方式" >
          <el-select v-model="form.authMode" placeholder="请选择认证方式">
            <el-option
              v-for="dict in dict.type.hw_scene_auth_mode"
              :key ="dict.value"
              :label="dict.label"
              :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认" >
          <el-radio-group v-model="form.defaultFlag">
            <el-radio
              v-for="dict in dict.type.hw_scene_default_flag"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="场景图片地址" prop="scenePic">
              <el-upload
                single
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                :limit="limit"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                ref="imageUpload"
                :on-remove="handleDeletes"
                :show-file-list="true"
                :headers="headers"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.fileList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>

              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>

              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>

        </el-form-item>
        <el-form-item label="保存周期（天）" prop="preserveTime">
          <el-input v-model="form.preserveTime" placeholder="请输入保存周期(单位：天）默认90天" />
        </el-form-item>
        <el-form-item label="测试环境保存周期（天）" prop="testPreserveTime">
          <el-input v-model="form.testPreserveTime" placeholder="请输入测试环境保存周期(单位：天）默认30天" />
        </el-form-item>
        <el-form-item label="场景描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </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>
    <el-dialog :title="title" :visible.sync="open1" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="场景名称" prop="sceneName">
          <el-input v-model="form.sceneName" placeholder="请输入场景名称" />
        </el-form-item>
        <!--        ，关联hw_tenant的tenant_id-->
        <!--        <el-form-item label="租户ID" prop="tenantId">-->
        <!--          <el-input v-model="form.tenantId" placeholder="请输入租户ID，关联hw_tenant的tenant_id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="所属租户" >

          <el-select v-model="form.tenantId" placeholder="请选择租户" disabled="disabled" >
            <el-option
              v-for="item in TenantName"
              :key="item.tenantId"
              :label="item.tenantName"
              :value="item.tenantId">
            </el-option>
          </el-select>
        </el-form-item>
        <!--        ，关联表hw_scene_mode的scene_mode_id-->
        <!--        <el-form-item label="场景类型" prop="sceneModeId">-->
        <!--          <el-input v-model="form.sceneModeId" placeholder="请输入场景类型，关联表hw_scene_mode的scene_mode_id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="场景类型" >
          <el-select v-model="form.sceneModeId" placeholder="请选择场景类型">
            <el-option
              v-for="item in SceneModeName"
              :key="item.sceneModeId"
              :label="item.sceneModeName"
              :value="item.sceneModeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="认证方式" >
          <el-select v-model="form.authMode" placeholder="请选择认证方式">
            <el-option
              v-for="dict in dict.type.hw_scene_auth_mode"
              :key ="dict.value"
              :label="dict.label"
              :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认" >
          <el-radio-group v-model="form.defaultFlag">
            <el-radio
              v-for="dict in dict.type.hw_scene_default_flag"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="场景图片地址" prop="scenePic">
          <el-upload
            single
            :action="uploadImgUrl"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload"
            :limit="limit"
            :on-error="handleUploadError"
            :on-exceed="handleExceed"
            ref="imageUpload"
            :on-remove="handleDeletes"
            :show-file-list="true"
            :headers="headers"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :class="{hide: this.fileList.length >= this.limit}"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <!-- 上传提示 -->
          <div class="el-upload__tip" slot="tip" v-if="showTip">
            请上传
            <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
            的文件
          </div>

          <el-dialog
            :visible.sync="dialogVisible"
            title="预览"
            width="800"
            append-to-body
          >
            <img
              :src="dialogImageUrl"
              style="display: block; max-width: 100%; margin: 0 auto"
            />
          </el-dialog>
        </el-form-item>

        <el-form-item label="场景key" prop="modeKey" >
          <el-input   v-model="form.modeKey" disabled="disabled" />
        </el-form-item>
        <el-form-item label="场景secret" prop="modeSecret">
          <el-input v-model="form.modeSecret" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="保存周期（天）" prop="preserveTime">
          <el-input v-model="form.preserveTime" placeholder="请输入保存周期(单位：天）默认90天" />
        </el-form-item>
        <el-form-item label="测试环境保存周期（天）" prop="testPreserveTime">
          <el-input v-model="form.testPreserveTime" placeholder="请输入测试环境保存周期(单位：天）默认30天" />
        </el-form-item>
        <el-form-item label="场景描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </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 { listScene, getScene, delScene, addScene, updateScene ,getSceneModeName,getTenantName,getIsNeedTenant} from "@/api/business/scene";
import { getToken } from "@/utils/auth";

export default {
  name: "Scene",
  dicts: ['sys_user_sex','hw_scene_default_flag','hw_scene_auth_mode'],
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //
      TenantName:"",
      SceneModeName:"",
      // 总条数
      total: 0,
      // 场景信息表格数据
      sceneList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      //
      isNeedTenant:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sceneName: null,
        tenantId: null,
        sceneModeId: null,
        scenePic: null,
        defaultFlag: null,
        sceneStatus: null,
        authMode: null,
        modeAccount: null,
        modeKey: null,
        modeSecret: null,
        preserveTime: null,
        testPreserveTime: null,
        sceneEnvironment: null,
        sceneField: null
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        sceneName: [
          { required: true, message: "场景名称不能为空", trigger: "blur" }
        ],
        sceneModeId: [
          { required: true, message: "场景类型，关联表hw_scene_mode的scene_mode_id不能为空", trigger: "blur" }
        ],
        defaultFlag: [
          { required: true, message: "是否默认不能为空", trigger: "blur" }
        ],
        // sceneStatus: [
        //   { required: true, message: "状态不能为空", trigger: "change" }
        // ],
        // authMode: [
        //   { required: true, message: "认证方式不能为空", trigger: "blur" }
        // ],
        // modeKey: [
        //   { required: true, message: "场景key不能为空", trigger: "blur" }
        // ],
        // modeSecret: [
        //   { required: true, message: "场景secret不能为空", trigger: "blur" }
        // ],
        // preserveTime: [
        //   { required: true, message: "保存周期(单位：天）默认90天不能为空", trigger: "blur" }
        // ],
        // testPreserveTime: [
        //   { required: true, message: "测试环境保存周期(单位：天）默认30天不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.getList();
    this.getSceneModeName();
    this.getTenantName();
    this.getIsNeedTenant();
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.data.url, url: res.data.url });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDeletes(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        // this.$emit("input", this.listToString(this.fileList));
      }
      this.form.scenePic = '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.form.scenePic = this.fileList[0].url;
        this.$modal.closeLoading();
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    /** 查询场景信息列表 */
    getList() {
      this.loading = true;
      listScene(this.queryParams).then(response => {
        // console.log(response)
        this.sceneList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sceneId: null,
        sceneName: null,
        tenantId: null,
        tenantName: null,
        TenantName:null,
        sceneModeId: null,
        sceneModeName: null,
        scenePic: null,
        defaultFlag: "0",
        sceneStatus: null,
        authMode: null,
        modeAccount: null,
        modeKey: null,
        modeSecret: null,
        preserveTime: null,
        testPreserveTime: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        sceneEnvironment: null,
        sceneField: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sceneId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = [];
      this.reset();
      this.open = true;
      this.title = "添加场景信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = [];

      this.reset();

      const sceneId = row.sceneId || this.ids
      getScene(sceneId).then(response => {
        if (response.data.scenePic != null) {
          let previewFile = {};
          previewFile.url = response.data.scenePic
          this.fileList.push(previewFile);
        }
        this.form = response.data;
        this.open1 = true;
        this.title = "修改场景信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sceneId != null) {
            updateScene(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open1 = false;
              this.getList();
            });
          } else {
            addScene(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // this.createTdeDb("db_scene_"+form.sceneId);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sceneIds = row.sceneId || this.ids;
      this.$modal.confirm('是否确认删除场景信息编号为"' + row.sceneName + '"的数据项？').then(function() {
        return delScene(sceneIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/scene/export', {
        ...this.queryParams
      }, `scene_${new Date().getTime()}.xlsx`)
    },
    getSceneModeName() {
      getSceneModeName().then(response => {
        console.log(response)
        this.SceneModeName = response.rows;
      });
    },
    getTenantName() {
      getTenantName().then(response => {
        console.log(response)
        this.TenantName = response.rows;
      });
    },
    getIsNeedTenant(){
      getIsNeedTenant().then(response => {{
        // console.log("??????????????????????"+response)
        this.isNeedTenant = response;
        // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+this.isNeedTenant)
      }})
    },
  }
};
</script>
