<template>
  <el-drawer
    v-bind="$attrs"
    v-on="$listeners"
    :size="width"
    :visible.sync="visible"
    destroy-on-close
    :show-close="false"
    @close="useBack"
    @open="beforeOpen"
    v-loading="loading"
  >
    <div
      slot="title"
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>{{ title }}</h3>
      <div>
        <el-button
          v-if="openMode !== 'see'"
          type="primary"
          :size="size"
          @click="useSave('superForm')"
          >保存</el-button
        >
        <el-button :size="size" @click="useBack">取消</el-button>
      </div>
    </div>

    <el-super-form
      v-model="form"
      :dict="dict"
      :rules="rules"
      :size="$attrs.size"
      :columns="FormColumns"
      ref="superForm"
      label-width="auto"
      label-position="right"
      style="padding: 20px"
      :disabled="openMode == 'see'"
    >
    </el-super-form>

    <el-card style="margin: 10px 20px">
      <div style="position: relative">
        <el-tabs v-model="activeName" @tab-click="useSwitchTab">
          <el-tab-pane
            v-for="({ item, TableColumns: columns }, index) in TabColumns"
            :key="index"
            :label="item.title"
            :name="item.key"
            lazy
          >
            <el-super-ux-table
              index
              v-model="form[item.key]"
              :dict="dict"
              :ref="activeName"
              :columns="columns"
              :size="$attrs.size"
              :height="500"
            >
              <ux-table-column
                fixed="right"
                title="操作"
                align="center"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="openMode !== 'see'"
                    type="text"
                    :size="size"
                    @click="useRowRemove(scope.$index, scope.row)"
                    >删 行</el-button
                  >
                </template>
              </ux-table-column>
            </el-super-ux-table>
          </el-tab-pane>
        </el-tabs>
        <el-button
          @click="useResetCycle"
          v-if="activeName == 'cycles' && openMode !== 'see'"
          :size="size"
          style="position: absolute; right: 10px; top: 5px"
          >重算周期</el-button
        >
        <el-button
          @click="useRowAdd"
          v-if="
            (activeName == 'indexs' || activeName == 'dimensionalitys') &&
            openMode !== 'see'
          "
          :size="size"
          type="primary"
          style="position: absolute; right: 10px; top: 5px"
          >增行</el-button
        >
      </div>
    </el-card>
  </el-drawer>
</template>

<script>
import {
  addTargetTemplate,
  updateTargetTemplate,
  getTargetTemplate,
} from "@/api/business/spd/starget/targetTemplate";
import useColumns from "./columns";

export default {
  name: "targettemplateDetail",
  components: {
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
  },
  props: {
    openMode: {
      type: String,
      default: "add",
    },
    row: {
      type: [Object, Array],
      required: true,
    },
    dict: {
      type: Object,
    },
  },
  data() {
    const { FormColumns, TabColumns } = useColumns();
    const rules = this.$init.rules(FormColumns);
    const params = this.$init.params(FormColumns);
    return {
      visible: false,
      loading: false,
      width: "100%",
      size: "mini",
      rules,
      TabColumns,
      FormColumns,
      form: {
        ...params,
        indexs: [],
        dimensionalitys: [],
        cycles: [],
      },
      activeName: "indexs",
    };
  },
  computed: {
    title: {
      get() {
        const { openMode } = this;
        if (openMode === "edit") {
          return "编 辑";
        }
        if (openMode === "see") {
          return "查 看";
        }
        if (openMode === "add") {
          return "新 增";
        }
      },
      set() {},
    },
    indexs() {
      return this.form.indexs.filter(({ delFlag }) => delFlag !== "2");
    },
    dimensionalitys() {
      return this.form.dimensionalitys.filter(({ delFlag }) => delFlag !== "2");
    },
  },
  async created() {},
  methods: {
    setVisible(prop) {
      this.visible = prop;
    },
    async beforeOpen() {
      switch (this.openMode) {
        case "add":
          var date = new Date();
          this.form.year = date.getFullYear() + "-" + "01" + "-" + "01";
          this.form.startTime = date.getFullYear() + "-" + "01" + "-" + "01";
          this.form.deadlineTime = date.getFullYear() + "-" + "12" + "-" + "31";
          this.form.cycle = "month";
          break;
        case "edit":
          await this.fetchTemplate(this.row.id);
          break;
        case "see":
          let columns = _.cloneDeep(this.TabColumns);
          this.TabColumns = columns.map(({ item, attr, TableColumns }) => ({
            item,
            attr,
            TableColumns: TableColumns.map(({ item, attr }) => ({
              item,
              attr: {
                ...attr,
                disabled: true,
              },
            })),
          }));
          await this.fetchTemplate(this.row.id);
          break;
      }
    },
    //保存
    async useSave(prop) {
      this.$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            let checkRes = this.checkBeforeSave(this.form);
            if (!checkRes) {
              return;
            }
            this.loading = true;
            let res = null;
            if (this.openMode === "add") {
              res = await addTargetTemplate(this.form);
            }
            if (this.openMode === "edit") {
              res = await updateTargetTemplate(this.form);
            }
            if (res.code === 200) {
              this.$modal.msgSuccess("保存成功");
              this.useBack();
            }
          } catch (err) {
            console.error(err);
          } finally {
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    //保存前校验
    checkBeforeSave(form) {
      if (form.indexs) {
        let arr = form.indexs.filter((item) => item.delFlag != "2");
        if (arr.length < 1) {
          this.$modal.msgError("指标页签不能为空！");
          return false;
        }
        arr = arr.filter((item) => !item.target);
        if (arr.length > 0) {
          this.$modal.msgError("指标页签不能存在空数据！");
          return false;
        }
      } else {
        this.$modal.msgError("指标页签不能为空！");
        return false;
      }
      if (form.dimensionalitys) {
        let arr = form.dimensionalitys.filter((item) => item.delFlag != "2");
        if (arr.length < 1) {
          this.$modal.msgError("维度页签不能为空！");
          return false;
        }
        arr = arr.filter((item) => !item.dimensionality);
        if (arr.length > 0) {
          this.$modal.msgError("维度页签不能存在空数据！");
          return false;
        }
      } else {
        this.$modal.msgError("维度页签不能为空！");
        return false;
      }
      if (form.cycles) {
        let arr = form.cycles.filter((item) => item.delFlag != "2");
        if (arr.length < 1) {
          this.$modal.msgError("周期页签不能为空！");
          return false;
        }
      } else {
        this.$modal.msgError("周期页签不能为空！");
        return false;
      }
      return true;
    },
    //查询详情
    async fetchTemplate(id) {
      try {
        // try
        this.loading = true;
        const { code, data } = await getTargetTemplate(id);
        if (code === 200) {
          this.form = data;
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //增行
    async useRowAdd() {
      let row = {};
      if (this.activeName == "indexs") {
        row = {
          target: null,
        };
      }
      if (this.activeName == "dimensionalitys") {
        row = {
          dimensionality: null,
        };
      }
      this.form[this.activeName].push({
        delFlag: "0",
        $index: new Date().getTime(),
        ...row,
      });
      console.log("this.form[this.activeName]", this.form[this.activeName]);
    },
    //删行
    async useRowRemove(index, row) {
      if (row.id) {
        this.form[this.activeName].forEach((e) => {
          if (e.id == row.id) {
            e.delFlag = "2";
          }
        });
      } else {
        this.form[this.activeName].splice(index, 1);
      }
      console.log("this.form[this.activeName]", this.form[this.activeName]);
    },
    //切换多页签
    useSwitchTab() {},
    //返回
    useBack() {
      const { FormColumns, TabColumns } = useColumns();
      const params = this.$init.params(FormColumns);
      this.form = {
        ...params,
        indexs: [],
        dimensionalitys: [],
        cycles: [],
      };
      this.visible = false;
      this.TabColumns = TabColumns;
      this.activeName = "indexs";
      this.$emit("success");
    },
    //重算周期
    useResetCycle() {
      if (!this.form.startTime || !this.form.deadlineTime || !this.form.cycle) {
        this.$modal.msgError("开始日期、结束日期、周期不能存在空值！");
        return;
      }
      if (this.form.startTime > this.form.deadlineTime) {
        this.$modal.msgError("开始日期不能大于结束日期！");
        return;
      }
      this.form.cycles = [];
      var cycles = [];
      var start = new Date(this.form.startTime);
      var deadline = new Date(this.form.deadlineTime);
      start.setHours(0, 0, 0);
      deadline.setHours(0, 0, 0);
      if (this.form.cycle == "period") {
        cycles.push({
          name:
            new Date(start).Format("yyyy-MM-dd") +
            "到" +
            new Date(deadline).Format("yyyy-MM-dd"),
          startTime: new Date(start).Format("yyyy-MM-dd"),
          deadlineTime: new Date(deadline).Format("yyyy-MM-dd"),
        });
      } else {
        while (deadline >= start) {
          if (this.form.cycle == "day") {
            var cy = {
              name: new Date(start).Format("yyyy-MM-dd"),
              startTime: new Date(start).Format("yyyy-MM-dd"),
              deadlineTime: new Date(start).Format("yyyy-MM-dd"),
            };
            cycles.push(cy);
            start.setDate(start.getDate() + 1);
          }
          if (this.form.cycle == "week") {
            var cy = {};
            let date = new Date(start).Format("yyyy-MM-dd");
            cy.startTime = new Date(start).Format("yyyy-MM-dd");
            start.setDate(start.getDate() + 6);
            cy.deadlineTime = new Date(start).Format("yyyy-MM-dd");
            cy.name = date + "到" + new Date(start).Format("yyyy-MM-dd");
            cycles.push(cy);
            start.setDate(start.getDate() + 1);
          }
          if (this.form.cycle == "month") {
            var cy = {};
            cy.name = new Date(start).Format("yyyy-MM");
            cy.startTime = new Date(start).Format("yyyy-MM-dd");
            let arr = cy.startTime.split("-");
            start = this.getLastDay(arr[0], arr[1]);
            console.log("start", start);
            cy.deadlineTime = new Date(start).Format("yyyy-MM-dd");
            cycles.push(cy);
            start.setDate(start.getDate() + 1);
          }
          if (this.form.cycle == "season") {
            var cy = {};
            let date = new Date(start).Format("yyyy-MM");
            cy.startTime = new Date(start).Format("yyyy-MM-dd");
            start.setDate(start.getDate() + 90);
            cy.deadlineTime = new Date(start).Format("yyyy-MM-dd");
            cy.name = date + "到" + new Date(start).Format("yyyy-MM");
            cycles.push(cy);
            start.setDate(start.getDate() + 1);
          }
        }
        cycles[cycles.length - 1].deadlineTime = deadline;
      }
      this.form.cycles = cycles;
      console.log("this.form.cycles", this.form.cycles);
    },

    getLastDay(year, month) {
      return new Date(
        new Date(
          `${month < 12 ? year : ++year}-${month == 12 ? 1 : ++month} 00:00`
        ).getTime() - 1
      );
    },
  },
};
</script>

<style scoped>
>>> .el-drawer__header {
  margin-bottom: 0;
  padding: 5px 20px;
}
</style>
