<template>
  <div class="app-container">
    <el-card>
      <el-button type="primary" icon="el-icon-plus" @click="handleAddContent" v-if="checkPermission(['test'])"
        >
        新增
      </el-button>
      <el-select v-model="queryType" placeholder="查询类型" clearable style="width: 200px" class="filter-item">
          <el-option label="按年查询" value="0" />
          <el-option label="按月查询" value="1" />
      </el-select>
      <el-date-picker
          v-if="queryType=='0'"
          v-model="listQuery.year"
          type="year"
          value-format="yyyy"
          placeholder="查询年份"
        >
      </el-date-picker>
      <el-date-picker
          v-if="queryType=='1'"
          v-model="queryDateMonth"
          type="month"
          value-format="yyyy-MM"
          placeholder="查询年月"
          @change="queryMonthChange"
        >
      </el-date-picker>
        <el-button 
        class="filter-item" 
        type="primary" 
        icon="el-icon-search" 
        @click="handleSearch">搜索</el-button>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-table
        v-loading="listLoading"
        :data="contentList.results"
        border
        fit
        stripe
        :span-method="objectSpanMethod"
        highlight-current-row
        max-height="600"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="月份" width='160'>
          <template slot-scope="scope">{{ scope.row.month }}月月度交流会</template>
        </el-table-column>
        <el-table-column label="资料名称" min-width="110">
          <template slot-scope="scope" v-if="scope.row.file_.file">
            <!-- <a v-if="scope.row.file_.file.indexOf('.pdf')>-1 " :href="`/static/build/generic/web/viewer.html?file=${scope.row.file_.file}`" target="view_window" class="flv">
              <el-link type="primary">{{ scope.row.name }}</el-link>
            </a> -->
            <el-link :href="scope.row.file_.file" type="primary">{{ scope.row.name }}</el-link>
          </template>
          <template slot-scope="scope" v-else>{{ scope.row.name }}</template>
        </el-table-column>
         <el-table-column label="资料简介"  >
          <template slot-scope="scope">{{ scope.row.description }}</template>
        </el-table-column>
        <el-table-column label="创建时间" width='160'>
          <template slot-scope="scope">{{ scope.row.create_time }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="120px"
          fixed="right"
          v-if="checkPermission(['test'])"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            />
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="contentList.count > 0"
        :total="contentList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <div id="example1"></div>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑文件' : '新增文件'"
    >
      <el-form
        ref="Form"
        :model="Content"
        label-width="80px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="Content.name" placeholder="文件名称" />
        </el-form-item>
        <el-form-item label="月份" prop="dateMonth">
          <el-date-picker
            v-model="Content.dateMonth"
            type="month"
            value-format="yyyy-MM"
            placeholder="时间"
            style="width: 100%;"
            @change="monthChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文件描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            v-model="Content.description"
            placeholder="文件描述"
          />
        </el-form-item>
        <el-form-item label="文件上传" prop="file" v-if="dialogVisible">
          <el-upload
          ref="upload"
          :action="upUrl"
          :on-preview="handlePreview"
          :on-success="handleUpSuccess"
          :on-remove="handleRemove"
          :headers="upHeaders"
          :file-list="fileList"
          :limit="1"
          accept=".pdf"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
  
</template>
<script>
import {getPolicyList,createPolicy,deletePolicy, updatePolicy} from "@/api/policy";
import pdf from 'pdfobject';
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { upUrl, upHeaders } from "@/api/file";
const defaultContent = {
  cate:'月度交流',
  name: "",
  description: "",
  file:null,
  year:2023,
  month:12,
  dateMonth:'',
};
export default {
  components: { Pagination, Treeselect },
  data() {
    return {
      queryDateMonth:'',
      queryType:'0',
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      fileList:[],
      Content: defaultContent,
      listLoading:false,
      dialogVisible: false,
      listQuery: {
        page: 1,
        cate:'月度交流',
        search:'',
        page_size: 20,
        year:''
      },
       contentList: {
        count:0
      },
      dialogType: "new",
      rule1: {
        dateMonth:[{required:true,message:'请选择月份',trigger:'blur'}],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      PdfWebPath: '',
      pdfTop: 40,
      showTips: true,
      OrderIndexArr:[],
    };
  },
  computed: {},
  watch: {
    filterOrgText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    document.onselectstart = function() {
      return false
    }
    // 禁止鼠标右键功能
    document.oncontextmenu = function() {
        return false
    }
    this.getList();
  
  },
  mounted(){
    let date = new Date();
    this.listQuery.year = date.getFullYear()+'';
  },
  methods: {
    handlePaste(event) {
      // 禁用鼠标右键
      event.preventDefault()
      return false
    },
    fileClick(row){
      var options = {
        height: '10000px',
        pdfOpenParams: {
          scrollbars: '0',
          toolbar: '1',
          statusbar: '1'
        } // 禁用工具栏代码
      }
      pdf.embed(row.file_.file,'#pdf-content', options)
      // pdf.embed(response.WebPath,'#pdf-content', options)
    },
    handleSearch(){
        this.getList(); 
    },
    handlePreview(file) {
      if ("url" in file) {
        window.open(file.url);
      } else {
        window.open(file.response.data.path);
      }
    },
    handleUpSuccess(res, file, filelist) {
      this.Content.file = res.data.id;
      
    },
    handleRemove(file, filelist){
      this.Content.file = null;
    },
    checkPermission,

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getList() {
      this.contentList.results = [];
      getPolicyList(this.listQuery).then((response) => {
        if (response.data) {
          let list = response.data.results;
          this.contentList.results = list;
          this.contentList.count =  response.data.count;
          let OrderObj = {};
          list.forEach((element, index) => {
            element.rowIndex = index
            if (OrderObj[element.month]) {
              OrderObj[element.month].push(index)
            } 
            else {
              OrderObj[element.month] = []
              OrderObj[element.month].push(index)
            }
        })
        var indexarrs=[];
        for (let k in OrderObj) {
          if (OrderObj[k].length > 1) {
            indexarrs.push(OrderObj[k])
          }
        }
        this.OrderIndexArr=indexarrs;
        }
      });
    },
    objectSpanMethod({row,column,rowIndex,columnIndex}) {
        if (columnIndex == 1) {
          for (let i = 0; i < this.OrderIndexArr.length; i++) {
            let element = this.OrderIndexArr[i];
            for (let j = 0; j < element.length; j++) {
              if (rowIndex == element[j]) {
                if (j == 0) {
                  return {
                    rowspan: element.length,
                    colspan: 1
                  }
                } else {
                  return {
                    rowspan: 0,
                    colspan: 0
                  }
                }
              }
            }
          }
        }
        
      },

    handleAddContent() {
      this.Content = Object.assign({}, defaultContent);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.fileList=[]
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.Content = Object.assign({},scope.row); // copy obj
      this.Content.dateMonth = scope.row.year+'-'+scope.row.month;
      this.dialogType = "edit";
      this.dialogVisible = true;
      if (this.Content.file) {
        this.fileList = [
          {
            name:this.Content.file_.name,
            url: this.Content.file,
          },
        ];
      }
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deletePolicy(scope.row.id);
          this.getList();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    monthChange(val){
      let arr = val.split('-');
      this.Content.year = parseInt(arr[0]) ;
      this.Content.month = parseInt(arr[1]);
    },
    queryMonthChange(val){
      let arr = val.split('-');
      this.listQuery.year = parseInt(arr[0]) ;
      this.listQuery.month = parseInt(arr[1]);
    },
    async confirm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            console.log(this.Content)
            updatePolicy(this.Content.id, this.Content).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("编辑成功");
              }
            });
          } else {
            createPolicy(this.Content).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("新建成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
