<script setup lang="ts">
import { ref, reactive, nextTick, Ref, watch, onMounted } from "vue";
import { ElMessageBox, ElMessage, FormRules } from "element-plus";
import { getDictTypeList } from "../../api/common";
import dayjs from "dayjs";
import {
  getList,
  postGenerateReport,
  getReportDate,
  postDeleteBatch,
} from "../../api/monitoring/report";
import { handleGetIndex } from "../../utils/tools";
import { usePermissions } from "../../composables/usePermissions";
import { useRouter } from "vue-router";
const { permissionsButtons } = usePermissions();
const router = useRouter();
usePermissions();
const butomData = ref([]);
onMounted(() => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  console.log(butomData, "butomData");

  getButton();
  search("loading");
  init();
});

/**
 *@description: 初始化
 */
const init = () => {
  getDictTypeList({ dictType: "时间段类型" }).then((res = []) => {
    const i = handleGetIndex(serchColumns, "key", "timePeriodType");
    const j = handleGetIndex(formColumns, "key", "timePeriodType");
    const timeTypeArr: any = [];
    res.forEach((item) => {
      timeTypeArr.push({
        value: item.dictValue,
        label: item.dictValue,
      });
    });
    serchColumns[i].options = timeTypeArr;
    formColumns[j].options = timeTypeArr;
  });
  // getDictTypeList({ dictType: "报告类型" }).then((res = []) => {
  //   const i = handleGetIndex(serchColumns, "key", "type");
  //   const j = handleGetIndex(formColumns, "key", "type");
  //   const reportTypeArr = [];
  //   res.forEach((item) => {
  //     reportTypeArr.push({
  //       value: item.dictValue,
  //       label: item.dictValue,
  //     });
  //   });
  //   let reportTypeArrCopy = JSON.parse(JSON.stringify(reportTypeArr));
  //   reportTypeArrCopy.shift();
  //   formColumns[j].options = reportTypeArr;
  //   serchColumns[i].options = reportTypeArrCopy;
  // });
  // let year = dayjs(new Date()).year();
  // let month = dayjs(new Date()).month();
  // let arr = [];
  // let i = 12;
  // while (i > 0) {
  //   if (month === 0) {
  //     month = 12;
  //     year--;
  //   }
  //   arr.push({
  //     value: `${year}年${month}月`,
  //     label: `${year}年${month}月`,
  //   });
  //   month--;
  //   i--;
  // }
  // const j = handleGetIndex(formColumns, "key", "month");
  // formColumns[j].options = arr;
};

let getButton = () => {
  let i = handleGetIndex(column, "prop", "oparation");
  console.log(column, "permissionsButtons", butomData);
  if (butomData.value.indexOf("预览") > -1) {
    let j = handleGetIndex(column[i].buttons, "title", "预览");
    column[i].buttons[j].hide = false;
  }
  if (butomData.value.indexOf("生成报告") > -1) {
    rightButtons.value.push({
      text: "生成报告",
      type: "primary",
      eventName: function () {
        resetFormData();
        drawerProps.showDrawer = true;
      },
    });
  }
  if (butomData.value.indexOf("删除") > -1) {
    let j = handleGetIndex(column[i].buttons, "title", "删除");
    column[i].buttons[j].hide = false;
    leftButtons.value.push({
      text: "批量删除",
      plain: true,
      eventName: function () {
        batchDelete();
      },
    });
  }
};

const serchColumns = reactive([
  {
    key: "time",
    type: "daterange",
    label: "时间范围",
    valueFormat: "YYYY-MM-DD",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
    col: 8,
  },
  // {
  //   key: "type",
  //   type: "select",
  //   label: "报告类型",
  //   options: [],
  //   clearable: true,
  //   col: 8,
  // },
  {
    key: "timePeriodType",
    type: "select",
    label: "时间段类型",
    options: [],
    clearable: true,
    col: 8,
  },
]);
const leftButtons = ref([]);
const rightButtons = ref([]);
const tableData = ref([]);
// 查询初始化
const initSearch = () => {
  page.value = 1;
  search();
};
const search = (loading?) => {
  let _data = JSON.parse(JSON.stringify(serchformData));
  delete _data.time;
  if (serchformData.time) {
    _data.startTime =
      serchformData.time[0] && serchformData.time[0] + " 00:00:00";
    _data.endTime =
      serchformData.time[1] && serchformData.time[1] + " 23:59:59";
  }
  _data.pageSize = pageSize.value;
  _data.pageNum = page.value;
  if (_data.type === "全部") {
    _data.type = "";
  }
  _data.yaLoading = loading;
  getList(_data).then((res) => {
    nextTick(() => {
      tableData.value = res.data.rows;
      total.value = res.data.total;
    });
  });
};
const serchformData = reactive({
  type: "",
  timePeriodType: "",
  time: [],
});

let initFromData = () => {
  page.value = 1;
  return {
    type: "",
    timePeriodType: "",
    time: [],
  };
};

// 重置
const reset = () => {
  Object.assign(serchformData, initFromData());
  search();
};

const tableBtnClick = (btn, row) => {
  btn.eventName(row);
};

let selectData = ref([]);

// 列表删除
const batchDelete = (id) => {
  if (!id && selectData.value.length == 0) {
    ElMessage.warning("请选择要批量删除的数据");
    return;
  }

  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    let idValue = (id && [id]) || [];
    if (!id && selectData.value.length) {
      selectData.value.forEach((item) => {
        idValue.push(item.id);
      });
    }
    postDeleteBatch(idValue).then((res) => {
      if (res.code == 200) {
        // page.value = 1;
        ElMessage.success("删除成功");
        search();
      }
    });
  });
};

// 表头定义
const column: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "name",
    label: "报告名称",
  },
  // {
  //   prop: "reportType",
  //   label: "报告类型",
  //   minWidth: "140px",
  // },
  {
    prop: "timePeriodType",
    label: "时间段类型",
  },
  {
    prop: "createTime",
    label: "生成时间",
  },
  {
    prop: "oparation",
    label: "操作",
    width: "150px",
    // align: "center",
    fixed: "right",
    buttons: [
      {
        title: "预览",
        hide: true,
        eventName: function (row) {
          handleGoPdf(row.id);
        },
      },
      {
        title: "删除",
        hide: true,
        eventName: function (row) {
          batchDelete(row.id);
        },
      },
    ],
  },
];

// 跳转pdf模板页
const handleGoPdf = (id) => {
  router.push("./report/detail?id=" + id);
  // window.open(`/#/pdfTemplate?id=${id}`);
};

const handleSelectionChange = function (val) {
  selectData.value = val;
};

const page = ref(1);
const total = ref(0);
const pageSize = ref(20);
const sizeChange = function (val: Number) {
  pageSize.value = val;
  page.value = 1;
  search();
};

const currentChange = function (val: Number) {
  page.value = val;
  search();
};

const formData = reactive({
  timePeriodType: "",
  // type: "",
  month: [],
});

/**
 * @describtion 表单数据初始化
 */
const resetFormData = () => {
  formData.timePeriodType = "";
  // formData.type = "";
  formData.month = [];
};

const formColumns = reactive([
  // {
  //   key: "type",
  //   type: "select",
  //   label: "报告类型",
  //   disabled: false,
  //   col: 24,
  //   placeholder: "请选择报告类型",
  //   options: [],
  //   clearable: true,
  // },
  {
    key: "timePeriodType",
    type: "select",
    label: "时间段类型",
    disabled: false,
    onChange(e) {
      handleReportDate(e);
    },
    col: 24,
    placeholder: "请选择时间段类型",
    options: [],
    clearable: true,
  },
  {
    key: "month",
    type: "select",
    label: "统计时间段",
    hide: true,
    disabled: false,
    col: 24,
    multiple: true,
    placeholder: "请选择统计时间段",
    options: [],
    clearable: true,
  },
]);

// 获取时间段
const handleReportDate = (type) => {
  getReportDate({ dateType: type }).then((res) => {
    const { code, data } = res || {};
    if (code === 200 && Array.isArray(data)) {
      const j = handleGetIndex(formColumns, "key", "month");
      const timeArr = data.map((item) => {
        return {
          label: item,
          value: item,
        };
      });

      formColumns[j].options = timeArr;
    }
  });
};

const rules = reactive<FormRules>({
  // type: [{ required: true, message: "请选择报告类型", trigger: "change" }],
  timePeriodType: [
    { required: true, message: "请选择时间段类型", trigger: "change" },
  ],
  month: [{ required: false, message: "请选择统计时间段", trigger: "change" }],
});

// 控制时间段显示
watch(
  () => formData.timePeriodType,
  (val) => {
    formData.month = [];
    const i = handleGetIndex(formColumns, "key", "month");
    formColumns[i].hide = true;
    nextTick(() => {
      const hideBool = val === "年度";
      if (!hideBool) {
        rules.month![0].required = true;
      }
      formColumns[i].hide = hideBool;
    });
  }
);

let dialogForm = ref();
let beforeOpen = () => {
  nextTick(() => {
    dialogForm.value.resetForm();
  });
};

let drawerProps = reactive({
  showDrawer: false,
  title: "生成报告",
  size: "small",
});

// 关闭抽屉
const handleCloseDrawer = async (done) => {
  if (dialogForm.value) {
    await dialogForm.value.resetForm(dialogForm.value.ruleFormRef);
  }
  done();
};

// 抽屉事件
const handleEvent = function (data) {
  if (data.eventName == "errorSubmit") {
    return;
  } else if (data.eventName == "success") {
    handleConfirm();
    return;
  } else if (data.eventName == "successSubmit") {
    handleSubmit();
    return;
  }
};

// 表单事件
// const handleFormEvent = (data) => {
//   if (data.eventName == ""successSubmit"") {
//     handleSubmit();
//     return;
//   }
// };

/**
 * @description 生成报告
 */
const handleSubmit = () => {
  console.log(formData);
  postGenerateReport(formData).then((res) => {
    const { code, data = [] } = res;
    if (code === 200) {
      ElMessage.success("生成报告成功");
      drawerProps.showDrawer = false;
      page.value = 1;
      search();
    }
  });
};

// 表单确认
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
</script>

<template>
  <div>
    <YaPageContent :formData="serchformData" :formColumns="serchColumns" :tableData="tableData" :tableColumns="column"
      :leftButtons="leftButtons" searchLabelWidth="90px" :rightButtons="rightButtons" @search="initSearch" @reset="reset"
      @tableBtnClick="tableBtnClick" @selectionChange="handleSelectionChange" :currentPage="page" :pageSize="pageSize"
      :total="total" @sizeChange="sizeChange" @currentChange="currentChange">
    </YaPageContent>
    <ya-drawer v-if="drawerProps.showDrawer" :drawerProps="drawerProps" @handleEvent="handleEvent" destroy-on-close
      :before-close="handleCloseDrawer">
      <template #content>
        <ya-form label-position="top" @handleEvent="handleEvent" :formColumns="formColumns" labelWidth="100px"
          :formData="formData" :rules="rules" :ref="(el) => {
            if (el) dialogForm = el;
          }
            ">
        </ya-form>
      </template>
    </ya-drawer>
  </div>
</template>
