<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="模板状态" prop="status">
        <el-select v-model="queryParams.status" clearable style="width: 240px">
          <el-option v-for="dict in surveyTempEnum.options" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="随访周期" prop="status">
        <PeriodSelector clearable style="width: 240px" defaultUnit=""
          :value="{ quantity: queryParams.periodNumber, unit: queryParams.periodUnit }" @change="
      queryParams.periodNumber = $event.quantity;
    queryParams.periodUnit = $event.unit;
    " />
      </el-form-item>

      <el-form-item label="应用科室" prop="deptIds">
        <TreeDept v-model="queryParams.deptIds" clearable style="width: 240px" :props="{ emitPath: true }"
          @change="queryParams.labelId = ''" />
      </el-form-item>

      <el-form-item label="应用疾病" prop="labelId">
        <el-select v-model="queryParams.labelId" filterable clearable style="width: 240px">
          <el-option v-for="item in diseaseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="模板名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入模板名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否自动匹配" prop="isMatch">
        <el-select v-model="queryParams.isMatch" placeholder="请选择" clearable style="width: 240px">
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <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 style="display: flex;justify-content: flex-end;padding-bottom: 8px;">
      <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">
        新增模板
      </el-button>
      <el-button :disabled="selectDatas.length <= 0" type="success" plain icon="el-icon-upload2" size="mini"
        @click="handlePublish" v-loading="isPublishLoading">发布模板</el-button>
    </div>

    <el-table v-loading="loading" :data="pageList" border @selection-change="selectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="isSelectable"></el-table-column>
      <el-table-column align="center" label="序号" type="index"
        :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1" width="120" />
      <el-table-column align="center" label="随访模板名称" prop="name" :show-overflow-tooltip="true"
        :class-name="'column-style-cursor'">
        <template slot-scope="scope">
          <div @click="setPreviewTemplate(scope.row)">{{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="随访模板ID" prop="id" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="应用疾病" prop="labelName" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="应用科室" prop="deptName" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="随访周期" prop="deptName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.periodNumber + periodUnitEnum.getLabel(scope.row.periodUnit) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="随访模板状态" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span :style="{ color: surveyTempEnum.enum[scope.row.status].color }">
            {{ surveyTempEnum.getLabel(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否自动匹配" prop="isMatch">
        <template slot-scope="scope">
          {{ scope.row.isMatch === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="随访单数" prop="followupDocumentSize" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleSwitchStatus(scope.row)"
            :disabled="scope.row.status === surveyTempMap.drafts"
            :class="[scope.row.status === surveyTempMap.online ? 'yellow-button' : 'green-button']">
            {{ scope.row.status === surveyTempMap.online ? "下线" : "发布" }}
          </el-button>
          <el-button size="mini" type="text" @click="handleEdit(scope.row)"
            :disabled="scope.row.status === surveyTempMap.online">
            编辑
          </el-button>

          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            :disabled="scope.row.status === surveyTempMap.online" class="red-button">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :sizes="[10]" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script>
import ApiButton from "@/components/ApiButton/index.vue";
import TreeDept from "@/components/TreeDept";
import {
  followUpPlanPageList,
  delFollowUpPlan,
  getMedicalLabel,
  switchPlanStatus,
  publishFollowUpPlanApi
} from "@/api/hospital";
import PeriodSelector from "../addPlan/components/PeriodSelector";
import { surveyTempMap } from "@/constant";

export default {
  name: "PlanManage",
  enums: ["surveyTempMap", "surveyTempEnum", "periodUnitEnum"],
  components: {
    ApiButton,
    PeriodSelector,
    TreeDept,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: "",
        labelId: "",
        deptIds: [],
        periodNumber: "",
        periodUnit: "",
        name: "",
        isMatch: null
      },
      pageList: [],
      diseaseList: [],
      selectDatas: [],
      isPublishLoading: false
    };
  },
  created() {
    this.loadData();
  },
  activated() {
    this.loadData();
  },
  watch: {
    "queryParams.deptIds"(val) {
      const deptId = val[1] || val[0];
      if (deptId) {
        this.loadDisease(deptId);
      } else {
        this.diseaseList = [];
      }
    },
  },
  methods: {
    isSelectable(row, index) {
      return ![surveyTempMap.online, surveyTempMap.drafts].includes(row.status);
    },
    selectionChange(value) {
      this.selectDatas = value || [];
    },
    async handlePublish() {
      this.isPublishLoading = true;
      const ids = this.selectDatas.map(item => item.id);
      try {
        await publishFollowUpPlanApi(ids)
        this.$message.success("发布成功！")
        this.getList();
      } catch (err) {
        console.log("err=", err);
      } finally {
        this.isPublishLoading = false;
      }
    },
    loadData() {
      this.getList();
    },
    getList() {
      this.loading = true;
      followUpPlanPageList(this.addDateRange(this.queryParams, this.dateRange))
        .then((res) => {
          const { data: { list, page } } = res
          this.pageList = list || [];
          this.total = Number(page.total) || 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    async loadDisease(deptId) {
      const res = await getMedicalLabel({ deptId });
      this.diseaseList = res.data;
    },

    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增患者 */
    handleAdd() {
      this.$router.push({ name: "AddPlan" });
    },
    /*预览模版 预览标记 'preview'*/
    setPreviewTemplate(item) {
      this.$router.push({ name: "EditPlan", params: { id: item.id, isPreview: 'preview' } });
    },
    /** 编辑 */
    handleEdit(item) {
      this.$router.push({ name: "EditPlan", params: { id: item.id } });
    },
    // 发布下线
    handleSwitchStatus(item) {
      const isOnline = item.status === this.surveyTempMap.online;
      const fetch = async () => {
        await switchPlanStatus(item.id);
        this.$message.success("操作成功");
        this.getList();
      };
      if (isOnline) {
        this.$modal
          .confirm(`是否确认下线？`)
          .then(fetch)
          .catch(() => { });
      } else {
        fetch();
      }
    },
    handleDelete(item) {
      this.$modal
        .confirm("是否确认删除？")
        .then(async () => {
          await delFollowUpPlan(item.id);
          this.$message.success("操作成功");
          this.getList();
        })
        .catch(() => { });
    },
  },
};
</script>
<style lang="scss" scoped></style>
