<template>
  <!-- 项目管理弹框 -->
  <el-dialog v-model="dialogVisible" title="项目管理" width="1600px">
    <!-- <el-card class="transparent-card"> -->
    <div style="display: flex; justify-content: space-between">
      <div>
        <span style="width: 80px; color: #fff">项目名称</span>
        <el-input
          v-model.trim="projectName"
          maxlength="32"
          placeholder="请输入项目名称"
          show-word-limit
          clearable
          style="width: 240px; margin-left: 10px"
          size="small"
        />
      </div>
      <div>
        <el-button :icon="Search" size="small" type="primary" @click="onSearch">
          查询</el-button
        >
        <!-- <el-button :icon="RefreshLeft" size="small" @click="onReset"
          >重置</el-button
        > -->
        <el-button :icon="Plus" size="small" type="primary" @click="onSubmitadd"
          >新增</el-button
        >
      </div>
    </div>
    <!-- </el-card> -->
    <div
      style="
        overflow-x: hidden;
        overflow-y: scroll;
        padding: 0 10px;
        margin-top: 10px;
        height: 660px;
      "
      v-loading="loading"
      :element-loading-background="'rgba(122, 122, 122, 0.8)'"
    >
      <el-row :gutter="12">
        <el-col
          :span="6"
          v-for="item in projectData"
          :key="item.id"
          class="mt10"
        >
          <el-card class="box-card" @click="querdata(item)" shadow="hover">
            <div slot="header" class="clearfix">
              <span style="display: flex; align-items: center; color: #fff"
                >{{ item.name }}

                <el-tooltip
                  class="item"
                  effect="dark"
                  content="修改项目"
                  placement="top"
                >
                  <el-icon
                    :size="20"
                    class="color"
                    style="cursor: pointer; margin-left: 5px"
                  >
                    <Edit @click="editd(item)" />
                  </el-icon>
                </el-tooltip>

                <!-- <el-tooltip
                  class="item"
                  effect="dark"
                  content="修改项目"
                  placement="top"
                >
                  <Edit
                    style="margin-left: 5px; width: 16px"
                    class="xiaoshou color"
                    @click="editd(item)"
                  /> </el-tooltip
              > -->
              </span>
              <div style="display: flex; justify-content: end">
                <el-button
                  v-if="item.active == 0"
                  class="color"
                  :icon="Compass"
                  style="padding: 3px 0"
                  type="text"
                  @click="activeItem(item)"
                  >激活</el-button
                >
                <el-button
                  v-else
                  class="color"
                  style="padding: 3px 0; color: #82bd51"
                  type="text"
                  >已激活</el-button
                >
                <el-button
                  class="color"
                  :icon="Share"
                  style="padding: 3px 0"
                  type="text"
                  @click="Aclick(item)"
                  >设计</el-button
                >

                <el-button
                  :icon="Delete"
                  style="padding: 3px 0; color: #c93434"
                  type="text"
                  @click="deleted(item)"
                  >删除</el-button
                >
              </div>
            </div>
            <img
              v-if="item.fileContent"
              :src="item.fileContent"
              class="image xiaoshou"
              @click="imgData(item)"
            />
            <el-empty v-else description="暂无设计" style="height: 220px" />
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
      </div>
    </template> -->
    <div class="table-pagination">
      <el-pagination
        small
        :currentPage="params.pageNum"
        :page-size="params.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        background
        :layout="'sizes,total, ->, prev, pager, next, jumper'"
        :total="params.total"
        @size-change="onTableSizeChange"
        @current-change="onTableCurrentChange"
      ></el-pagination>
    </div>
  </el-dialog>
  <!-- 新增弹框 -->
  <el-dialog v-model="innerVisible" :title="dialogTitle" width="500px">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="ruleForm.name"
          maxlength="32"
          show-word-limit
          placeholder="请输入项目名称"
        />
      </el-form-item>
      <!-- <el-form-item label="工程项目" prop="projectIds">
        <el-select
          v-model="ruleForm.projectIds"
          placeholder="请选择"
          :popper-append-to-body="false"
          popper-class="custom-select-dropdown"
        >
          <el-option label="Zone one111" value="shanghai" />
          <el-option label="Zone two" value="beijing" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="项目排序" prop="orderBy">
        <el-input v-model="ruleForm.orderBy" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="ruleForm.remark" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button size="small" @click="resetForm">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
} from "vue";
import {
  Search,
  RefreshLeft,
  Plus,
  Share,
  Delete,
  Edit,
  Compass,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  projectList,
  add,
  edit,
  active,
  getActive,
} from "@/api/manage_wx/index";

const emit = defineEmits<{
  (e: "project-change", project: { id: string; name: string }): void;
}>();

const projectData = ref([]);

// 系统配置弹框
const dialogVisible = ref(false);

const innerVisible = ref(false);
const loading = ref(false);

const projectName = ref("");

const dialogTitle = ref("新增项目");

const firstForm = ref({
  name: "",
  id: "",
});

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

interface RuleForm {
  name: string;
  projectIds: [];
  orderBy: string;
  remark: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  name: "",
  projectIds: [],
  orderBy: "100",
  remark: "",
});

const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  projectIds: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  orderBy: [
    {
      required: true,
      message: "请输入项目排序",
      trigger: "change",
    },
  ],
});

onMounted(() => {
  fetachData();
});

// 创建一个专门发送数据到 iframe 的函数
const sendToIframe = (type: string, data: any) => {
  try {
    // 确保数据可以被序列化
    const serializableData = JSON.parse(JSON.stringify(data));

    window.parent.postMessage(
      {
        type: type,
        data: serializableData,
      },
      "*"
    );
  } catch (error) {
    console.error("发送到 iframe 失败:", error);
  }
};

const fetachData = async () => {
  loading.value = true;
  const res = await projectList({
    pageNum: params.pageNum,
    pageSize: params.pageSize,
    searchValue: projectName.value,
  });
  // projectData.splice(0, projectData.length, ...res.records);
  projectData.value = res.data.records;
  params.total = res.data.total;
  loading.value = false;
  if (res.data.records.length > 0) {
    firstForm.value.id = res.data.records[0].id;
    firstForm.value.name = res.data.records[0].name;
  }
};

// 查询
const onSearch = () => {
  fetachData();
};

// 重置
const onReset = () => {
  projectName.value = "";
  fetachData();
};

// 新增
const onSubmitadd = () => {
  innerVisible.value = true;
  dialogTitle.value = "新增项目";
  // Object.assign(ruleForm, {});   不生效
  Object.assign(ruleForm, {
    //生效，但是一个个赋值，麻烦
    id: "0944fe372e90daeefd040916a105ac8b",
    name: "",
    orderBy: "100",
    projectIds: ["1dd1b076e104f15459ac401fc1b902c4"],
    remark: "",
  });
  //Object.keys(ruleForm).forEach((key) => delete ruleForm[key]); //生效，但是有默认值的，一进去会直接报校验
};

const querdata = (e: any) => {};

// 编辑修改
const editd = (row: any) => {
  innerVisible.value = true;
  dialogTitle.value = "修改项目";
  // Object.assign(ruleForm, row);
  Object.assign(ruleForm, {
    id: row.id,
    name: row.name,
    orderBy: row.orderBy,
    projectIds: row.projectIds,
    remark: row.remark,
  });
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (dialogTitle.value == "新增项目") {
        getAdd();
      } else {
        getEdit();
      }
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const getAdd = async () => {
  // const params = { ...ruleForm, id: "0944fe372e90daeefd040916a105ac8b" };
  const res: any = await add(ruleForm);
  if (res.code == "A0000") {
    ElMessage({
      type: "success",
      message: "新增成功!",
    });
    innerVisible.value = false;
    fetachData();
  } else {
    ElMessage({
      type: "error",
      message: res.message,
    });
  }
};

const getEdit = async () => {
  const res: any = await edit(ruleForm);
  if (res.code == "A0000") {
    ElMessage({
      type: "success",
      message: "修改成功!",
    });
    innerVisible.value = false;
    fetachData();
  }
};

const resetForm = () => {
  innerVisible.value = false;
};

const onTableSizeChange = (size: number) => {
  params.pageSize = size;
  //emit("refreshData"); // 触发父组件方法
  fetachData();
};

const onTableCurrentChange = (page: number) => {
  params.pageNum = page;
  //emit("refreshData"); // 触发父组件方法
  fetachData();
};

// 设计
const Aclick = (e: any) => {
  // window.open( window.location.origin + `/zutai/?id=${e.id}&&name=decodeURI(${e.name})&&flag=false`)
  // window.open(
  //   window.location.origin  +
  //     `/zutai/?id=${e.id}&&name=${e.name}&&preview=false&&graphicDisplay=true`
  // );
  // 无锡项目进去不展示数据绑定图元
  window.open(
    window.location.origin +
      `/zutai/?id=${e.id}&&name=${e.name}&&preview=false&&graphicDisplay=wx`
  );
};
// 删除
const deleted = (e: any) => {
  ElMessageBox.confirm("此操作将永久删除该项目, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = {
        id: e.id,
        name: e.name,
        status: "0",
      };
      edit(data).then((res: any) => {
        if (res.code == "A0000") {
          ElMessage({
            type: "success",
            message: "删除项目成功!",
          });
        }
        fetachData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

const imgData = (e: any) => {
  // window.open(window.location.origin + `/zutai/?id=${e.id}&&name=decodeURI(${e.name})&&flag=true`)
  // window.open(
  //  window.location.origin  +
  //     `/zutai/?id=${e.id}&&name=${e.name}&&preview=true#/preview`
  // );
  window.open(
    window.location.origin +
      `/zutai/?id=${e.id}&&name=${e.name}&&preview=true&&graphicDisplay=wx#/preview`
  );
};

// 获取激活
const getActiveItem = () => {
  getActive({}).then((res: any) => {
    if (res.code == "A0000") {
      // 通知父组件
      emit("project-change", {
        id: res.data.id,
        name: res.data.name,
      });
    }
  });
};

// 激活
const activeItem = (item: any) => {
  ElMessageBox.confirm("是否确认激活该项目?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = {
        id: item.id,
      };
      active(data).then((res: any) => {
        if (res.code == "A0000") {
          ElMessage({
            type: "success",
            message: "激活成功!",
          });
        }
        fetachData().then(() => {
          getActiveItem();
        });
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消激活",
      });
    });
};

const open = () => {
  dialogVisible.value = true;
};
defineExpose({
  open,
});
</script>
<style lang="scss">
.custom-select-dropdown {
  // background-color: transparent !important;
  width: 510px;
}

.custom-select-dropdown .el-select-dropdown__list {
  // background-color: transparent !important;
  width: 500px;
}
</style>

<style lang="scss" scoped>
.item {
  margin-bottom: 18px;
}

.image {
  display: block;
  width: 100%;
  height: 220px;
}

.clearfix::before,
.clearfix::after {
  display: table;
  content: "";
}

.clearfix::after {
  clear: both;
}
.box-card {
  width: 100%;
  // box-shadow: var(--el-box-shadow-light)
  background-color: transparent; /* 设置背景颜色为透明 */
  border: 1px solid gray; /* 添加边框，可以根据需要调整颜色和宽度 */
  box-shadow: 0 2px 8px gray; /* 添加边框阴影 */
}

.transparent-card {
  background-color: transparent; /* 设置背景颜色为透明 */
  border: 1px solid gray; /* 添加边框，可以根据需要调整颜色和宽度 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 添加边框阴影 */
}

.xiaoshou {
  cursor: pointer;
}
.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}

.color {
  color: var(--el-color-primary);
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-tree) {
  padding-top: 15px;
  padding-left: 10px;

  // 不可全选样式
  .el-tree-node {
    .is-leaf + .el-checkbox .el-checkbox__inner {
      display: inline-block;
    }

    .el-checkbox .el-checkbox__inner {
      display: none;
    }
  }
}

:deep(.el-card__header) {
  padding: 13px 10px;
  height: 44px;
}

.table-pagination {
  box-sizing: border-box;
  width: 100%;
  max-width: 100%;
  background-color: var(--ba-bg-color-overlay);
  padding: 10px;
}

:deep(.el-pagination__sizes) {
  .el-select {
    min-width: 128px;
  }
}

:deep(.el-form-item .el-form-item__label) {
  color: #fff;
}

// :deep(.el-input__wrapper) {
//   background-color: transparent !important;
// }

// :deep(.el-select__wrapper) {
//   background-color: transparent !important;
// }

// :deep(.el-textarea__inner) {
//   background-color: transparent !important;
// }

// :deep(.el-input .el-input__count .el-input__count-inner) {
//   background-color: transparent !important;
//   display: inline-block;
//   line-height: normal;
//   padding-left: 8px;
// }
</style>
