<template>
  <div>
    <div class="select-box">
      <el-form :inline="true" :model="data.selectData" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="data.selectData.name" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="详情">
          <el-input
            v-model="data.selectData.description"
            placeholder="请输入关键字"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-button style="margin-left: 600px" type="primary" @click="onAdd"
            >新增算法</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="display-box">
      <el-table
        :data="dataList.comList"
        :border="parentBorder"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div m="5">
              <p m="t-0 b-2">算法ID: {{ props.row.algorithm_id }}</p>
              <p m="t-0 b-2">算法名称: {{ props.row.algorithm_name }}</p>
              <!-- <p m="t-0 b-2">所属领域: {{ props.row.fieldStr }}</p>
              <p m="t-0 b-2">适用场景: {{ props.row.userStr }}</p> -->
              <h3>算法详细描述</h3>
              <p m="t-0 b-2">{{ props.row.algorithm_description }}</p>
              <!-- <h3>算法详细描述</h3> -->
              <!-- <el-table :data="data.list" :border="childBorder"> -->
              <!-- <el-table-column label="算法名称" prop="name" />
                <el-table-column label="所属领域" prop="state" />
                <el-table-column label="应用场景" prop="city" />
                <el-table-column label="Address" prop="address" />
                <el-table-column label="Zip" prop="zip" /> -->
              <!-- </el-table> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="算法ID" prop="algorithm_id" />
        <el-table-column label="算法名称" prop="algorithm_name" />
        <el-table-column label="所属领域" prop="fieldList" />
        <el-table-column label="应用场景" prop="useList" />
        <el-table-column label="贡献者" prop="algorithm_coder" />
        <el-table-column label="算法封面">
          <template #default="scope">
            <div class="demo-image__lazy">
              <el-image :src="scope.row.algorithm_img" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >

            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="example-pagination-block">
        <el-pagination
          @current-change="currentChange"
          @size-change="sizeChange"
          layout="prev, pager, next"
          :total="data.selectData.count"
        />
      </div>
      <el-dialog v-model="data.isShow" title="编辑信息">
        <el-form :model="data.active">
          <el-form-item label="算法名称" label-width="100px">
            <el-input v-model="data.active.algorithm_name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="算法描述" label-width="100px">
            <el-input
              v-model="data.active.algorithm_description"
              autocomplete="off"
              autosize
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="算法贡献者" label-width="100px">
            <el-input
              v-model="data.active.algorithm_coder"
              autocomplete="off"
            />
          </el-form-item>

          <el-form-item label="所属领域" label-width="100px">
            <el-select
              v-model="data.active.fieldList"
              multiple
              placeholder="请选择应用领域"
              style="width: 240px"
            >
              <el-option
                v-for="item in data.fieldList"
                :key="item.field_id"
                :label="item.field_name"
                :value="item.field_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="应用场景" label-width="100px">
            <el-select
              v-model="data.active.useList"
              multiple
              placeholder="请选择应用领域"
              style="width: 240px"
            >
              <el-option
                v-for="item in data.useList"
                :key="item.usecase_id"
                :label="item.usecase_name"
                :value="item.usecase_name"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="上传图片"> -->
          <h1>上传算法图片</h1>
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="http://192.168.2.107:8080/api/file/upload"
            :show-file-list="false"
            :on-change="justselect"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            :data="{ algorithm_id: data.active.algorithm_id }"
          >
            <img
              v-if="data.active.algorithm_img"
              :src="data.active.algorithm_img"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <!-- </el-form-item> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.isShow = false">Cancel</el-button>
            <el-button type="primary" @click="updateAlgorithm">
              Confirm
            </el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="data.isAddShow" title="新增算法">
        <el-form :model="data.addList">
          <el-form-item label="算法名称" label-width="100px">
            <el-input
              v-model="data.addList.algorithm_name"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="算法描述" label-width="100px">
            <el-input
              v-model="data.addList.algorithm_description"
              autocomplete="off"
              autosize
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="算法贡献者" label-width="100px">
            <el-input
              v-model="data.addList.algorithm_coder"
              autocomplete="off"
            />
          </el-form-item>

          <el-form-item label="所属领域" label-width="100px">
            <el-select
              v-model="data.addList.fieldList"
              multiple
              placeholder="请选择应用领域"
              style="width: 240px"
            >
              <el-option
                v-for="item in data.fieldList"
                :key="item.field_id"
                :label="item.field_name"
                :value="item.field_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="应用场景" label-width="100px">
            <el-select
              v-model="data.addList.useList"
              multiple
              placeholder="请选择应用领域"
              style="width: 240px"
            >
              <el-option
                v-for="item in data.useList"
                :key="item.usecase_id"
                :label="item.usecase_name"
                :value="item.usecase_name"
              />
            </el-select>
          </el-form-item>
          <h1>上传算法图片</h1>
          <el-upload
            ref="uploadAddRef"
            class="avatar-uploader"
            action="http://192.168.2.107:8080/api/file/upload"
            :show-file-list="false"
            :on-change="justAddselect"
            :on-success="getReturnName"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            :data="{ algorithm_id: 999 }"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.isAddShow = false">Cancel</el-button>
            <el-button type="primary" @click="addAlgorithm">
              Confirm
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  getAllAlgorithm,
  getAllField,
  getAllUse,
  updatePostAlgorithm,
  addPostAlgorithm,
  deleteAlgorithm,
} from "@/request/api";
import { reactive, toRefs, ref, computed, watch } from "vue";
import { InitData } from "../type/algorithm";
import type { ALgorithmInt } from "../type/algorithm";
import { ElMessage, ElMessageBox } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import { Plus } from "@element-plus/icons-vue";

import type { UploadFile, UploadProps } from "element-plus";
const parentBorder = ref(true);
const childBorder = ref(true);
const data = reactive(new InitData());
const uploadRef = ref();
const uploadAddRef = ref();
let imageUrl = ref("");
const imgUrl = ref("");

// const handleAvatarSuccess: UploadProps["onSuccess"] = (
//   response,
//   uploadFile
// ) => {
//   data.active.algorithm_img = URL.createObjectURL(uploadFile.raw!);
// };
const justselect = (uploadFile: UploadFile) => {
  console.log("该百年");

  console.log(uploadFile.raw);

  data.active.algorithm_img = URL.createObjectURL(uploadFile.raw!);
};
const getReturnName: UploadProps["onSuccess"] = (response, file) => {
  console.log("打印防护");
  console.log(file.response);
  console.log(file.name); // 这里的 file.name 就是文件名
  if (typeof file.response === "string") {
    console.log("类型符合");

    imageUrl.value = "http://192.168.1.133:9000/algorithm/" + file.response;
  }
};
const justAddselect = (uploadFile: UploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw!);
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

//获取算法列表
getAllAlgorithm().then((res) => {
  data.list = res.data;
  console.log(res.data.length);

  console.log("打印展示列表");
  console.log(data.list);
  // 总条数
  data.selectData.count = res.data.length;
});
// 获取领域列表
getAllField().then((res) => {
  // console.log(res);
  data.fieldList = res.data;
});

getAllUse().then((res) => {
  console.log(res);
  data.useList = res.data;
});

// const data = reactive()
const dataList = reactive({
  comList: computed(() => {
    console.log("打印");
    console.log(data.list);

    return data.list.slice(
      (data.selectData.page - 1) * data.selectData.pagesize,
      data.selectData.page * data.selectData.pagesize
    );
  }),
});
const currentChange = (page: number) => {
  data.selectData.page = page;
};

const sizeChange = (pagesize: number) => {
  data.selectData.pagesize = pagesize;
};

const onSubmit = () => {
  // console.log(data.selectData.name);
  // console.log(data.selectData.description);
  // 定义查询之后要展示的数据
  let arr: ALgorithmInt[] = [];
  if (data.selectData.name || data.selectData.description) {
    if (data.selectData.name) {
      arr = data.list.filter((value) => {
        return value.algorithm_name.indexOf(data.selectData.name) !== -1;
      });
    }
    if (data.selectData.description) {
      arr = data.list.filter((value) => {
        return (
          value.algorithm_description.indexOf(data.selectData.description) !==
          -1
        );
      });
    }
  } else {
    arr = data.list;
  }
  data.selectData.count = arr.length;
  data.list = arr;
};
// 监听输入框属性
watch([() => data.selectData.name, () => data.selectData.description], () => {
  if (data.selectData.name == "" && data.selectData.description == "") {
    getAllAlgorithm().then((res) => {
      data.list = res.data;
      // console.log(res.data.length);

      // console.log("打印展示列表");
      // console.log(data.list);
      // 总条数
      data.selectData.count = res.data.length;
    });
  }
});
const handleEdit = (row: ALgorithmInt) => {
  // data.active = row
  // console.log(row);
  data.active = {
    algorithm_id: row.algorithm_id,
    algorithm_name: row.algorithm_name,
    algorithm_description: row.algorithm_description,
    fieldStr: "",
    userStr: "",
    fieldList: row.fieldList,
    useList: row.useList,
    algorithm_img: row.algorithm_img,
    algorithm_coder: row.algorithm_coder,
  };
  data.isShow = true;
};

const handleDelete = (row: ALgorithmInt) => {
  ElMessageBox.confirm(
    "proxy will permanently delete the file. Continue?",
    "Warning",
    {
      confirmButtonText: "OK",
      cancelButtonText: "Cancel",
      type: "warning",
    }
  )
    .then(() => {
      // console.log("打印要删除算法");
      // console.log(row);
      deleteAlgorithm(row).then((res) => {
        if (res.status == 200) {
          getAllAlgorithm().then((res) => {
            data.list = res.data;
            // console.log(res.data.length);

            // console.log("打印展示列表");
            // console.log(data.list);
            // 总条数
            data.selectData.count = res.data.length;
          });
          ElMessage({
            type: "success",
            message: "Delete completed",
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

const updateAlgorithm = async () => {
  console.log("打印所选值");
  console.log(dataList.comList);
  await uploadRef.value.submit();
  await new Promise((resolve) => setTimeout(resolve, 500));
  updatePostAlgorithm(data.active).then((res) => {
    console.log(res);

    console.log(data.active);
    getAllAlgorithm().then((res) => {
      data.list = res.data;
      console.log("打印展示图片后的数据");
      console.log(data.list);
      console.log("fg");

      console.log(dataList.comList);

      // console.log(res.data.length);

      // console.log("打印展示列表");
      // console.log(data.list);
      // 总条数
      data.selectData.count = res.data.length;
    });
  });
  data.isShow = false;
};

const onAdd = () => {
  data.isAddShow = true;
  data.addList.algorithm_description = "";
  data.addList.algorithm_name = "";
  data.addList.fieldList = [];
  data.addList.useList = [];
  data.addList.algorithm_img = "";
  imgUrl.value = "";
  // console.log("打印datalist");
  // console.log(dataList.comList);
};

const addAlgorithm = async () => {
  console.log("打印前addlist");

  console.log(data.addList);

  await uploadAddRef.value.submit();
  await new Promise((resolve) => setTimeout(resolve, 700));
  data.addList.algorithm_img = imageUrl.value;
  // data.addList.algorithm_img =
  console.log("打印后");
  console.log(imageUrl.value);

  console.log(data.addList.algorithm_img);

  console.log(data.addList);

  console.log("开始发送请求");

  addPostAlgorithm(data.addList).then((res) => {
    console.log("day");

    console.log(data.addList);

    console.log(res);

    getAllAlgorithm().then((res) => {
      data.list = res.data;
      // console.log(res.data.length);

      // console.log("打印展示列表");
      // console.log(data.list);
      // 总条数
      data.selectData.count = res.data.length;
    });

    data.isAddShow = false;
  });
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
