<template>
  <div class="page">
    <div class="top">
      <div class="topLeft" @click="clickBack">
        <img src="./img/rollback.png" style="margin-right: 8px" /><span>返回</span>
      </div>
      <div class="topRight">
        <span >{{ OperationTypeNames[pageType] }}报表配置</span>
      </div>
    </div>
    <div class="content">
      <div class="left">
        <el-form ref="ruleFormRef" style="max-width: 1000px" :model="form" :rules="rules" label-width="auto"
          class="demo-ruleForm" :size="formSize" :label-position="labelPosition">
          <el-form-item v-if="form.type === PushMessageTypeEnum.DESIGNEE_ACCESS_DATA" label="指定人员:" required prop="designatedUserList" style="width: 660px"
            :rules="{ required: true, message: '请选择人员', trigger: 'change' }">
            <el-col :span="18">
              <DesignatedPersonSelection :form="form" :disableType="disableType" />
            </el-col>
          </el-form-item>

          <el-form-item label="报表周期：" prop="statisticType" required>
            <el-radio-group v-model="form.statisticType" :disabled="disableType.statisticTypeDisable">
              <StatisticOption
                v-for="option in ReportOptions"
                :key="option.value"
                :value="option.value"
                :tooltip-content="option.tooltipContent"
                :tooltip-placement="option.tooltipPlacement"
                :label="option.label"
              />
            </el-radio-group>
          </el-form-item>

          <component :is="currentComponent" :form="form" :disableType="disableType" />
          <div v-if="Number(form.statisticType) === StatisticTypeEnum.CUSTOM_REPORT" class="custom-report">
            <CustomReport ref="CustomReportComponent" :form="form" :disableType="disableType"
              :ruleFormRef="ruleFormRef">
            </CustomReport>
          </div>

          <el-form-item label="推送渠道：" prop="pushChannel" required>
            <el-checkbox-group v-model="form.pushChannel" :disabled="disableType.contentDisable">
              <el-col :span="2">
                <el-checkbox :value="1" name="channel"> 蓝信推送 </el-checkbox>
              </el-col>
              <el-col :span="2">
                <el-checkbox :value="2" name="channel"> 平台推送 </el-checkbox>
              </el-col>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="操作人：" style="margin-left: 10px">
            <el-input style="width: 425px; margin-left: -10px" disabled :placeholder="operater" />
          </el-form-item>
        </el-form>
        <div class="two-btns">
          <el-button @click="clickBack">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)" :disabled="disableType.contentDisable">
            确定
          </el-button>
        </div>
      </div>
      <div class="right">
        <TemplateExample :form="form" :disableType="disableType"></TemplateExample>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onBeforeMount, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormProps } from 'element-plus';
import { debounce } from 'lodash-es';
import { addMassage, searchMassage, editMassage } from '@/api/message/report-message';
import { useUserStore } from '@/store/modules/user';
import { useFormList } from './store/useFormList';
import { reportMessage, toReportMessage, reportMessageToFinal } from './class';
import { OperationTypeEnum, StatisticTypeEnum, OperationTypeNames, PushMessageTypeEnum, Default_Value,ReportOptions } from '@/types/message/constant';
import StatisticOption from "./components/StatisticOption.vue";
import DesignatedPersonSelection from './components/DesignatedPersonSelection.vue';
import TemplateExample from './TemplateExample.vue';
import WeekReport from './WeekReport.vue';
import MonthReport from './MonthReport.vue';
import YearReport from './YearReport.vue';
import CustomReport from './CustomReport.vue';

const labelPosition = ref<FormProps['labelPosition']>('left');
const useUser = useUserStore();
const FormList = useFormList();
const { info } = storeToRefs(useUser);
const { type } = storeToRefs(FormList);
let operater = info.value.realname;
let disableType = ref({ statisticTypeDisable: false, contentDisable: false }); // 控制是否可编辑
const formSize = ref('default'); // 校验表单
const ruleFormRef = ref();
const route = useRoute();
const router = useRouter();
// 功能类型：1是新增，2是查询，3是编辑
const pageType = ref<number>(route.query.operationType ? Number(route.query.operationType) : Default_Value);
// 报表类型：1是违规报警，2是平台访问，3是指定人员访问
const reportType = ref<number>(route.query.type ? Number(route.query.type) : Default_Value);
// 统计时间段类型：1-周报 2-月报 3-季报 4-年报 5-自定义
const statisticType = ref<number>(
  route.query.statisticType ? Number(route.query.statisticType) : Default_Value,
);
let queryType = { type: reportType.value, statisticType: statisticType.value };

const form = reactive<reportMessage>({
  configIdList: null,
  type: Default_Value,
  statisticType: Default_Value,
  monthAndDayList: ['1', '1'],
  dayOfWeek: 1,
  monthList: [''],
  dayOfMonthList: ['1'],
  pushTimeList: ['09:00:00'],
  pushChannel: [],
  userGroupList: [],
  designatedUserList: [],
  recipientType: undefined,
  customPushConfigList: [],
  customUserList: [],
});


// 根据报表周期展示不同组件
const ComponentEnum = {
  [StatisticTypeEnum.WEEK_REPORT]: WeekReport,
  [StatisticTypeEnum.MONTH_REPORT]: MonthReport,
  [StatisticTypeEnum.YEAR_REPORT]: YearReport,
}

// 当前组件
const currentComponent = computed(() => ComponentEnum[form.statisticType]);

form.customUserList.value = []; // 防止进入页面开始就显示校验错误
form.designatedUserList = [];

const rules = reactive({
  statisticType: [{ required: true, message: '请选择统计时间段', trigger: 'change, blur' }],
  pushChannel: [{ required: true, message: '请选择推送渠道', trigger: 'change' }],
  dayOfWeek: [{ required: true, message: '请选择推送日期', trigger: 'change' }],
  dayOfMonthList: [{ required: true, message: '请选择推送日', trigger: 'change' }],
  recipientType: [{ required: true, message: '请选择推送对象', trigger: ['blur', 'change'] }],
  userGroupList: [{ required: true, message: '请选择推送分组', trigger: 'change' }],
});

const addDebounce = debounce((form) => {
  addMassage(form).then(() => {
    ElMessage.success('新增成功');
    clickBack();
  });
}, 500);

const editDebounce = debounce((form) => {
  editMassage(form).then(() => {
    ElMessage.success('修改成功');
    clickBack();
  });
}, 500);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      let submitForm = reportMessageToFinal(form);
      if (pageType.value != OperationTypeEnum.EDIT) {
        addDebounce(submitForm);
      } else {
        editDebounce(submitForm);
      }
    } 
  });
};

const clickBack = () => {
  type.value = reportType.value;
  router.back();
};

const getDisableType = (pageType) => {
  if (pageType === OperationTypeEnum.ADD) {
    // 新增
    disableType.value.statisticTypeDisable = false;
    disableType.value.contentDisable = false;
  } else if (pageType === OperationTypeEnum.SEARCH) {
    // 查询
    disableType.value.statisticTypeDisable = true;
    disableType.value.contentDisable = true;
  } else if (pageType === OperationTypeEnum.EDIT) {
    // 编辑
    disableType.value.statisticTypeDisable = true;
    disableType.value.contentDisable = false;
  }
};

onBeforeMount(() => {
  getDisableType(pageType.value);
  if (pageType.value === OperationTypeEnum.SEARCH || pageType.value === OperationTypeEnum.EDIT) {
    searchMassage(queryType).then((res) => {
      toReportMessage(form, res);
      return res;
    });
  }
  form.type = reportType.value;
});
</script>

<style lang="scss" scoped>
.page {
  height: calc(100vh - 64px - 18px);
  background-color: rgba(255, 255, 255, 1);

  .top {
    display: flex;
    padding: 16px 0 15px 20px;
    border-bottom: 1px solid #e9e9e9;

    .topLeft {
      display: flex;
      align-items: center;
      cursor: pointer;

      a {
        display: flex;
        align-items: center;
      }
    }

    .topRight {
      margin-left: 20px;
    }
  }

  .content {
    display: flex;
    height: calc(100vh - 130px);

    .left {
      display: flex;
      flex-direction: column;
      position: relative;
      padding: 20px 0 0 32px;
      width: 769px;
      border-right: 1px solid rgba(0, 0, 0, 0.06);
      overflow-y: auto;

      .custom-report {
        max-height: calc(100vh - 450px);
        overflow-y: auto;
      }

      .two-btns {
        position: absolute;
        right: 33px;
        bottom: 32px;
      }
    }

    .right {
      height: 299px;
      width: 363px;
      margin-left: 31px;
      margin-top: 20px;
      background: #ffffff;
      border-radius: 4px 4px 0px 0px;
      border: 1px solid #e9e9e9;
    }
  }
}
</style>
