<script setup lang="ts">
import { shallowRef, ref, onMounted, nextTick, watch } from "vue";
import BusinessQuery from "/@/components/BasicForm/src/fields/business-permission/index.vue";
import DepartQuery from "/@/components/BasicForm/src/fields/depart.vue";
import { useUserStore } from "/@/store/modules/user";
import { ElForm, ElMessage } from "element-plus";
import { isBeyondTime } from "../../_utils";
import apis from "./config/apis";
import dayjs from "dayjs";

defineProps<{ isBusiness?: boolean }>();

const emit = defineEmits(["refresh"]);

const visible = shallowRef(false);
const loading = shallowRef(false);

const deraptNameRef = ref("");
const userStore = useUserStore();
const departQueryRef = ref<InstanceType<typeof DepartQuery> | null>(null);
const businessQueryRef = ref<InstanceType<typeof BusinessQuery> | null>(null);
const execList = ref<Array<Record<string, string>>>([]);

const createInitialData = () => ({
  date: [],
  exec_id: "2",
  companyNo: "",
  depart_id: "0",
  plat_type: "",
  exec_type: "1"
});

const rules = {
  date: [{ required: true, message: "请选择数据时间", trigger: "change" }],
  exec_id: [{ required: true, message: "请输入业务表", trigger: "change" }],
  depart_id: [{ required: true, message: "请选择所在部门", trigger: "change" }],
  plat_type: [{ required: true, message: "请选择平台类型", trigger: "change" }],
  companyNo: [{ required: true, message: "请选择业务公司", trigger: "change" }],
  exec_type: [{ required: true, message: "请选择执行类型", trigger: "change" }]
};

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const formData = ref({ ...createInitialData() });

async function onSubmit() {
  console.log(formData.value)

  try {
    await formRef.value?.validate();
    const { date, ...rest } = formData.value;
    loading.value = true;

    if (String(rest.exec_type) === "1") {
      const beyondTime = isBeyondTime({
        message: "立即执行时，时间区间不能超过31天！",
        start: date[0],
        end: date[1],
        len: 31
      });
      if (beyondTime) return;
    } else {
      const beyondTime = isBeyondTime({
        message: "延迟执行时，时间区间不能超过62天！",
        start: date[0],
        end: date[1],
        len: 62
      });
      if (beyondTime) return;
    }

    const end1 = dayjs(date[1]).subtract(-1, "days");
    const end = dayjs(end1).subtract(1, "days").format("YYYY-MM-DD");

    const response = await apis.create_exec({
      start: date[0] + " 00:00:00",
      end: end + " 23:59:59",
      ...rest
    });

    loading.value = false;

    if (response.code === 1) {
      visible.value = false;
      emit("refresh");
    } else {
      ElMessage.warning(response.message);
    }
  } catch (error) {
    console.log(error);
  }
}

function handleClose() {
  formData.value = createInitialData();
  visible.value = false;
}

onMounted(async () => {
  const response = await apis.exce_list({
    size:100
  });
  if (response.code !== 1) return;
  execList.value = response.data.list;
});


defineExpose({
  onDisplay: companyNo => {
    console.log(companyNo);
    visible.value = true;
    nextTick(() => (companyNo && businessQueryRef.value) && businessQueryRef.value.initialData(companyNo));
  }
});
</script>

<template>
  <el-dialog v-model="visible" title="修改报表需求" center @close="handleClose">
    <el-form label-width="90px" :rules="rules" :model="formData" ref="formRef">
      <el-form-item label="业务表:" prop="exec_id">
        <el-select
          v-model="formData.exec_id"
          style="width: 100%"
          placeholder="业务表"
          disabled
        >
          <el-option
            v-for="exec in execList"
            :key="exec.id"
            :label="exec.exec_name"
            :value="exec.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="数据时间:" prop="date">
        <el-date-picker
          v-model="formData.date"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>

      <el-form-item label="执行类型" prop="exec_type">
        <el-select
          v-model="formData.exec_type"
          placeholder="执行类型"
          style="width: 100%"
        >
          <el-option value="1" label="立即执行" />
          <el-option value="2" label="延迟执行" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="所在部门" prop="depart_id">
        <depart-query ref="departQueryRef" v-model="formData.depart_id" />
      </el-form-item> -->

      <el-form-item label="业务公司" prop="companyNo" v-if="isBusiness">
        <business-query
          ref="businessQueryRef"
          :not-initial="true"
          disabled
          v-model="formData.companyNo"
        />
      </el-form-item>

      <el-form-item>
        <div class="w-full flex justify-between">
          <el-alert
            type="warning"
            style="width: 260px; margin-right: 10px; padding: 0px"
            size="small"
            :closable="false"
            v-if="String(formData.exec_type) === '1'"
          >
            立即执行:文件会在申请后几分钟内生成;
          </el-alert>

          <el-alert
            type="warning"
            style="width: 260px; margin-right: 10px; padding: 0px"
            size="small"
            :closable="false"
            v-if="String(formData.exec_type) === '2'"
          >
            延迟执行:文件会在申请当天20:00开始执行;
          </el-alert>

          <el-button class="float-right" type="primary" @click="onSubmit"
            >保存</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
