<template>
  <div class="index">
    <!-- <editor v-model="editorParams1.content"></editor> -->

    <!-- 搜索区 -->
    <div class="search_b u-fcb">
      <el-form class="form-inlines search_form" inline label-width="50px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标题:">
              <el-input v-model="searchForm.title" size="small" placeholder="文章标题" />
            </el-form-item>
            <el-form-item label="平台:">
              <el-input v-model="searchForm.platform" size="small" placeholder="平台" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作者:">
              <el-select v-model="searchForm.account" placeholder="请选择" size="small" clearable filterable>
                <el-option v-for="item in docoptions" :key="item.id" :label="item.showName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态:">
              <el-select v-model="searchForm.status" size="small" placeholder="请选择" clearable>
                <el-option label="未就绪" :value="1"></el-option>
                <el-option label="已就绪" :value="2"></el-option>
                <el-option label="已下载" :value="3"></el-option>
                <el-option label="已发布" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div class="btn_b u-f u-fdc u-ac">
        <el-button type="primary" size="mini" @click="begin">搜索</el-button>
      </div>
    </div>
    <div class="add_count_b u-f u-ac u-jcb">
      <div class="total_b">
        <el-button type="warning" size="mini" @click="readys" :disabled='selectDataList.length==0'>批量就绪</el-button>
      </div>
      <div>
        <el-button type="primary" size="mini" @click="add">添加</el-button>
      </div>
    </div>
    <!-- 表格区 -->
    <el-table ref="configurationTable" v-loading="tableLoading" :data="tableData" border :height="'100%'" size="small"
      :row-key="getRowKeys" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :reserve-selection="true" />
      <el-table-column prop="id" label="ID" show-overflow-tooltip />

      <el-table-column prop="nickname" label="封面" show-overflow-tooltip width="100">
        <template slot-scope="{ row }">
          <el-image style="width: 50px; height: 50px" :src="row.cover" :preview-src-list="[row.cover]" />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" show-overflow-tooltip />
      <el-table-column prop="des" label="简介" show-overflow-tooltip />
      <el-table-column prop="doctor.name" label="作者" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{row.account_names }}
        </template>
      </el-table-column>
      <el-table-column prop="platform" label="平台" show-overflow-tooltip />
      <el-table-column prop="create_time" label="时间" show-overflow-tooltip />
      <el-table-column prop="create_time" label="状态" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span :style="'color:'+(row.status!=1?'green':'red')">
            {{({1:'未就绪',2:'已就绪',3:'已下载',4:'已发布'})[row.status]}}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="text" v-if="row.status==1" @click="ready( row,2)">就绪</el-button>
          <el-button size="mini" type="text" v-if="row.status==2" @click="ready( row,1)">取消就绪</el-button>
          <el-button size="mini" type="text" :disabled="row.status!=1?true:false" @click="editm($index, row)">编辑
          </el-button>
          <el-button size="mini" type="text" :style="'color:'+(row.status!=1?'#C0C4CC':'red')"
            :disabled="row.status!=1?true:false" @click="deletem($index, row)">删除</el-button>
          <el-button size="mini" type="text" @click="copyArticle( row)">复制</el-button>
          <!-- <el-dropdown trigger="click" style="margin-left:10px">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item><span @click="editm($index, row)">编辑</span> </el-dropdown-item>

              <el-dropdown-item divided><span style="color:red" @click="deletem($index, row)">删除</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page_b">
      <div>
        <el-pagination :current-page="currentPage" :page-sizes="[15, 30, 50, 100]" :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="count" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
      <div />
    </div>

    <!-- 编辑 -->
    <formdialog ref="editformdialog" :title="setFormTit" :loading="adddialogLoading" :width="'900px'" :top="'0px'"
      :visibleshow.sync="formdialogVisible" is-confirm-btn :close-on-click-modal="false"
      @onConfirm="editconfirm('editform')" @onClose='closeEdit'>
      <el-form ref="editform" :model="editform" :rules="rules" label-width="80px" class="demo-ruleForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="editform.title" size="small" placeholder="文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="doctorId">
              <el-select v-model="editform.doctorId" placeholder="请选择" size="small" clearable filterable>
                <el-option v-for="item in docoptions" :key="item.id" :label="item.showName" :value="item.id">
                </el-option>
              </el-select>
              <!-- <el-input v-model="editform.account" size="small" placeholder="作者" /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="封面" prop="cover">
              <uploadimg :limit="1" :name="'file'" :img-url-list="articleCover" @onUpload="eqrcodeUpload" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="简介" prop="des">
              <el-input v-model="editform.des" type="textarea" :rows="2" placeholder="请输入内容" size="small" />
            </el-form-item>
            <el-form-item label="内容" required>
              <!-- <WangEditor ref="wangEditorRef1" :editor-params="editorParams1" /> -->

              <editor v-model="editform.content" :key="editIndex"></editor>

            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
    </formdialog>


  </div>
</template>

<script>
  import {
    getActicleList,
    getActicleDetail,
    edtiSubmit,
    delActicle,
    getAuthors,
    idsReady,
    copyArticle

  } from '@/api/admin'



  import uploadimg from '@/components/Upload/Image.vue'


  import formdialog from '@/components/formdialog/index.vue'

  // import WangEditor from '@/components/editor'

  import Editor from '@/components/editor/tinymce'
  export default {
    components: {
      formdialog,
      uploadimg,
      // WangEditor,
      Editor,
    },
    data() {
      return {
        searchForm: {
          status: '',
          title: '',
          account: '',
          platform: '',
        },
        tableLoading: false,
        tableData: [],
        currentPage: 1,
        pagesize: 15,
        count: 0,
        selectDataList: [], // 多选的数据
        clearForm: {},
        detaildata: {
          name: '',
          mark: ''
        },
        editform: {
          // id:'',//医生id
          account: '',
          des: '', // 简介
          title: '', // 名称
          content: '', //内容
          doctorId: '',
          cover: ''
        },


        formdialogVisible: false,
        dataildialogVisible: false,
        dialogLoading: false,
        adddialogLoading: false,

        rules: {
          // 校验规则
          title: [{
            required: true,
            message: '请填写文章标题',
            trigger: 'blur'
          }],

          des: [{
            required: true,
            message: '请填写简介',
            trigger: 'blur'
          }],
          doctorId: [{
            required: true,
            message: '请选择作者',
            trigger: 'blur'
          }],
          cover: [{
            required: true,
            message: '请上传封面',
            trigger: 'blur'
          }],
        },
        dataId: '', // 要编辑的数据ID
        setFormTit: '添加', // 弹窗标题

        province_options: [], // 省
        city_options: [], // 市
        district_options: [], // 区
        articleCover: [],
        detailimg: [],
        content: ``,
        options: [],
        zc_options: [],
        bm_options: [],
        disease_options: [],
        zzdoc_options: [],

        // 富文本
        editorParams1: {
          content: '', // 富文本内容
          placeholder: '请填写内容', // 富文本占位内容
          height: '300px' // 富文本最小高度
        },
        teamdialogVisible: false,
        ksProps: {
          label: "name",
          value: "id",
          children: 'submenu',
          multiple: true

        },
        jbProps: {
          label: "name",
          value: "id",
          children: 'submenu',
          multiple: true
        },
        docoptions: [],
        videoSrc: '',
        editIndex: 1

      }
    },
    computed: {},
    watch: {},
    created() {},
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    mounted() {
      this.begin()
      this.getAuthorList()
      this.objClone()
    },
    methods: {
      objClone() {
        this.clearForm = {
          ...this.editform
        }
      },

      begin() {
        this.currentPage = 1
        this.search()
      },
      search() {
        this.tableLoading = true
        getActicleList({
            limit: this.pagesize,
            page: this.currentPage,
            title: this.searchForm.title,
            status: this.searchForm.status,
            account: this.searchForm.account,
            platform: this.searchForm.platform,
          })
          .then((res) => {
            this.tableData = res.data
            this.count = res.count
          })
          .finally(() => {
            this.tableLoading = false
          })
      },
      getAuthorList() {
        getAuthors({})
          .then((res) => {
            this.docoptions = res.data
          })
          .finally(() => {})
      },
      add() {
        this.setFormTit = '添加'
        this.formdialogVisible = true
        this.editform = {
          ...this.clearForm
        }

        this.articleCover = []
        this.editIndex++
        this.$nextTick(() => {
          this.$refs.editform.clearValidate()
        })
      },
      closeEdit() {

      },


      handleSelectionChange(val) {
        this.selectDataList = val
      },
      getRowKeys(row) {
        return row.id // id为列表数据的唯一标识
      },
      handleSizeChange(val) {
        const that = this
        that.pagesize = val
        this.search()
      },
      handleCurrentChange(val) {
        const that = this
        that.currentPage = val
        this.search()
      },
      editm(index, row) {
        this.formdialogVisible = true
        this.$nextTick(() => {
          this.$refs.editform.clearValidate()
        })
        this.setFormTit = '编辑'
        this.adddialogLoading = true
        this.editIndex++
        getActicleDetail({
          id: row.id
        }).then((res) => {
          this.editform.id = res.data.id
          this.editform.title = res.data.title
          this.editform.des = res.data.des
          this.editform.content = res.data.content
          this.editform.cover = res.data.cover
          // this.editform.doctorId = res.data.account?res.data.account.split(',').map(Number):[]
          this.editform.doctorId = res.data.account?res.data.account - 0:''
          this.articleCover = res.data.cover ? [{
            url: res.data.cover
          }] : []

          // this.editform.departId = res.departIds[0] == '[' ? JSON.parse(res.departIds) : [];
          // this.editform.diseaseId = res.diseaseIds ? JSON.parse(res.diseaseIds) : []
          this.adddialogLoading = false
        })
      },
      copyArticle(row) {
        copyArticle({
            id: row.id,
          })
          .then((res) => {
            this.$message.success('复制成功！')
            this.search()
          })
          .catch((err) => {
            this.search()
          })
      },

      deletem(index, row) {
        this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            delActicle({
              id: row.id
            }).then((res) => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success'
              })
              this.search()
            })
          })
          .catch(() => {})
      },
      ready(row, status) {
        this.$confirm(`确认此文章${status==1?'取消就绪':'已准备就绪'}吗，是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            edtiSubmit({
              status: status,
              id: row.id
            }).then((res) => {
              this.$notify({
                title: '成功',
                message: '文章已就绪',
                type: 'success'
              })
              this.search()
            }).finally(f=>{
              
            })
          })
          .catch(() => {})
      },
      readys() {
        this.$confirm('确认批量文章已准备就绪吗, 准备就绪后将自动发布，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            let ids = this.selectDataList.map(a => a.id)
            idsReady({
              status: 2,
              id: ids
            }).then((res) => {
              this.$notify({
                title: '成功',
                message: '文章已就绪',
                type: 'success'
              })
              this.search()
            }).finally(f=>{

            })
          })
          .catch((err) => {})
      },
      detailconfirm() {},
      async editconfirm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.editform.content == '') return this.$message('请填写文章内容')
            this.adddialogLoading = true
            // const wangEditorRef1 = this.$refs.wangEditorRef1
            // if (wangEditorRef1 != null) {
            //   this.editform.content = wangEditorRef1.getEditorHtml()
            // }

            // let departIds = JSON.stringify(this.editform.departId)
            // let diseaseIds = JSON.stringify(this.editform.diseaseId)
            // let departId = this.editform.departId.map(a => a[a.length - 1]).toString()
            // let departPid = this.editform.departId.map((a) => a[0]).toString();
            // // this.editform.departId = departId
            // let diseaseId = this.editform.diseaseId.map(a => a[a.length - 1]).toString()

            // let docIds = this.editform.doctorId.toString()
            if (this.editform.id) {
              edtiSubmit({
                  id: this.editform.id,
                  title: this.editform.title, // 名称 
                  account: this.editform.doctorId,
                  des: this.editform.des, // 简介
                  content: this.editform.content, //内容
                  cover: this.editform.cover

                })
                .then((res) => {
                  this.$message.success('编辑文章成功！')
                  this.formdialogVisible = false
                  this.search()
                })
                .finally((f) => {
                  this.adddialogLoading = false
                }).catch(err => {
                })
            } else {
              copyArticle({
                  title: this.editform.title, // 名称 
                  account: this.editform.doctorId,
                  des: this.editform.des, // 简介
                  content: this.editform.content, //内容
                  cover: this.editform.cover
                })
                .then((res) => {
                  this.$message.success('新增文章成功！')
                  this.formdialogVisible = false
                  this.search()
                })
                .finally((f) => {
                  this.adddialogLoading = false
                }).catch(err => {
                })
            }

          } else {
            return false
          }
        })
      },

      eqrcodeUpload(a) {
        const imgs = []
        a.forEach((data) => {
          imgs.push(data.response.data)
        })
        this.articleCover = a
        this.editform.cover = a.length > 0 ? imgs[0].url : ''
      },

    }
  }
</script>
<style lang="scss" scoped>
  @import "../styles/style.scss";

  .index {
    .label {
      width: 150px;
      // border-style: dashed;
    }

    .el-dropdown-link {
      cursor: pointer;
      color: #1890ff;
      font-size: 12px;
    }

    .el-icon-arrow-down {
      font-size: 12px;
    }
  }
</style>
<style>
  .detail_item {
    border-bottom: 1px dashed #eee;
    padding: 0 10px;
    border-radius: 5px;
    line-height: 30px;
    min-height: 30px;
  }

  .el-upload-list__item {
    transition: none !important;

  }
</style>