<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" >
      <el-form-item label="医生" prop="doctorId">
      <el-select v-model="queryParams.doctorId" filterable placeholder="请输入医生名称" :filter-method="doctorMethod" clearable size="small">
        <el-option
          v-for="item in docuser"
          :key="item.name"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      </el-form-item>

      <el-form-item label="分类" prop="cateId">
     <el-select v-model="queryParams.cateId" placeholder="分类" clearable size="small">
       <el-option
         v-for="dict in cates"
         :key="dict.dictValue"
         :label="dict.dictLabel"
         :value="dict.dictValue"
       />
     </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
      <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
        <el-option
          v-for="dict in articleStatus"
          :key="dict.dictValue"
          :label="dict.dictLabel"
          :value="dict.dictValue"
        />
      </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>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="封面图" align="center" prop="imageUrl" >
         <template slot-scope="scope">
          <el-popover v-if="scope.row.imageUrl!=null"
            placement="right"
            title=""
            trigger="hover">
            <img slot="reference" :src="scope.row.imageUrl" width="50px">
            <img :src="scope.row.imageUrl" style="max-width: 150px;">
          </el-popover>
         </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="所属医生" align="center" prop="doctorName" />
      <el-table-column label="分类" align="center" prop="cateId">
        <template slot-scope="scope">
          <span v-for="category in cates"  v-if="category.dictValue == scope.row.cateId">
              {{ category.dictLabel }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="views" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
           <dict-tag :options="articleStatus" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150px"/>
      <el-table-column label="创建时间" align="center" prop="updateTime" width="150px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:article:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
            v-hasPermi="['his:article:edit']"
          >详情</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:article:remove']"
          >删除</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"
    />

    <!-- 添加或修改医生文章对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :rules="rules">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生" prop="doctorId" v-if="form.articleId==null">
          <el-select v-model="form.doctorId" filterable placeholder="输入医生名称搜索" :filter-method="doctorMethod" >
            <el-option
              v-for="item in docuser"
              :key="item.name"
              :label="`${item.name} (${item.position})`"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="cateId">
          <el-select v-model="form.cateId" placeholder="分类" clearable size="small">
              <el-option
                v-for="dict in cates"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
          </el-select>
        </el-form-item>

        <el-form-item label="封面图" prop="imageUrl">
           <el-upload
                      v-model="form.imageUrl"
                      class="avatar-uploader"
                      :action="uploadUrl"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" width="200px">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="视频地址" prop="videoUrl">
         <div>
             <el-upload
               ref="upload"
               class="upload-demo"
               :action="uploadUrl"
               :on-success="handleSuccess"
               :before-upload="beforeUpload"
               :limit="1"
               :accept="videoAccept"
             >
            <el-button size="small" type="primary">点击上传视频</el-button>
            </el-upload>
            <video v-if="form.videoUrl" :src="form.videoUrl" controls style="max-width: 400px; max-height: 400px;"></video>
         </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <Editor ref="myeditor"   @on-text-change="updateText"/>
        </el-form-item>
        <el-form-item label="浏览量" prop="views">
           <el-input-number v-model="form.views"  :min="0"  label="请输入浏览量"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="状态" clearable size="small">
            <el-option
              v-for="dict in articleStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
       <el-drawer
            :with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <articleDetails  ref="articleDetails" />
           </el-drawer>

  </div>
</template>

<script>
import {
  listdocuser,
  listArticle,
  getArticle,
  delArticle,
  addArticle,
  updateArticle,
  exportArticle,
  listDocList
} from '@/api/his/doctorArticle'
import articleDetails from '../../components/his/doctorArticleDetails.vue';
import { getAllArticleCateList} from "@/api/his/doctorArticleCate";
import Editor from '@/components/Editor/wang';
export default {
  name: "Article",
  components: { articleDetails,Editor },
  data() {
    return {
      videoUrl: "",
      videoAccept:"video/*",
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      show:{
              title:"医生文章详情",
              open:false,
            },
      cates: [],
      articleStatus: [],
      docuser:[],
      userName: {name:"1"},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生文章表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorId: null,
        imageUrl: null,
        cateId: null,
        title: null,
        content: null,
        views: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        doctorId: [
          { required: true, message: "所属医生不能为空", trigger: "submit" }
        ],
        cateId: [
          { required: true, message: "分类不能为空", trigger: "submit" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "submit" }
        ],
        imageUrl: [
          { required: true, message: "封面图不能为空", trigger: "submit" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "submit" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "submit" }
        ],
      }
    };
  },
  created() {

    this.getList();
    getAllArticleCateList().then(response => {
      this.cates = response.data;
    });
    this.getDicts("sys_doctor_article_status").then(response => {
      this.articleStatus = response.data;
    });

    listDocList().then(response => {
      this.docuser=response.rows;
    });

  },
  methods: {
    handleSuccess(response, file) {
          // 上传成功后的回调函数
          this.myloading.close();
          this.form.videoUrl = response.url;
          this.$refs.upload.clearFiles();
        },
    beforeUpload(file) {
      // 上传前的钩子函数，可以在这里对文件进行处理
      // 返回 false 则取消上传

      // 例如限制文件大小
      const isLt2M = file.size / 1024 / 1024 < 200;
      if (!isLt2M) {
        this.$message.error('上传视频文件大小不能超过 200MB!');
        return false;
      }
      this.myloading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

    },
    updateText(text){
      this.form.content=text
    },
    handleAvatarSuccess(res, file) {
      if(res.code==200){
           this.form.imageUrl=res.url;
           self.$forceUpdate()
       }else{
              this.msgError(res.msg);
            }
        },
    beforeAvatarUpload(file) {
       const isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
            this.$message.error('上传图片大小不能超过 1MB!');
          }
          return   isLt1M;
    },
    doctorMethod(rows){
      this.userName.name=rows;
      this.getlistdocuser();
    },
    getlistdocuser(){
        listdocuser(this.userName).then(response => {
          this.docuser=response.rows;
      });
    },
    handleDetails(row){
        this.show.open=true;
        setTimeout(() => {
             this.$refs.articleDetails.getDetails(row.articleId);
        }, 1);
    },
    /** 查询医生文章列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: null,
        doctorId: null,
        imageUrl: null,
        cateId: null,
        title: null,
        content: null,
        views: null,
        videoUrl:null,
        status: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加医生文章";
        setTimeout(() => {
          this.$refs.myeditor.setText("");
        }, 100);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const articleId = row.articleId || this.ids
      getArticle(articleId).then(response => {
      this.form = response.data;
      setTimeout(() => {
          if(this.form.content==null){
            this.$refs.myeditor.setText("");
          }else{
            this.$refs.myeditor.setText(this.form.content);
          }
        }, 1);
        this.open = true;
        this.title = "修改医生文章";
        this.form.status = String(this.form.status)

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.articleId != null) {
            updateArticle(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$confirm('是否确认删除医生文章编号为"' + articleIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delArticle(articleIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有医生文章数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportArticle(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
    .avatar-uploader .el-upload {
       border: 1px dashed #d9d9d9;
       border-radius: 6px;
       cursor: pointer;
       position: relative;
       overflow: hidden;
     }
     .avatar-uploader .el-upload:hover {
       border-color: #409EFF;
     }

     .avatar-uploader-icon {
       font-size: 28px;
       color: #8c939d;
       width: 150px;
       height: 150px;
       line-height: 150px;
       text-align: center;
     }
</style>


