<template>
  <div class="follow-task">
    <el-row v-show="!showItemsTable" :gutter="20" style="width: 100%">
      <el-col :span="12" class="itemsTable-box">
        <el-card class="left-card">
          <el-steps direction="vertical" :active="value.length + 1">
            <el-step v-for="(item, index) in value" :key="index" style="flex-basis: auto">
              <template slot="title">
                <div style="display: flex; align-items: center">
                  <span>第{{ index + 1 }}次随访任务</span>
                  <span class="ml10" style="font-size: 14px; color: #cccccc">基线时间+</span>
                  <div class="ml10">
                    <el-input-number v-if="isPreview" size="mini" v-model="item.lagNumber"
                      disabled></el-input-number>
                    <el-input-number v-else size="mini" v-model="item.lagNumber"
                      v-bind="getTaskTimeRange(item, index)"
                      @change="changeNumber(item,index)"></el-input-number>
                    <span class="ml5" style="font-size: 12px; color: #000">天</span>
                  </div>
                </div>
              </template>
              <template slot="description">
                <el-table :data="item.items" :ref="'previewTemplateTable'+index" border
                  emptyText="暂无待办事项" highlight-current-row class="mt10"
                  @current-change="handleCurrentChange(index,$event)">
                  <el-table-column align="center" property="targetType" label="待办类型">
                    <template slot-scope="scope">
                      {{ todoItemTypeEnum.getLabel(scope.row.targetType) }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" property="targetName" label="名称" />
                  <el-table-column v-if="!isPreview" align="center" label="操作">
                    <template slot-scope="scope">
                      <el-button class="color-red" size="mini" type="text"
                        @click="hanldeDelTodoItem(scope.$index, index)" v-if="!isPreview">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button v-if="item.items.length < 10 && !isPreview" @click="handleAddTodo(index)"
                  class="mb20" type="primary" style="width: 100%">
                  添加待办事项
                </el-button>
              </template>
            </el-step>
          </el-steps>
          <div v-if="!isPreview" class="operation-btn" style="width:100%;text-align: center">
            <el-button type="default" class="btn-style" @click="cancel">取消</el-button>
            <el-button type="primary" class="btn-style" @click="sureSelectedItem">保存</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="11" :offset="1">
        <el-card>
          <ArticlePreview v-if="previewData.targetType === todoItemTypeMap.article" style="height: 100%;"
          :articleId="previewData.targetId" :isTemp="true" />
          <DWViewer v-else-if="previewData.targetType === todoItemTypeMap.survey" :url="url" />
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>
<script>
import ArticlePreview from "@/components/ArticlePreview";
import DWViewer from "@/components/DWViewer";
export default {
  enums: ["todoItemTypeEnum", "periodUnitMap", "todoItemTypeMap"],
  components: {
    ArticlePreview,
    DWViewer,
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    maxDays: {
      type: Number,
    },
    isPreview: {
      // 预览标记
      type: Boolean,
      default: false,
    },
  },
  computed: {
    url() {
      return `${process.env.VUE_APP_SURVEY_PREFIX}/survey/diaowen-m.html?surveyId=${this.previewData.surveyId}&sid=&tag=p-auth-0&t=${new Date().getTime()}`;
    },
  },
  watch: {
    value(newVal, oldVal) {
      console.log("newVal", newVal, oldVal);
      if (newVal.length && newVal[0].items.length) {
        const item = newVal[0].items[0];
        this.setPdf(item);
        // this.setCurrent(0, item);
      }
    },
  },
  data() {
    return {
      previewData: {},
      showArticle: true,
      searchItemsForm: {
        pageSize: 10,
        pageNum: 1,
        name: "",
        type: 1,
      },
      loading: false,
      itemsTableList: [],
      showItemsTable: false,
      total: 0,
      selectedItem: [],
      itemArticleId: "",
      itemSurveyId: "",
      isItemArticle: true,
      editIndex: null,
    };
  },
  created() {},
  mounted() {
    if (this.value.length === 0 && !this.isPreview) {
      // 自动插入一条
      this.handleAddTask();
    }
    if (this.value.length && this.value[0].items.length) {
      const item = this.value[0].items[0];
      this.setPdf(item);
    }
  },
  unMounted() {
    this.showArticle = true;
    this.previewData = {}
  },
  methods: {
    getTaskTimeRange(item, index) {
      let maxNum = this.maxDays;
      if (index !== this.value.length - 1) {
        maxNum = this.maxDays - (this.value.length - (index + 1));
      }
      const range = {
        min: index === 0 ? 0 : this.value[index - 1].lagNumber + 1,
        max: index === this.value.length - 1 ? this.maxDays : maxNum,
      };
      // console.log(`${index}----range`, range);
      return range;
    },
    changeNumber(item, index) {
      this.computNumAdd(item, index);
      this.computNumRemove(item, index);
    },
    computNumAdd(item, index) {
      const currentIndexNum = this.value[index].lagNumber;
      let maxNum = this.maxDays;
      if (index !== this.value.length - 1) {
        maxNum = this.maxDays - (this.value.length - (index + 1));
      }
      // console.log("maxNum!!!", maxNum);
      if (index < this.value.length - 1 && this.value[index + 1].lagNumber <= maxNum) {
        this.value[index + 1].lagNumber = currentIndexNum + 1;
        this.computNumAdd(item, index + 1);
      }
    },
    computNumRemove(item, index) {
      if (index !== 0) {
        const currentIndexNum = this.value[index].lagNumber;
        const lastIndexNum = this.value[index - 1].lagNumber;
        if (lastIndexNum >= currentIndexNum) {
          this.value[index - 1].lagNumber = currentIndexNum - 1;
          this.computNumRemove(item, index - 1);
        }
      }
    },
    handleAddTask() {
      if (this.isPreview === "preview") return false;
      this.$emit("input", [
        ...this.value,
        {
          lagNumber: undefined,
          lagUnit: this.periodUnitMap.day,
          items: [],
        },
      ]);
    },
    handleDelTask(index) {
      if (this.isPreview === "preview") return false;
      if (index === 0) {
        return this.$message.warning("至少包含一个任务");
      }
      const taskList = [...this.value];
      taskList.splice(index);
      this.$emit("input", taskList);
    },
    // 修改添加待办事项
    handleAddTodo(index) {
      this.$emit("selectTodo", index);
    },
    // 查看预览待办事项
    handlePrewviewItem(item) {
      if (item.targetType === this.todoItemTypeMap.article) {
        this.$refs.previewArticle.open(item.targetId);
      } else {
        this.$refs.previewSurvey.open(item.surveyId);
      }
    },
    // 删除待办事项
    hanldeDelTodoItem(todoIndex, taskIndex) {
      const taskList = [...this.value];
      taskList[taskIndex].items.splice(todoIndex, 1);
      this.$emit("change", taskList);
    },
    setCurrent(index, row) {
      this.$nextTick(() => {
        this.$refs["previewTemplateTable" + index][0].setCurrentRow(row);
      });
    },
    clearCurrentRow() {
      // 清除高亮
      this.$nextTick(() => {
        console.log(this.$refs);
        this.value.forEach((table, index) => {
          console.log(this.$refs["previewTemplateTable" + index]);
          this.$refs["previewTemplateTable" + index][0].setCurrentRow(null);
        });
      });
    },
    handleCurrentChange(index, row) {
      console.log('index===', index)
      this.setPdf(row);
    },
    setPdf(row) {
      if (!row) {
        this.previewData = {}
        return
      }
      this.previewData = row
      // console.log('row=', row)
      // const item = row;
      // this.articleId = "";
      // this.surveyId = "";
      // if (item.targetType === this.todoItemTypeMap.article) {
      //   this.showArticle = true;
      //   this.articleId = item.targetId;
      // } else if(item.targetType === this.todoItemTypeMap.survey) {
      //   this.showArticle = false;
      //   this.surveyId = item.surveyId;
      // }
    },
    // 确定按钮
    sureSelectedItem() {
      this.$emit("save");
    },
    cancel() {
      this.$emit("closeEditDialog");
    },
  },
};
</script>

<style lang="scss" scoped>
.follow-task {
  display: flex;
  height: 75vh;
  .el-row {
    height: 100%;
    .el-card {
      height: 100%;
    }
    ::v-deep .el-card__body {
      overflow: auto;
      height: 100%;
    }
    .el-steps {
      height: auto;
      min-height: 80%;
    }
  }
  .el-col {
    height: 100%;
  }

  ::v-deep .el-step__description {
    padding-right: 0 !important;
    margin-bottom: 30px !important;
  }
  ::v-deep .el-table .el-table__header .el-table-column--selection .el-checkbox {
    display: none !important;
  }
  ::v-deep .el-table .cell::before {
    content: "";
    text-align: center;
    line-height: 37px;
  }
  .itemsTable-box {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
}
</style>

