<template>
  <div class="todo-selector" v-show="visible">
    <div class="sf-title mb5">添加待办事项</div>
    <el-card>
      <el-form ref="form" inline>
        <el-form-item label="类型" prop="targetType" placeholder="请选择" style="margin: 0">
          <el-select v-model="targetType">
            <el-option
              v-for="item in targetTypeOptions"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="状态"
          prop="selectType"
          placeholder="请选择"
          style="margin: 0; margin-left: 20px"
        >
          <el-select v-model="queryParams.selectType">
            <el-option label="全部" value="" />
            <el-option label="已选" value="1" />
            <el-option label="未选" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="keyword" style="margin: 0; margin-left: 20px">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入待办事项名称进行搜索"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="table">
      <el-table :data="paginatedData" border class="mt20">
        <el-table-column align="center" width="300" property="targetName" label="名称" />
        <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="status" label="状态">
          <template slot-scope="scope">
            <div :class="[getCheckedStatus(scope.row) ? 'green-button' : 'gary-button']">{{ getCheckedStatus(scope.row) ? "已选" : "未选" }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-checkbox
              :value="getCheckedStatus(scope.row)"
              @change="handleCheckedChange(scope.row, $event)"
            ></el-checkbox>
            <el-button @click="handlePreview(scope.row)" class="ml10" size="mini" type="text">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="searchData.length > 0"
        :total="searchData.length"
        :page.sync="pageNum"
        :limit.sync="pageSize"
      />
      <el-card class="mt20">
        <div class="footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </el-card>
    </div>
    <ArticlePreviewPopup ref="previewArticle" />
    <SurveyPreviewPopup ref="previewSurvey" />
    <RemindPreviewPopup ref="previewRemind" />
  </div>
</template>

<script>
import { getPlanItemList } from "@/api/hospital";
import { todoItemTypeMap } from "@/constant";
import ArticlePreviewPopup from "../ArticlePreviewPopup";
import SurveyPreviewPopup from "../SurveyPreviewPopup";
import RemindPreviewPopup from "../RemindPreviewPopup";


export default {
  enums: ["todoItemTypeEnum", "todoItemTypeMap"],
  components: {
    ArticlePreviewPopup,
    SurveyPreviewPopup,
    RemindPreviewPopup
  },
  props: {
    defaultValue: {
      type: Array,
      default: () => [],
    },
    form: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      targetType: todoItemTypeMap.survey,
      queryParams: {
        selectType: "",
        keyword: "",
      },
      listMap: {
        [todoItemTypeMap.article]: 'allArticleList',
        [todoItemTypeMap.survey]: 'allSurveyList',
        [todoItemTypeMap.remind]: 'allRemindList'
      },
      allArticleList: null, // 文章
      allSurveyList: null, // 问卷数据
      allRemindList: null,
      selectList: [],
      visible: false,
    };
  },
  computed: {
    // 分页后数据
    paginatedData() {
      const startIndex = (this.pageNum - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.searchData.slice(startIndex, endIndex);
    },
    listField() {
      return this.listMap[this.targetType]
    },
    // 过滤查询的数据
    searchData() {
      const allData = this[this.listField] || []
      return allData.filter((item) => {
        // 未选/已选
        if (this.queryParams.selectType) {
          const checked = this.getCheckedStatus(item);
          if (this.queryParams.selectType === "1" && !checked) {
            return false;
          }
          if (this.queryParams.selectType === "2" && checked) {
            return false;
          }
        }
        // 按名称搜索
        if (this.queryParams.keyword) {
          return item.targetName.includes(this.queryParams.keyword);
        }
        return true;
      });
    },
    targetTypeOptions() {
      return this.todoItemTypeEnum.options.filter(item => item.value !== todoItemTypeMap.remark)
    }
  },
  watch: {
    targetType: "getList",
    "form.labelId"() {
      // 修改疾病，清空数据
      this.allArticleList = null;
      this.allSurveyList = null;
    },
  },
  methods: {
    open(defaultValue = []) {
      this.getList();
      this.selectList = [...defaultValue];
      this.defaultCheckIds = this.getCheckedIds(this.selectList);

      this.visible = true;
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
      });
    },
    getList() {
      if (this[this.listField]) return;
      getPlanItemList({ targetType: this.targetType, labelId: this.form.labelId }).then((res) => {
        this[this.listField] = res.data || [];
      });
    },
    getCheckedIds(list) {
      return list
        .map((item) => item.targetId)
        .sort()
        .join(",");
    },
    reset() {
      this.visible = false;
      this.queryParams.selectType = "";
      this.queryParams.keyword = "";
      this.targetType = todoItemTypeMap.survey;
    },
    handleCancel() {
      const newCheckedIds = this.getCheckedIds(this.selectList);
      const close = () => {
        this.reset();
        this.promise.reject();
      };
      if (this.defaultCheckIds !== newCheckedIds) {
        this.$modal.confirm("页面内信息尚未保存，是否继续确定退出？").then(close);
        return false;
      }
      close();
    },
    handleConfirm() {
      if (this.selectList.length === 0) {
        this.$message.error("至少选择一个待办事项");
        return;
      }
      this.reset();
      this.promise.resolve(this.selectList);
    },
    getCheckedStatus(row) {
      return this.selectList.some(
        (item) => item.targetId === row.targetId && item.targetType === row.targetType
      );
    },
    handleCheckedChange(row, checked) {
      console.log('row=', checked)
      const selectList = this.selectList.filter((item) => item.targetType === row.targetType);
      if (checked) {
        if (selectList.length >= 5) {
          this.$message.error("同一类型待办事项最多5个");
          return;
        }
        this.selectList.push({ ...row });
      } else {
        const index = this.selectList.findIndex(
          (item) => item.targetId === row.targetId && item.targetType === row.targetType
        );
        if (index > -1) {
          this.selectList.splice(index, 1);
        }
      }
    },
    // 预览文章/问卷
    handlePreview(item) {
      if (item.targetType === this.todoItemTypeMap.article) {
        this.$refs.previewArticle.open(item.targetId);
      } else if(item.targetType === this.todoItemTypeMap.survey) {
        this.$refs.previewSurvey.open(item.surveyId);
      } else if (item.targetType === this.todoItemTypeMap.remind) {
        this.$refs.previewRemind.open(item.targetId)
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.todo-selector {
  max-width: 1000px;
  .tree-menus {
    border: 1px solid #dfe4ed;
    height: 200px;
    border-radius: 4px;
    overflow-y: auto;
  }
  .footer {
    text-align: center;
  }
}
</style>
