<template>
  <div class="app-container">
    <el-card v-show="!visiable" class="card" :body-style="{ height: '100%', maxWidth: '1000px' }">
      <div class="main">
        <div class="form" v-show="step === 1">
          <BaseForm ref="form" :isPreview="isPreview"/>
        </div>
        <template v-if="step === 2">
          <el-form>
            <el-form-item label="随访任务" prop="tasks" required>
              <span style="color: #f56c6c; font-size: 12px">
                单个任务最多添加10个待办事项（5篇患教文章+5个随访问卷）
              </span>
            </el-form-item>
          </el-form>
          <el-card class="tasks">
            <FollowTaskSetting :maxDays="maxDays" :isPreview="isPreview" v-model="tasks" @selectTodo="handleSelectTodo" />
          </el-card>
        </template>
      </div>
      <div class="footer">
        <el-button @click="handleBack">取消</el-button>
        <el-button key="next" type="primary" v-if="step === 1" @click="handleNextStep">
          下一步
        </el-button>
        <template v-else>
          <el-button key="prev" type="warning" @click="handlePrevStep" plain>上一步</el-button>
          <template v-if="!isPreview"><!--非预览展示操作按钮-->
            <el-button type="primary" @click="handleSaveDrafts" plain>保存草稿</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </template>
        </template>
      </div>
    </el-card>
    <el-collapse-transition>
      <TodoItemSelector ref="todoSelector" :form="formData" />
    </el-collapse-transition>
  </div>
</template>
<script>
import { addFollowUpPlan, updateFollowUpPlan, getPlanDetail } from "@/api/hospital";
import BaseForm from "./components/BaseForm";
import TodoItemSelector from "./components/TodoItemSelector";
import FollowTaskSetting from "./components/FollowTaskSetting";
export default {
  name: "AddPlan",
  enums: ["periodUnitMap", "surveyTempMap"],
  components: {
    BaseForm,
    FollowTaskSetting,
    TodoItemSelector,
  },
  data() {
    return {
      step: 1,
      formData: {},
      tasks: [],
      maxDays: 0, // 随访周期
      editId: this.$route.params.id,
      isPreview: this.$route.params.isPreview, // 预览标记 'preview'
      visiable: false,
    };
  },
  created() {
    if (this.editId) {
      this.getDetail();
    }
  },
  computed: {
    saveParams() {
      return {
        ...this.formData,
        followTaskTemplates: this.tasks.map((task, index) => {
          return {
            ...task,
            batchNo: index + 1,
            items: task.items.map((item, i) => {
              return {
                ...item,
                serialNo: i + 1,
              };
            }),
          };
        }),
      };
    },
  },
  methods: {
    getDetail() {
      getPlanDetail(this.editId).then((res) => {
        const { taskList, ...params } = res.data;
        this.tasks = taskList;
        this.$refs.form.init(params);
      });
    },
    // 取消
    handleBack() {
      this.$tab.closePage(undefined, { name: "PlanManage" });
    },
    // 上一步
    handlePrevStep() {
      this.step = 1;
    },
    // 下一步
    handleNextStep() {
      this.$refs.form.submit().then((data) => {
        this.formData = { ...data };
        this.maxDays = this.getDays(this.formData.periodNumber, this.formData.periodUnit);
        this.step = 2;
      });
    },
    // 选择待办事项
    handleSelectTodo(index) {
      const curTask = this.tasks[index];
      this.visiable = true;
      this.$refs.todoSelector
        .open(curTask.items)
        .then((items) => {
          this.tasks.splice(index, 1, {
            ...curTask,
            items,
          });
          this.visiable = false;
        })
        .catch(() => {
          this.visiable = false;
        });
    },
    validate() {
      if (this.tasks.length === 0) {
        this.$message.error("随访任务不能为空");
        return false;
      }
      let preTime = 0;
      for (const [index, task] of this.tasks.entries()) {
        if (typeof task.lagNumber !== "number") {
          this.$message.error(`第${index + 1}次随访任务[基线时间+]未选择`);
          return false;
        }
        if (task.items.length === 0) {
          this.$message.error(`第${index + 1}次随访任务未添加待办事项`);
          return false;
        }
        if (task.lagNumber < preTime) {
          this.$message.error(
            `第${index + 1}次随访任务[基线时间+]不能小于${index === 0 ? "0" : "前一次"}`
          );
          return false;
        }
        preTime = task.lagNumber;
        if (task.lagNumber >= this.maxDays) {
          this.$message.error(`随访任务[基线时间+]超过了随访总周期`);
          return false;
        }
      }

      return true;
    },
    getDays(periodNumber, periodUnit) {
      switch (periodUnit) {
        case this.periodUnitMap.day:
          return periodNumber;
          break;
        case this.periodUnitMap.month:
          return periodNumber * 30;
          break;
        case this.periodUnitMap.year:
          return periodNumber * 30 * 12;
          break;
      }
    },
    // 保存草稿
    handleSaveDrafts() {
      this.save(this.surveyTempMap.drafts);
    },
    // 提交
    handleSubmit() {
      this.save(this.surveyTempMap.save);
    },
    async save(status) {
      if (!this.validate()) return;
      const api = this.editId ? updateFollowUpPlan : addFollowUpPlan;
      const res = await api({
        ...this.saveParams,
        id: this.editId,
        status,
      });
      // 保存成功页面不跳转，再次保存即编辑
      if (!this.editId) {
        this.editId = res.data.id;
      }
      if (status === this.surveyTempMap.save) {
        this.$message.success("提交成功");
        this.handleBack();
      } else {
        this.$message.success("保存成功");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  height: 100%;
  .card {
    height: 100%;
  }
  .main {
    height: calc(100% - 100px);
    .tasks {
      height: calc(100% - 50px);
      overflow-y: auto;
      ::v-deep .el-step__description {
        padding-right: 0 !important;
      }
    }
  }

  .footer {
    margin-top: 50px;
    text-align: center;
  }
}
</style>
