<template>
  <div class="container">
    <!-- 查询配置 -->
    <div style="padding: 0px 20px">
      <div ref="lxHeader">
        <LxHeader icon="md-apps" text="内容管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
          <div slot="content"></div>
          <slot>
            <div>
              <Input style="width: 200px; margin-right: 10px" v-model="searchFields.KeyWord" placeholder="关键字搜索" />
              <Button type="primary" @click="load" style="margin-left: 10px">查询</Button>
              <Button type="primary" @click="edit()" style="margin-left: 10px">新增</Button>
            </div>
          </slot>
        </LxHeader>
      </div>

      <el-row :gutter="20">
        <el-col :span="3">
          <Card class="box-card">
            <div style="overflow: auto;" :style="{height:tableHeight-32+'px'}">
              <el-scrollbar style="flex: 1">
                <el-tree class="filter-tree" highlight-current @node-click="menuClick" accordion :data="options"
                  :props="defaultProps" ref="tree">
                </el-tree>
              </el-scrollbar>
            </div>
          </Card>
        </el-col>
        <el-col :span="21">
          <div class="table-tree">
            <el-table :data="tableData" class="v-table" :height="tableHeight" border style="width: 100%">
              <el-table-column type="index" align="center">
              </el-table-column>
              <el-table-column prop="menu" align="left" label="归属模块" width="180">
                <template slot-scope="scope">
                  <el-tag>{{scope.row.menu?scope.row.menu.name:"无"}}</el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="title" label="标题">
                <template slot-scope="scope">
                  <el-link type="primary" @click="show(scope.row)">{{scope.row.title}}</el-link>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" align="center" label="创建日期" width="160">
              </el-table-column>
              <el-table-column prop="admin" align="center" label="创建人" width="120">
                <template slot-scope="scope">
                  {{scope.row.admin?scope.row.admin.name:""}}
                </template>
              </el-table-column>
              <el-table-column prop="department" align="center" label="创建人科室" width="120">
                <template slot-scope="scope">
                  {{scope.row.department?scope.row.department.name:""}}
                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                  <Button ghost size="small" @click="edit(scope.row)" type="primary"
                    style="margin-left: 10px;">编辑</Button>
                  <Button ghost size="small" @click="del(scope.row)" type="error" style="margin-left: 10px;">删除</Button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination background @current-change="handleCurrentChange" :current-page="pagination.page"
                :page-size="pagination.page_size" layout="total,prev, pager, next" :total="pagination.total">
              </el-pagination>
            </div>
          </div>

        </el-col>
      </el-row>
      <el-dialog title="内容编辑" :visible.sync="dialogFormVisible" fullscreen width="90%">
        <div class="dialogConcent" :style="{height:clientHeight+'px'}">
          <el-scrollbar style="flex: 1">
            <el-form :model="form" :rules="rules" ref="form" label-position="right" :label-width="formLabelWidth">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请填写标题" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="模块" prop="menu_id">
                <treeselect :multiple="false" :options="options" :normalizer="normalizer" placeholder="请选择模块"
                  v-model="form.menu_id" />
              </el-form-item>

              <el-form-item label="内容" prop="content">
                <div style="width: 99.9%;">
                  <el-input v-model="form.content" :rows='8' type='textarea' placeholder="请输入备注内容" clearable
                    ></el-input>
                  <!-- <tinymce v-model="form.content" ref="tiny" :height="300" /> -->
                </div>
              </el-form-item>
              <el-form-item label="附件" prop="file_list">
                <el-upload class="upload-demo" :on-success="handlesuccess" :data="uploadOther" :action="action"
                  :on-remove="handleRemove" :before-remove="beforeRemove" :on-exceed="handleExceed"
                  :file-list="fileList">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-scrollbar>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('form')">取 消</el-button>
          <el-button type="primary" v-preventReClick @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>

     </div>
    <viewInfo ref="viewInfo"></viewInfo>
  </div>
</template>

<script>
  import {
    getToken
  } from '@/utils/auth'
  import viewInfo from './components/viewInfo.vue'
  import LxHeader from "@/components/LxHeader/index.vue";
  import Treeselect from "@riophae/vue-treeselect";
  // import Tinymce from '@/components/Tinymce'
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {
    save,
    listarticle,
    store,
    del,
    get
  } from "@/api/lawsfile/article.js";
  import {
    listregulation
  } from "@/api/lawsfile/regulation.js";

  export default {
    components: {
      LxHeader,
      Treeselect,
      // Tinymce,
      viewInfo
    },
    created() {
      var that = this;
      that.fileList = [];
      that.uploadOther.token = getToken();
      that.initLoad();
      that.loadregulation();
      that.load();
    },
    mounted() {},
    data() {
      return {
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        uploadOther: {
          token: ""
        },
        menu_children:[],
        dialogViewVisible: false,
        dialogFormVisible: false,
        formLabelWidth: "120px",
        form: {
          title: "",
          menu_id: null,
          content: "",
          file_list: "",
          type: 1
        },
        options: [],
        normalizer(node) {
          return {
            id: node.id,
            label: node.name,
            children: node.children,
          }
        },
        rules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }],
          menu_id: [{
            required: true,
            message: '请选择归属的模块',
            trigger: 'blur'
          }]
        },
        tableHeight: 0,
        //查询条件字段
        searchFields: {
          KeyWord: "",
          menu_id: ""
        },
        tableData: [],
        pagination: {
          page: 1,
          page_size: 15,
          total: 0
        },
        clientHeight: 0,
        fileList: [],
        filterText: ""
      }
    },
    methods: {
      menuClick(data) {
        let that = this;
        this.menu_children = []
        this.menu_children.push(data)
        if(data.children.length>0){
          this.hasChildren(data)
        }
        let menuids = ''
        if(this.menu_children.length>0){
          this.menu_children.map(item=>{
            menuids+=item.id+','
          })
          menuids = menuids.slice(0,-1)
        }
        that.searchFields.menu_id = menuids;
        that.load();
      },
      hasChildren(arr){
        if(arr.children.length>0){
          arr.children.map(item=>{
            this.menu_children.push(item)
            if(item.children.length>0){
              this.hasChildren(item)
            }
          })
        }else{
          this.menu_children.push(arr)
        }
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      initLoad() {
        var that = this;
        var clientHeight = document.documentElement.clientHeight
        var lxHeader_height = 96.5; //查询 头部
        var paginationHeight = 37; //分页的高度
        var topHeight = 50; //页面 头部
        let tableHeight = clientHeight - lxHeader_height - topHeight - paginationHeight - 20;
        that.tableHeight = tableHeight;
      },
      handleCurrentChange(val) {
        this.pagination.page = val;
        this.load();
      },
      loadregulation() {
        var that = this;
        let type = parseInt(this.$route.path.split("_")[1]);
        let type1 = parseInt(this.$route.path.split("_")[2]);
        // if(type1){
        //   type = type1
        // }else{
        //   // if(type==10){
        //   //   type = 10
        //   // }else{
        //     type  =  '2,1,3,12'
        //   // }
        // }
        listregulation(1, type).then(response => {
          that.options = response;
        }).catch(error => {
          console.log(error)
          //reject(error)
        })
      },
      load() {
        var that = this;
        let type = parseInt(this.$route.path.split("_")[1]);
        let type1 = parseInt(this.$route.path.split("_")[2]);
        // if(type1){
        //   type = type1
        // }else{
        //   // if(type==10){
        //   //   type = 10
        //   // }else{
        //     type  =  '2,1,3,12'
        //   // }
        // }

        listarticle(that.pagination.page, that.searchFields.menu_id, that.searchFields.KeyWord, that.pagination
          .page_size, type).then(response => {
          that.tableData = response.data;
          that.pagination.total = response.total;
        }).catch(error => {
          console.log(error)
          //reject(error)
        })
      },
      del(obj) {
        var that = this;
        if (obj) {
          this.$Modal.confirm({
            title: '确认要删除数据？',
            onOk: () => {
              del(obj.id).then(response => {
                this.$Message.success('操作成功');
                that.load();
              }).catch(error => {
                console.log(error)
                reject(error)
              })
            },
            onCancel: () => {
              //this.$Message.info('Clicked cancel');
            }
          });
        }
      },
      show(obj) {
       this.$refs.viewInfo.dialogViewVisible = true;
       this.$refs.viewInfo.getinfo(obj.id);

      },
      info(obj) {
        var that = this;
        get(obj.id).then(response => {
          let result = Object.assign(that.form, response);
          that.form = result;
          let _files = [];
          for (var _mod of result.regulation_article_file) {
            console.log(_mod.files)
            let mod = _mod.files;
            let m = Object.assign({}, mod.files);
            m.name = mod.original_name;
            _files.push(m);
          }
          that.fileList = _files;
          // that.$refs.tiny.setContent(result.content);
        }).catch(error => {
          //reject(error)
        })
      },
      edit(obj) {
        var that = this;
        this.form = this.$options.data().form;
        this.fileList = [];

        this.form.type = parseInt(this.$route.path.split("_")[1]);
        this.clientHeight = document.documentElement.clientHeight - 84 - 110;
        if (obj) {
          that.info(obj);
        } else {
          that.$nextTick(function(){

              // that.$refs.tiny.setContent("");

          })
        }
        this.dialogFormVisible = true;
      },
      submitForm(formName) {
        var that = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (that.form.id) {
              that.form.regulation_article_id = that.form.id;
              save(that.form).then(response => {
                //console.log(response)
                this.$Message.success('操作成功');
                that.load();
                that.dialogFormVisible = false;

              }).catch(error => {
                //reject(error)
              })
            } else {
              store(that.form).then(response => {
                //console.log(response)
                this.$Message.success('操作成功');
                that.load();
                that.dialogFormVisible = false;
              }).catch(error => {
                //reject(error)
              })
            }
            that.fileList = [];
          } else {
            this.$Message.error('数据校验失败');
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleRemove(file, fileList) {
        console.log(fileList);
        let listUrl = [];
        for (var m of fileList) {
          if (m.response)
            listUrl.push(m.response.id);
          else
            listUrl.push(m.id);
        }
        this.form.file_list = listUrl;
      },
      handleExceed(files, fileList) {},
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handlesuccess(response, file, fileList) {
        console.log(fileList);
        let listUrl = [];
        for (var m of fileList) {
          if (m.response)
            listUrl.push(m.response.id);
          else
            listUrl.push(m.id);

        }
        this.form.file_list = listUrl;
      },
      resetForm(formName) {
        var that = this;
        this.$refs[formName].resetFields();
        that.dialogFormVisible = false;
      }
    }
  };
</script>

<style>
  .dialogConcent {
    overflow-y: auto;
  }
  .el-tree-node__label{
    text-wrap:wrap;
  }
  .el-tree-node__content{
    height:auto;
  }
</style>
