<template>
  <div class="mt10 df aic jcsb mb20">
    <div>
      <el-button type="primary" class="mr30" @click="isModalVisable = true">
        添加版本记录
      </el-button>
      <el-popover placement="bottom" trigger="hover" :width="240">
        <div style="width: 100%; height: 80vh; overflow-y: scroll">
          <el-timeline>
            <el-timeline-item
              v-for="item in store.state.versions"
              center
              :timestamp="item.timer"
              placement="top"
            >
              <div class="log-card">
                <p style="margin-bottom: 10px">Version: {{ item.version }}</p>
                <div
                  style="margin-bottom: 5px; font-size: 12px"
                  v-for="(item1, index) in item.remarks"
                >
                  {{ index + 1 }}. {{ item1.text }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <template #reference>
          <el-badge value="new">
            <!-- <div class="log">新功能日志</div> -->
            <el-button>新功能日志</el-button>
          </el-badge>
        </template>
      </el-popover>
    </div>
    <div>
      <!-- <el-button @click="">返回版本记录列表</el-button>
      <el-button class="mr20 ml20" type="warning" @click="trash"
        >回收站</el-button
      > -->
    </div>

    <el-dialog
      title="版本管理"
      width="500px"
      v-model="isModalVisable"
      @closed="cancel"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="版本号" prop="version">
          <el-input style="width: 240px" v-model="ruleForm.version"></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="timer">
          <el-date-picker
            style="width: 240px"
            v-model="ruleForm.timer"
            type="date"
            placeholder="请选择日期"
            format="YYYY/MM/DD"
            value-format="YYYY/MM/DD"
          ></el-date-picker>
        </el-form-item>
        <hr class="mb20" />
        <el-form-item
          v-for="(item, index) in ruleForm.remarks"
          :label="'发布内容 ' + parseInt(index + 1) + ' :'"
          prop="remarks"
        >
          <div class="df aic jcsb">
            <el-input
              type="textarea"
              style="width: 240px"
              v-model="item.text"
              autosize
            ></el-input>
            <el-button size="small" @click="deleteRemark(index)" type="danger">
              删除
            </el-button>
          </div>
        </el-form-item>
        <div class="df aic jcfe">
          <el-button
            size="small"
            type="primary"
            @click="ruleForm.remarks.push({})"
          >
            添加一条记录
          </el-button>
        </div>
        <hr class="mt20 mb20" />
        <div class="df aic jcfe">
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="add(ruleFormRef)">提交</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
  <el-table :data="versions">
    <el-table-column
      type="index"
      label="序号"
      min-width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="version"
      label="版本号"
      min-width="100"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="timer"
      label="发布时间"
      min-width="100"
      align="center"
    ></el-table-column>
    <el-table-column label="版本内容" min-width="150" align="center">
      <template v-slot="scope">
        <div
          style="width: 100%; text-align: left"
          v-for="(item, index) in scope.row.remarks"
        >
          {{ index + 1 + ". " + item.text }}
        </div>
      </template>
    </el-table-column>
    <!-- <el-table-column label="状态" min-width="150" align="center">
      <template v-slot="scope">
        <el-switch
          v-model="scope.row.disabled"
          active-color="#13ce66"
          :active-value="false"
          :inactive-value="true"
          inactive-color="#ff4949"
          @change="changeSwitch($event, scope.row._id)"
        />
      </template>
    </el-table-column> -->
    <el-table-column label="操作" min-width="150" align="center">
      <template v-slot="scope">
        <el-button
          @click="detail(scope.row, scope.$index)"
          type="primary"
          size="small"
        >
          修改
        </el-button>
        <el-button
          @click="deleteItem(scope.row._id, scope.$index)"
          type="danger"
          size="small"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <div style="width: 100%; text-align: right; padding: 43px 0">
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="pageChange"
    ></el-pagination>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { AnonymousLogin, tcb } from "apis/cloudLogin";
import _ from "lodash";
import { ElMessage, ElMessageBox } from "element-plus";
import store from "../../store";
const db = tcb.database();
const v = db.collection("huihenduo_versions");
const __ = db.command;

let versions = ref([]);
let isModalVisable = ref(false);
let ruleFormRef = ref(null);
let currentPage = ref(1);
let pageSize = ref(10);
let currentVersionId = ref(null);
let total = ref(0);

function detail(item1) {
  let item = _.cloneDeep(item1);
  let { _id, version, timer, remarks } = item;
  currentVersionId.value = _id;
  ruleForm.value = { version, timer, remarks };

  isModalVisable.value = true;
}

async function deleteItem(_id) {
  ElMessageBox.confirm("确认删除版本日志?", "Warning", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await v.doc(_id).update({
        deleted: true,
      });
      getAllVersions();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
}

async function changeSwitch(disabled, id) {
  let res = await v.doc(id).update({
    disabled,
  });
  getAllVersions();
}

function deleteRemark(index) {
  ruleForm.value.remarks.splice(index, 1);
}

async function add() {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let res;
      for (let i in ruleForm.value.remarks) {
        if (!ruleForm.value.remarks[i].text) {
          ruleForm.value.remarks.splice(i, 1);
        }
      }
      if (currentVersionId.value) {
        res = await v.doc(currentVersionId.value).update({
          ...ruleForm.value,
          updateTime: db.serverDate(),
        });
      } else {
        res = await v.add({
          ...ruleForm.value,
          disabled: false,
          createTime: db.serverDate(),
        });
      }

      getAllVersions();
      cancel();
    } else {
      console.log("未提交", ruleForm.value);
    }
  });
}

async function getAllVersions(listType) {
  let res1 = await v.where({ deleted: __.neq(true) }).count();
  total.value = res1.total;
  let res = await v
    .aggregate()
    .match({ deleted: __.neq(true) })
    .sort({
      createTime: -1,
    })
    .skip((currentPage.value - 1) * pageSize.value)
    .limit(pageSize.value)
    .end();
  versions.value = res.data;
  getAbledVersions();
}

let abledVersions = ref([]);
async function getAbledVersions() {
  let res = await v
    .aggregate()
    .match({ deleted: __.neq(true) })
    .sort({
      createTime: -1,
    })
    .limit(10)
    .end();
  abledVersions.value = res.data;
  store.commit("setVersions", abledVersions.value);
}

function cancel() {
  isModalVisable.value = false;
  ruleForm.value = {
    version: "",
    timer: "",
    remarks: [{}, {}, {}],
  };
  currentVersionId.value = null;
}

let ruleForm = ref({
  version: "",
  timer: "",
  remarks: [{}, {}, {}],
});

const rules = reactive({
  version: [
    {
      required: true,
      message: "请填写版本号",
      trigger: "blur",
    },
  ],
  timer: [
    {
      required: true,
      message: "请填写发布时间",
      trigger: "blur",
    },
  ],
});
async function init() {
  await AnonymousLogin();
  getAllVersions();
}

function pageChange(e) {
  currentPage.value = e;
  getAllVersions();
}

onMounted(() => {
  init();
});
</script>

<style scoped></style>
