<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="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>
        <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-row :gutter="10" class="mb8">
      <el-col :span="1.5">

      </el-col>
    </el-row>

    <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="setPreview(scope.row)">{{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="随访问卷ID" prop="surveyId" :show-overflow-tooltip="true" />
      <el-table-column align="center" label="最后编辑时间" prop="updateTime" :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="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="操作" 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="handleCopy(scope.row)">
            复制
          </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" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <CrudPopup ref="crud" />
    <SurveyPreviewPopup ref="previewSurvey" />
  </div>
</template>

<script>
import ApiButton from "@/components/ApiButton/index.vue";
import TreeDept from "@/components/TreeDept";
import {
  surveyPageList,
  delSurvey,
  getMedicalLabel,
  offlineSurvey,
  publishSurvey,
  batchPublishSurveyApi
} from "@/api/hospital";
import { surveyTempMap } from "@/constant";
import CrudPopup from "./components/CrudPopup/index.vue";
import SurveyPreviewPopup from "../../planManage/addPlan/components/SurveyPreviewPopup";

export default {
  name: "SurveyManage",
  enums: ["surveyTempMap", "surveyTempEnum"],
  components: {
    ApiButton,
    CrudPopup,
    TreeDept,
    SurveyPreviewPopup,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        deptIds: [],
        labelId: "",
        status: "",
      },
      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 batchPublishSurveyApi(ids)
        this.$message.success("发布成功！")
        this.getList();
      } catch (err) {
        console.log("err=", err);
      } finally {
        this.isPublishLoading = false;
      }
    },
    // 预览问卷
    setPreview(item) {
      this.$refs.previewSurvey.open(item.surveyId);
    },
    loadData() {
      this.getList();
    },
    async loadDisease(deptId) {
      const res = await getMedicalLabel({ deptId });
      this.diseaseList = res.data;
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      surveyPageList(this.addDateRange(this.queryParams, this.dateRange))
        .then((res) => {
          const { data: { list, page } } = res
          this.pageList = list || [];
          this.total = page?.total || 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增 */
    handleAdd() {
      this.$refs.crud.open().then(this.getList);
    },
    /** 编辑 */
    handleEdit(item) {
      this.$refs.crud.open(item).then(this.getList);
    },
    /** 复制 */
    handleCopy(item) {
      this.$refs.crud
        .open({
          ...item,
          name: item.name + " (复制)",
          id: undefined,
          // deptId: item.deptId,
          // deptName: item.deptName,
          // labelId: item.labelId,
          // name: item.name + " (复制)",
          // clientId: item.clientId,
          // surveyId: item.surveyId,
          // labelName: item.labelName,
          // status: item.status,
        })
        .then(this.getList);
    },
    // 发布下线
    handleSwitchStatus(item) {
      const isOnline = item.status === this.surveyTempMap.online;
      const fetch = async () => {
        if (isOnline) {
          await offlineSurvey(item.id);
        } else {
          await publishSurvey(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 delSurvey(item.id);
          this.$message.success("操作成功");
          this.getList();
        })
        .catch(() => { });
    },
  },
};
</script>
<style lang="scss" scoped></style>
