<!--
 * @Author: guanxiaoyan guanxiaoyan@pb-station.com
 * @Deion:
 * @Date: 2023-12-25 09:51:03
 * @LastEditors: guanxiaoyan guanxiaoyan@pb-station.com
 * @LastEditTime: 2024-01-03 10:53:08
 * @FilePath: /followUp-operate/src/views/workStation/followTask/CreateFollowPlan/components/TodoItemSelector/index.vue
-->
<template>
  <div class="todo-selector" v-show="visiable">
    <div class="sf-title mb5">添加待办事项</div>
    <el-row>
      <el-col :span="12">
        <el-card>
          <el-form ref="form" inline>
            <el-form-item label="类型" prop="targetType" placeholder="请选择" style="margin: 0">
              <el-select size="mini" v-model="queryParams.targetType" @change="getList">
                <el-option v-for="item in todoItemTypeEnum.options.filter(
                (item) => item.value !== todoItemTypeMap.remark
              )" :label="item.label" :value="item.value" :key="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="name" style="margin: 0; margin-left: 20px">
              <el-input size="mini" v-model="queryParams.name" style="width:200px"
                placeholder="请输入待办事项名称进行搜索"></el-input>
            </el-form-item>
            <el-form-item style="margin-left:20px">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
                搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="table">
            <el-table :data="tableList" ref="todoTableRef" border class="mt20" v-loading="loading"
              highlight-current-row @current-change="handleCurrentChange(index,$event)">
              <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="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
            <div class="footer" style="margin-top:50px">
              <el-button @click="handleCancel">取 消</el-button>
              <el-button type="primary" @click="handleConfirm">确定</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="11" :offset="1" style="height:100%;min-height:500px;flex:1;">
        <!-- <div class="sf-title mb5">事项预览</div> -->
        <el-card>
          <ArticlePreview v-if="selectPreview.targetType === todoItemTypeMap.article" style="height: 75vh; overflow-y: auto"
            :articleId="selectPreview.targetId" :isTemp="false"/>
          <DWViewer v-else-if="selectPreview.targetType === todoItemTypeMap.survey" style="height: 75vh; overflow-y: auto" :url="url" />
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import ArticlePreview from "@/components/ArticlePreview";
import DWViewer from "@/components/DWViewer";
import { todoItemTypeMap } from "@/constant";
import { surveyPageList } from '@/api/hospital/followupManage/followupSurvey'
import { remindTemplateListApi } from '@/api/hospital/remindManage/remindList'
import { getArticlePageApi } from '@/api/hospital/followupManage/followupPlan'
export default {
  enums: ["todoItemTypeEnum", "todoItemTypeMap"],
  components: {
    ArticlePreview,
    DWViewer,
  },
  props: {
    defaultValue: {
      type: Array,
      default: () => [],
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    visiable: {
      type: Boolean
    }
  },
  data() {
    return {
      queryParams: {
        targetType: todoItemTypeMap.survey,
        name: "",
        pageNum: 1,
        pageSize: 10,
      },
      tableList: [],
      selectList: [],
      loading: false,
      total: 0,
      defaultCheckIds: null,
      surveyId: "",
      articleId: "",
      showArticle: false,
      // 当前选中的数据
      selectPreview: {}
    };
  },
  computed: {
    url() {
      return `${process.env.VUE_APP_SURVEY_PREFIX}/survey/diaowen-m.html?surveyId=${this.selectPreview.targetId}&sid=&tag=p-auth-0&t=${new Date().getTime()}`;
    },
  },
  watch: {},
  mounted() {
    this.getList();
  },
  methods: {
    open(defaultValue = []) {
      this.selectList = [...defaultValue];
      this.getList();
      this.defaultCheckIds = this.getCheckedIds(this.selectList);
      this.$emit('update:visiable', true)
      this.promise = {};
      return new Promise((resolve, reject) => {
        this.promise.resolve = resolve;
        this.promise.reject = reject;
      });
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.targetType === this.todoItemTypeMap.survey;
      this.queryParams.name = "";
    },
    getList() {
      this.tableList = [];
      this.loading = true;
      let apiMethod = ''
      if (this.queryParams.targetType === this.todoItemTypeMap.survey) {
        apiMethod = surveyPageList
      } else if (this.queryParams.targetType === this.todoItemTypeMap.article) {
        apiMethod = getArticlePageApi
      } else if (this.queryParams.targetType === this.todoItemTypeMap.remind) {
        apiMethod = remindTemplateListApi
      }
      apiMethod(this.queryParams).then(async (res) => {
          if (res?.data?.list.length) {
            const list = res.data.list;
            list.forEach((item) => {
              item.targetName = item.name;
              item.targetType = this.queryParams.targetType;
              item.targetId = item.id;
            });
            this.tableList = list || [];
            this.total = Number(res.data.page.total);
            // 默认选中第一条
            const item = this.tableList[0];
            await this.$nextTick()
            this.$refs.todoTableRef?.setCurrentRow(item);
            this.setPdf(item);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getCheckedIds(list) {
      return list
        .map((item) => item.targetId)
        .sort()
        .join(",");
    },
    reset() {
      this.$emit('update:visable', false)
      this.queryParams.name = "";
      this.targetType = this.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=', row)
      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);
        }
      }
    },
    // 预览pdf
    setPdf(row) {
      const item = row;
      // this.articleId = "";
      // this.surveyId = "";
      // console.log('setPdf=', row)
      this.selectPreview = row
      // 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;
      // }
    },
    handleCurrentChange(index, row) {
      console.log('TodoItemSelector=handleCurrentChangeindex=', index)
      console.log('row', row)
      if (!row) {
        return
      }
      this.setPdf(row);
    },
  },
};
</script>
<style lang="scss" scoped>
.todo-selector {
  .tree-menus {
    border: 1px solid #dfe4ed;
    height: 200px;
    border-radius: 4px;
    overflow-y: auto;
  }
  .footer {
    text-align: center;
  }
}
</style>
