<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="list">
      <el-table-column
        label="版本"
        align="center"
        width="100"
        prop="version"
        :show-overflow-tooltip="true"
      />
       <el-table-column
        label="代码段"
        align="center"
        width="200"
        prop="pyCode"
        :show-overflow-tooltip="true"
      />
       <el-table-column
        label="开始时间"
        align="center"
        width="200"
        prop="startTime"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="结束时间"
        align="center"
        width="200"
        prop="endTime"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="文件地址"
        align="center"
        width="200"
        prop="filePath"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="onDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="shwoEdite(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNumber"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
    <el-dialog title="新增版本" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="版本">
              <el-input
                v-model="form.version"
                type="input"
                placeholder="请输入版本号"
              ></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="24">
            <el-form-item label="代码段">
              <el-input
                v-model="form.pyCode"
                 :autosize="{ minRows: 2, maxRows: 6 }"
                type="textarea"
                placeholder="请输入代码段"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
                placeholder="请选择开始时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"  
                placeholder="请选择结束时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="添加文件">
              <!-- <el-upload
                class="upload-demo"
                accept="file/*"
                ref="upload"
                :auto-upload="false"
                action="#"
                :show-file-list="false"
                :limit="1"
                :on-change="handleChange"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload> -->

                <el-upload
                multiple
                :action="uploadFileUrl"
                :before-upload="handleBeforeUpload"
                :limit="limit"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                :headers="headers"
                class="upload-file-uploader"
                ref="fileUpload"
                >
                <el-button size="mini" type="primary">选取文件</el-button>
                </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.filePath">
            <div>
             地址 <a :href="form.filePath" target="_blank">{{form.filePath}}</a>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onAdd">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑版本" :visible.sync="editOpen" width="600px" append-to-body>
      <el-form ref="editForm" :model="editForm" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="版本">
              <el-input
                v-model="editForm.version"
                type="input"
                placeholder="请输入版本号"
              ></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="24">
            <el-form-item label="代码段">
              <el-input
                v-model="editForm.pyCode"
                 :autosize="{ minRows: 2, maxRows: 6 }"
                type="textarea"
                placeholder="请输入代码段"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="editForm.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
                placeholder="请选择开始时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="editForm.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"  
                placeholder="请选择结束时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="添加文件">
              <!-- <el-upload
                class="upload-demo"
                accept="file/*"
                ref="upload"
                :auto-upload="false"
                action="#"
                :show-file-list="false"
                :limit="1"
                :on-change="handleChange"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload> -->

                <el-upload
                multiple
                :action="uploadFileUrl"
                :before-upload="handleBeforeUpload"
                :limit="limit"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                :headers="headers"
                class="upload-file-uploader"
                ref="fileUpload"
                >
                <el-button size="mini" type="primary">选取文件</el-button>
                </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="editForm.filePath">
            <div>
             地址 <a :href="editForm.filePath" target="_blank">{{editForm.filePath}}</a>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEdit">确定修改</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, deleteList, updateList, UrlFile } from "@/api/comfyui/index";
import { Loading } from "element-ui";
import { getToken } from "@/utils/auth";

export default {
  name: "comfyuiVersion",
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/file/fileUpload',
      limit: 1,
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      open: false,
      editOpen: false,
      form: {
        version: "",
        pyCode:'',
        startTime:null,
        endTime:null,
        filePath:''
      },
      displayText:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选择用户名
      selectName: "",
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 日期范围
      dateRange: [],
      // 默认排序
      defaultSort: { prop: "loginTime", order: "descending" },
      // 查询参数
      queryParams: {
        pageNumber: 1,
        pageSize: 10,
        ipaddr: undefined,
        userName: undefined,
        status: undefined,
      },
      deleteAllParams: [],
      editForm: {
        name: "",
        url: "",
        id: "",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleBeforeUpload(file) {
      console.log('file1',file);
      this.uploadLoading = true;  // 设置 loading 状态
      return true;  // 返回 true 允许上传
    },

    handleUploadError(error, file, fileList) {
      this.uploadLoading = false;
      this.$message.error('上传失败,请重新上传');
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },

    handleUploadSuccess(response, file, fileList) {
      if(this.open){
        this.form.filePath = response.data.path
      }else{
        this.editForm.filePath = response.data.path
      }
      this.uploadLoading = false;
      this.$refs.fileUpload.clearFiles();  // 清空上传组件的文件列表
    },

    handleTextAreaInput(value) {
      // this.displayText = value;
      // 实时更新存储值（可选，也可以只在change时更新）
      // this.form.text = 
      // const text = value.replace(/\n/g, "[BR]");
      this.form.pyCode = value;
    },

      // 表单提交时处理
    handleTextAreaChange(value) {
      // this.form.name = value.replace(/\n/g, "[BR]");
      // const text = value.replace(/\n/g, "[BR]");
      this.form.pyCode = value;
    },

    handleChange(file) {
      let loadingInstance = Loading.service({text:'正在上传图片'});
      const formData = new FormData();
      formData.append("file", file.raw); // 假设后端接收字段是 `file`
      UrlFile(formData).then((response) => {
        if (response.code === 200) {
          this.form.filePath = response.data;
        }
      }).finally(()=>{
        loadingInstance.close();
      })
      this.$refs.upload.clearFiles();
    },
    handleEditChange(file) {
      let loadingInstance = Loading.service({text:'正在上传图片'});
      const formData = new FormData();
      formData.append("file", file.raw); // 假设后端接收字段是 `file`
      UrlFile(formData).then((response) => {
        if (response.code === 200) {
          this.editForm.url = response.data;
        }
      }).finally(()=>{
        loadingInstance.close();
      })
      this.$refs.upload.clearFiles();
    },
    cancelEdit() {
      this.editOpen = false;
      this.editForm.name = "";
      this.editForm.url = "";
      this.editForm.id = "";
    },
    handleEdit() {
      updateList(this.addDateRange(this.editForm)).then((response) => {
        this.$modal.msgSuccess("编辑成功");
        this.getList();
        this.cancelEdit();
      }).catch((err)=>{
        debugger  
        this.$message.error('编辑失败,请重新编辑');
      });
    },
    shwoEdite(row) {
      this.editForm = JSON.parse(JSON.stringify(row))
      this.$nextTick(()=>{
        this.editOpen = true;
      })
    },

    handleAdd() {
      this.open = true;
    },
    cancel() {
      this.form.name = "";
      this.form.url = "";
      this.open = false;
    },
    handleUpdateStatus(row, status) {
      this.form.productId = row.productId;
      this.form.type = row.type;
      this.form.status = status;
      if (status === 1) {
        this.open = true;
      } else {
        updateStatus(this.addDateRange(this.form)).then((response) => {
          this.$modal.msgSuccess("已通过");
          this.getList();
        });
      }
    },

    onAdd() {
      add(this.addDateRange(this.form)).then((response) => {
        this.$modal.msgSuccess("添加成功");
        this.getList();
        this.cancel();
      });
    },
    /** 查询登录日志列表 */
    getList() {
      this.loading = true;
      list(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.list = response.data;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNumber = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.pageNumber = 1;
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
    },
    /** 多选框选中数据 */
    // handleSelectionChange(selection) {
    //   this.ids = selection.map((item) => item.infoId);
    //   this.single = selection.length != 1;
    //   this.multiple = !selection.length;
    //   this.selectName = selection.map((item) => item.userName);
    // },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 删除按钮操作 */
    onDelete(row) {
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return deleteList({id:row.id});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

  },
};
</script>
<style>
.addImg {
  width: 130px;
  height: 130px;
}
</style>
