<template>
  <el-dialog v-loading="loading" :title="'修改表格需求'" :center="true" align="left" top="25vh" width="600px"
    :close-on-click-modal="false" :visible.sync="showModelThis" element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" @close="closeModel">
    <el-card style="margin: -20px 0 0 0">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rulesThis" label-width="90px"
            class="demo-ruleForm">
            <el-form-item label="业务表" prop="id">
              <el-select v-model="ruleForm.id" style="width: 100%" disabled placeholder="请选择业务表">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据时间" prop="start">
              <period-date-picker :start="ruleForm.start" :end="ruleForm.end" :type="type" :width="'199px'"
                :size="searchSize" @timeReturned="timeReturned($event)" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-alert style="width: 230px" :closable="false" :title="
            type === '2'
              ? '报表会在提交后开始执行！'
              : '报表会在明天01:00开始生成'
          " type="warning">
          </el-alert>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button v-if="!isDetail" type="primary" @click="submitForm">保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
          isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/reportQuery/financeReport/index.js";
import resToken from "@/mixins/resToken";
import PeriodDatePicker from "./components/PeriodDatePicker";
export default {
  name: "financeReport",
  props: ["showModel", "sitem", "type"],
  mixins: [resToken],
  components: {
    PeriodDatePicker,
  },

  data() {
    const validateTime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("数据开始时间不能为空！"));
      } else {
        if (this.ruleForm.end === "") {
          callback(new Error("数据结束时间不能为空！"));
        } else {
          callback();
        }
      }
    };
    return {
      options: [],
      loading: false,
      title: "添加账号",
      showModelThis: this.showModel,
      ruleForm: {
        start: "",
        end: "",
        id: "",
      },
      rulesThis: this.rules,
      rules: {
        start: [
          {
            required: true,
            validator: validateTime,
            trigger: "change",
          },
        ],
        id: [
          {
            required: true,
            message: "请选择业务表！",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    closeModel() {
      console.log("closeModel!!");
    },
    async initForm() {
      this.loading = true;
      this.options = [];
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    async timeReturned(e) {
      if (e.startTime !== "") {
        this.ruleForm.start = e.startTime;
      } else {
        this.ruleForm.start = "";
      }
      if (e.endTime !== "") {
        this.ruleForm.end = e.endTime;
      } else {
        this.ruleForm.end = "";
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { start, end, id, name } = this.sitem;
          // console.log(this.sitem);
          this.options = [
            {
              value: id,
              label: name,
            },
          ];
          this.ruleForm = {
            start: "",
            end: "",
            id: id || "",
          };
          console.log(this.ruleForm);
        }
      });
    },
    getDiffDay(date_1, date_2) {
      // 计算两个日期之间的差值
      let totalDays, diffDate
      let myDate_1 = Date.parse(date_1)
      let myDate_2 = Date.parse(date_2)
      // 将两个日期都转换为毫秒格式，然后做差
      diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
      totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
      return totalDays    // 相差的天数
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          const model = JSON.parse(JSON.stringify(this.ruleForm));
          const diffDays = this.getDiffDay(model.start,model.end);
          if(diffDays > 30) return this.$message.warning('数据时间间隔不能超过30天');
          
          this.loading = true;

          let res = await asyncRequest.add(model);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "需求创建成功！",
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh");
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.account {}
</style>
